// nova-werun/components/home/index.js
const Parse = getApp().Parse;
const company = getApp().globalData.company;
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        //屏幕高度
        statusBarHeight: 0, // 状态栏高度
        screenHeight: 0, // 屏幕高度
        customHeight: 0, // 自定义导航栏高度(如小程序右上角胶囊按钮)
        bottomNavHeight: 0, // 底部导航栏高度
        contentHeight: 0, // 可用内容高度
        contentpadding: 0, //顶部padding高度
        //选择
        rows: [{
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/3l5p1v041343137.png?imageView2/1/w/200/h/200',
                text: '签到打卡',
                url: '../../pages/home/signin/index'
            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/v6p4fm041343296.png?imageView2/1/w/200/h/200',
                text: '排行榜',
                url: '../../pages/home/ranking/index'
            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/mcu488041343362.png?imageView2/1/w/200/h/200',
                text: '转发分享',
                url: '../../pages/home/share/index'

            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/pqln61041343428.png?imageView2/1/w/200/h/200',
                text: '我的勋章',
                url: '../../pages/home/medal/index'
            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/9crt85041343498.png?imageView2/1/w/200/h/200',
                text: '步行',
                url: '../../pages/home/sport/sport-home/index',

            },

            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/71svpg041343669.png?imageView2/1/w/200/h/200',
                text: '跑步',
                url: '../../pages/home/sport/sport-home/index',
                active: 1
            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/uk13u1041343733.png?imageView2/1/w/200/h/200',
                text: '我的统计',
                url: '../../pages/home/statistics/index'
            },
            {
                image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241104/k1q4no034958681.png?imageView2/1/w/200/h/200',
                text: '积分',
                url: '../../pages/home/integral/index'
            },
        ],
        target: 0,
        sharList: [],

        address: "",
    },
    lifetimes: {

        detached: function () {
            // 在组件实例被从页面节点树移除时执行
        },
        attached: async function () {
            // 在组件实例进入页面节点树时执行
            // 计算
            const systemInfo = wx.getSystemInfoSync();
            const statusBarHeight = systemInfo.statusBarHeight || 0;
            const screenHeight = systemInfo.screenHeight || 0;
            const custom = wx.getMenuButtonBoundingClientRect();
            const customHeight = custom.height + 10 + 2 || 0;
            const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;

            const contentpadding = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth;
            const contentHeight = (screenHeight - bottomNavHeight - 50 - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
            this.setData({
                statusBarHeight,
                screenHeight,
                customHeight,
                bottomNavHeight,
                contentHeight,
                contentpadding
            });
            console.log('123', contentpadding);
            this.getWeRunData()
            this.gettarget()
            // this.order()
             this.Getlocation()

        },
    },

    /**
     * 组件的方法列表
     */
    methods: {
        //跳转
        gourl(e) {
            const url = e.currentTarget.dataset.url
            const active = e.currentTarget.dataset.active
            if (active) {
                wx.navigateTo({
                    url: `${url}?id=` + active // 目标页面的路径
                });
                console.log(active);
            } else {
                wx.navigateTo({
                    url: `${url}` // 目标页面的路径
                });
            }

        },
        //获取目标步数
        async gettarget() {
            const currentUser = Parse.User.current();
            let userquery = new Parse.Query('_User');
            userquery.equalTo('company', company);
            userquery.equalTo('objectId', currentUser.id);
            userquery.notEqualTo('isDeleted', true)
            let user = await userquery.find();
            let num = user.map(item => item.toJSON());
            if (num[0].num) {
                this.setData({
                    target: num[0].num
                })
                console.log('当前步数', this.data.target);
            } else {
                const currentUser2 = Parse.User.current();
                let userquery2 = new Parse.Query('_User');
                userquery2.equalTo('company', company);
                userquery2.equalTo('objectId', currentUser2.id);
                userquery2.notEqualTo('isDeleted', true)
                let user2 = await userquery2.first();
                user2.set('num', 5000)
                try {
                    let saveDate2 = await user2.save();
                    console.log(saveDate2);
                    this.setData({
                        target: 5000
                    })
                    console.log("目标步数更改成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            }
        },
        //获取当天运动数据
        async order() {
            const currentUser = Parse.User.current();
            let ActivityDataquery = new Parse.Query('ActivityData');
            ActivityDataquery.equalTo('user', currentUser.id);
            ActivityDataquery.equalTo('company', company);
            ActivityDataquery.equalTo('type', 'today');
            ActivityDataquery.notEqualTo('isDeleted', true);

            // 获取今天的日期
            const today = new Date();
            const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 今天的开始时间
            const todayEnd = new Date(todayStart);
            todayEnd.setHours(23, 59, 59, 999); // 今天的结束时间

            // 在查询条件中添加对 createdAt 的限制
            ActivityDataquery.greaterThanOrEqualTo('createdAt', todayStart);
            ActivityDataquery.lessThanOrEqualTo('createdAt', todayEnd);
            ActivityDataquery.include('user');

            let r = await ActivityDataquery.find();
            let sharList = r.map(item => item.toJSON());

            this.setData({
                sharList
            });
            console.log(this.data.sharList);
        },
        //获取当前位置信息
        Getlocation() {
            // 获取当前位置信息
            wx.getLocation({
                type: 'wgs84',
                success: (res) => {
                    const {
                        latitude,
                        longitude
                    } = res;
                    //调用api解析地址
                    wx.request({
                        url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude,
                        data: {},
                        header: {
                            'Content-Type': 'application/json'
                        },
                        success: (ops) => { // 使用箭头函数
                            console.log(ops);
                            const address = ops.data.result.formatted_address;
                            this.setData({
                                address: address,
                            });
                            console.log(this.data.address);
                        },
                        fail: function (resq) {
                            wx.showModal({
                                title: '信息提示',
                                content: '请求失败',
                                showCancel: false,
                                confirmColor: '#f37938'
                            });
                        },
                        complete: function () {}
                    })

                },
                fail: (err) => {
                    console.error(err);
                    wx.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    });
                }
            });
        },
        //获取微信步数
        getWeRunData() {
            wx.getWeRunData({
                success: (res) => {
                    // 获取到的加密数据
                    const encryptedData = res.encryptedData;
                    const iv = res.iv;
                    // 这里需要调用你的后端接口进行解密
                    // 假设你有一个解密函数 decryptData
                    // this.decryptData(encryptedData, iv).then(steps => {
                    //     this.setData({
                    //         steps: `${steps}`
                    //     });
                    //     console.log('用户步数:', this.data.steps);
                    // }).catch(err => {
                    //     console.error('解密失败:', err);
                    // });
                    const steps = this.decryptData(encryptedData, iv)
                    console.log(steps);
                    this.updatetoday(steps)
                },
                fail: (err) => {
                    console.error('获取运动数据失败:', err);
                }
            });
        },
        decryptData(encryptedData, iv) {
            // return new Promise((resolve, reject) => {
            //     // 发送请求到后端进行解密
            //     wx.request({
            //         url: '', // 替换为你的后端解密接口
            //         method: 'POST',
            //         data: {
            //             encryptedData: encryptedData,
            //             iv: iv,
            //             // 需要传递 session_key,通常在用户登录时获取
            //             session_key: wx.getStorageSync('session_key') // 假设你已经存储了 session_key
            //         },
            //         success: (res) => {
            //             if (res.data && res.data.steps) {
            //                 // resolve(res.data.steps); // 返回步数
            //                 const steps = 123456
            //                 resolve(steps);
            //             } else {
            //                 reject('解密返回数据格式错误');
            //             }
            //         },
            //         fail: (err) => {
            //             reject(err);
            //         }
            //     });
            // });
            const steps = 323456
            return steps
        },
        //更新今日步数
        async updatetoday(steps) {
            const currentUser = Parse.User.current();
            let ActivityDataquery = new Parse.Query('ActivityData');
            ActivityDataquery.equalTo('user', currentUser.id);
            ActivityDataquery.equalTo('company', company);
            ActivityDataquery.equalTo('type', 'today');
            ActivityDataquery.notEqualTo('isDeleted', true);
            // 获取今天的日期
            const today = new Date();
            const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 今天的开始时间
            const todayEnd = new Date(todayStart);
            todayEnd.setHours(23, 59, 59, 999); // 今天的结束时间

            // 在查询条件中添加对 createdAt 的限制
            ActivityDataquery.greaterThanOrEqualTo('createdAt', todayStart);
            ActivityDataquery.lessThanOrEqualTo('createdAt', todayEnd);

            let r = await ActivityDataquery.first();
            if (r) {
                r.set('steps', steps)
                try {
                    let saveDate = await r.save();
                    this.order()
                    console.log("步数修改成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            } else {
                const currentUser = Parse.User.current();
                let userquery = new Parse.Query('_User');
                userquery.equalTo('company', company);
                userquery.equalTo('objectId', currentUser.id);
                userquery.notEqualTo('isDeleted', true)
                let user = await userquery.first();

                let companyPointer = Parse.Object.extend('Company').createWithoutData(company);
                let Comment = new Parse.Object('ActivityData');
                Comment.set('company', companyPointer);
                Comment.set('type', 'today');
                Comment.set('user', user.toPointer());
                Comment.set('steps', steps);
                try {
                    let saveDate2 = await Comment.save();
                    this.order()
                    // console.log(saveDate2);
                    console.log("步数保存成功");
                } catch (error) {
                    console.error("保存数据时出现错误:", error);
                }
            }
        }
    }
})