// nova-werun/pages/home/statistics/index.js
import * as echarts from "../../../components/ec-canvas/echarts.min"
const Parse = getApp().Parse;
const company = getApp().globalData.company;


Page({

    /**
     * 页面的初始数据
     */
    data: {
        //屏幕高度
        statusBarHeight: 0, // 状态栏高度
        screenHeight: 0, // 屏幕高度
        customHeight: 0, // 自定义导航栏高度（如小程序右上角胶囊按钮）
        bottomNavHeight: 0, // 底部导航栏高度
        contentHeight: 0, // 可用内容高度
        contentHeight2: 0,
        contentpadding: 0, //顶部padding高度

        active: 0,
        //
        day: '7',
        target: '',
        sharList: [],
        //生涯数据
        stardate: '',
        daysDifference: "",
        totalSteps: 0,
        totalDistance: 0,
        totalBurnCalories: 0,
        totalsportDate: 0,

        ec: {
            onInit: null
        },
        resultList: [],
        stepsData: [], //统计图柱状
        xAxis: [], //x轴

        percentage: '',
        percent: '',

        //排名百分比
        percebtage: 0,
        //
        average: 0,
        totle: 0,

        //显示日历
        todatDate:null,
        minDate: null,
        maxDate: null,
        formatter(day) {
            day.topInfo = '11111'
            return day;
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        // 计算
        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 - 50 - bottomNavHeight - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
        this.setData({
            statusBarHeight,
            screenHeight,
            customHeight,
            bottomNavHeight,
            contentpadding,
            contentHeight
        });
        await this.gettarget()
        await this.order()
        this.allorder()
        await this.getweekday()
        this.echartsComponnet = this.selectComponent('#mychart')
        await this.initChart()
        this.gettoday()
    },
    //图表
    // 将 initChart 定义在 Page 上下文中
    initChart() {
        if (this.chart) {
            this.chart.clear();
        }
        this.echartsComponnet.init((canvas, width, height, dpr) => {
            // 初始化图表
            this.chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // 清晰度 使canvas的图表更加清晰
            });
            this.chart.setOption(this.getOption())
            return this.chart;
        });
    },

    getOption() {
        var option = {
            xAxis: {
                type: 'category',
                data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                axisLabel: {
                    formatter: (value, index) => this.formatter(value, index)
                }
            },
            yAxis: {
                type: 'value',
                max: 20000, // 设置Y轴最大值为20000
                axisLabel: {
                    formatter: function (value) {
                        if (value >= 10000) {
                            return (value / 1000) + 'k'; // 格式化为20k
                        }
                        return value;
                    }
                }
            },
            series: [{
                // data: [
                //     12000,
                //     {
                //         value: 12000,
                //         itemStyle: {
                //             color: '#a90000',
                //         }
                //     },
                //     12000,
                //     12000,
                //     12000,
                //     12000,
                //     12000
                // ],
                data: this.data.stepsData,
                type: 'bar',
                barWidth: '10',
                itemStyle: {
                    borderRadius: 15,
                }
            }],
        };
        return option; // 返回 option 对象
    },
    // 返回x轴底下的字
    formatter(value, index) {
        let daylist = this.data.resultList.map(item => {
            const day = new Date(item.createdAt); // 获取当前日期
            const dayOfMonth = day.getDate(); // 获取今天是几号
            return dayOfMonth
        })
        daylist.reverse()
        const dayindex = daylist.length - 1
        if (daylist.length < 7) {
            for (let i = daylist.length; i < 7; i++) {
                const lastDay = daylist[daylist.length - 1];
                daylist.push(lastDay + (i - daylist.length + 1)); // 补充后续日期
            }
        }
        const dates = daylist.map(item => {
            return `${item}号`
        })
        return index === dayindex ? '今天' + '\n' + '\n' + dates[index] : value + '\n' + '\n' + dates[index];
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    //底部tab栏修改
    onChange(event) {
        this.setData({
            active: event.detail
        });
        this.echartsComponnet = this.selectComponent('#mychart')
        this.initChart()
    },
    //修改30天或者7天数据
    changeday() {
        if (this.data.day == '7') {
            this.setData({
                day: '30',
            })
            this.gettodaydate()
        } else {
            this.setData({
                day: '7'
            })
            this.echartsComponnet = this.selectComponent('#mychart')
            this.initChart()
            this.getweekday()
        }
    },
    //获取目标步数
    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);
        }
    },
    //获取当天运动数据
    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
        });
        this.getBackgroundColor()
        console.log(this.data.sharList);
    },
    //获取生涯运动数据
    async allorder() {
        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);

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

        // 根据 createdAt 日期从以前到现在排列
        allList.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));

        // 获取最早的 createdAt 日期
        const earliestDate = new Date(allList[0].createdAt);

        // 格式化为 YYYY年MM月DD日
        const formattedDate = `${earliestDate.getFullYear()}年${String(earliestDate.getMonth() + 1).padStart(2, '0')}月${String(earliestDate.getDate()).padStart(2, '0')}日`;

        // 计算从最早日期到今天的天数
        const today = new Date();

        // 清零时间部分
        earliestDate.setHours(0, 0, 0, 0); // 将最早日期的时间部分清零
        today.setHours(0, 0, 0, 0); // 将今天的时间部分清零

        // 计算日期差值
        const timeDifference = today - earliestDate; // 时间差（毫秒）
        const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); // 转换为天数

        // 计算 steps、distance 和 burnCalories 的总和
        let totalSteps = 0;
        let totalDistance = 0;
        let totalBurnCalories = 0;
        let totalsportDate = 0;

        allList.forEach(item => {
            totalSteps += Number(item.steps) || 0; // 确保为数字类型，避免 NaN
            totalDistance += Number(item.distance) || 0; // 确保为数字类型，避免 NaN
            totalBurnCalories += Number(item.burnCalories) || 0; // 确保为数字类型，避免 NaN
            totalsportDate += Number(item.sportDate) || 0;
        });

        // 将总运动时间转换为天、小时、分钟
        const days = Math.floor(totalsportDate / (60 * 24)); // 转换为天数
        const hours = Math.floor((totalsportDate % (60 * 24)) / 60); // 剩余小时
        const minutes = totalsportDate % 60; // 剩余分钟
        // 设置 stardate 和 daysDifference
        this.setData({
            stardate: formattedDate,
            daysDifference: daysDifference,
            totalSteps,
            totalDistance,
            totalBurnCalories,
            totalsportDate: `${days}天 ${hours}小时 ${minutes}分钟` // 格式化为字符串
        });

        console.log(allList, this.data.totalsportDate);
    },
    //修改光圈
    getBackgroundColor() {
        const steps = this.data.sharList[0].steps || 0;

        let percent = (steps / this.data.target) * 100;
        console.log('目标', percent);
        if (percent > 100) {
            percent = 100;
        }
        // 保留两位小数
        percent = parseFloat(percent.toFixed(2));
        this.setData({
            percent,
            percentage: `conic-gradient(from 0deg, #015EEA ${percent}%, white 0%)`,
        })
        console.log('百分比', this.data.percentage);
    },
    //获取本周记录
    async getweekday() {
        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);

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

        // 按时间降序排序（从现在到以前）
        allList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

        // 获取今天是星期几（0 = 周日, 1 = 周一, ..., 6 = 周六）
        const today = new Date();
        const dayOfWeek = today.getDay(); // 获取当前星期几

        // 根据星期几决定取多少条数据
        let numItemsToTake;
        if (dayOfWeek === 0) {
            numItemsToTake = 7; // 周日取7条数据
        } else {
            numItemsToTake = dayOfWeek; // 周一至周六取对应条数
        }

        // 取出对应数量的数据
        const resultList = allList.slice(0, numItemsToTake);
        const stepsData = resultList.map((item, index) => {
            if (index === 0) {
                // 如果是第一条数据，设置特殊样式
                return {
                    value: item.steps,
                    itemStyle: {
                        color: '#a90000',
                    }
                };
            } else {
                // 其他数据直接返回 steps
                return item.steps;
            }
        });
        stepsData.reverse()
        //总计，平均
        let totle = 0
        for (let i = 0; i < resultList.length; i++) {
            totle = totle + Number(resultList[i].steps)
        }
        const average = totle / resultList.length
        console.log('totle', totle, average);
        this.setData({
            resultList,
            stepsData,
            totle,
            average,
        })
        console.log('resultList', resultList);

    },
    //获取今日排名百分比
    async gettoday() {
        const currentUser = Parse.User.current();
        let ActivityDataquery = new Parse.Query('ActivityData');
        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); // 今天的结束时间
        console.log(todayStart, todayEnd);
        // 在查询条件中添加对 createdAt 的限制
        ActivityDataquery.greaterThanOrEqualTo('createdAt', todayStart);
        ActivityDataquery.lessThanOrEqualTo('createdAt', todayEnd);

        // 根据 steps 字段进行降序排序
        ActivityDataquery.descending('steps');
        ActivityDataquery.include('user');

        try {
            let P = await ActivityDataquery.find();
            let todayList = P.map(item => item.toJSON());
            console.log('todayList', todayList);
            let rank = 0
            // 更新页面数据
            todayList.forEach((item, index) => {
                if (item.user.objectId == currentUser.id) {
                    rank = index + 1;
                    return
                }
            })

            var ranper = 100 - (rank / todayList.length) * 100
            ranper = parseFloat(ranper.toFixed(2));
            this.setData({
                percebtage: ranper
            })
            console.log('percebtage', this.data.percebtage);
        } catch (error) {
            console.error('Error fetching today\'s data:', error);
        }
    },
    //获取当月第一天日期和最后一天日期
    gettodaydate() {

        // 获取今天的日期
        const today = new Date();
        // 获取当月第一天的日期
        const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1).getTime();
        // 获取当月最后一天的日期
        const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getTime();
        this.setData({
            minDate:startOfMonth,
            maxDate:endOfMonth,
            todatDate:today.getTime()
        })
    }
})