//打卡日历页面
const Parse = getApp().Parse;
const dateF = require('../../../utils/date.js')
const company = getApp().globalData.company;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        days: [], //存放一个月的天数数组
        signUp: [], //用户判断当天是否已打卡  可废除下方模拟打卡数组直接采用此数组
        //用于判断
        cur_year: 0, //年
        cur_month: 0, //月
        count: 0, //累计打卡的数量
        continuous_daka_count: 0, //连续打卡次数
        task: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        //获取当前年月  
        const date = new Date();
        let _cur_year = date.getFullYear();
        let _cur_month = date.getMonth() + 1;
        let _weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
        this.setData({
            cur_year: _cur_year,
            cur_month: _cur_month,
            weeks_ch: _weeks_ch,
        })
        await this.getTask(),//查询积分表赋值给credit
            await this.calculateEmptyGrids(this.data.cur_year, this.data.cur_month); // 计算当月1号前空了几个格子，把它填充在days数组的前面
        await this.calculateDays(this.data.cur_year, this.data.cur_month); // 绘制当月天数占的格子，并把它放到days数组中
        await this.onGetSignUp();//获取当前用户当前任务的人签到状态
    },
    //查询积分表赋值给credit
    async getTask() {
        let Task = new Parse.Query('Task');
        Task.equalTo('company', company);
        Task.equalTo('isOpen', true);
        Task.equalTo('taskType', 'daily-check');
        let task = await Task.first();
        if (task && task.id) {
            let taskJSON = task.toJSON();
            this.setData({
                task: taskJSON
            });
            await this.setSignUp()
        } else {
            wx.showToast({
                title: '未设置签到规则',
                icon: 'none',

            })
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
            }, 1500)

        }
    },

    ///查询数据库签到了多少天 并复制给signUp数组
    async setSignUp() {
        let uid = Parse.User.current().id;
        let TaskLog = new Parse.Query("TaskLog");
        TaskLog.equalTo('company', company);
        TaskLog.equalTo('user', uid);
        TaskLog.equalTo('task', this.data.task.objectId);
        let taskLog = await TaskLog.find();
        let parsetsJSON = [];
        if (taskLog && taskLog.length > 0) {
            taskLog.forEach(parse => {
                let b = parse.toJSON();
                parsetsJSON.push(b);
            })
        }
        console.log(parsetsJSON)
        //这个用来装数据库的时间
        let count = new Array();
        for (let i = 0; i < taskLog.length; i++) {
            let sum = "";
            let dateSubString = "";
            sum = parsetsJSON[i].updatedAt;
            dateSubString = sum.substring(0, 10);
            count.push(dateSubString)
        }
        this.setData({
            signUp: count
        })
        this.onGetSignUp();
    },

    //获取当前用户该任务的签到数组
    onGetSignUp: function () {
        let that = this;
        let _arr = [];
        that.data.signUp.map(item => {
            _arr.push(item);
        })
        that.setData({
            count: _arr.length
        });
        //获取后就判断签到情况
        that.onJudgeSign();//匹配判断当月与当月哪些日子签到打卡
    },

    //匹配判断当月与当月哪些日子签到打卡
    onJudgeSign() {
        let that = this;
        let signs = that.data.signUp;
        let daysArr = that.data.days;
        for (let i = 0; i < signs.length; i++) {
            let current = new Date(signs[i].replace(/-/g, "/"));
            let year = current.getFullYear();
            let month = current.getMonth() + 1;
            let day = current.getDate();
            day = parseInt(day);
            for (let j = 0; j < daysArr.length; j++) {
                //年月日相同并且已打卡
                if (year == that.data.cur_year && month == that.data.cur_month && daysArr[j].date == day) {
                    daysArr[j].isSign = true;
                }
            }
        }
        that.setData({
            days: daysArr
        });
        that.onJudgeContinuousClock();
    },

    //判断连续打卡次数
    onJudgeContinuousClock() {
        let that = this;
        let _count = 0;
        let arr = that.data.signUp
        // 再实际数据中，dateList 是不需要咱们手动排序的，我这边主要是用于测试，所以一些校验并未完善
        arr = arr.sort((a, b) => {
            return Date.parse(`${a.year}/${a.month}/${a.date}`) - Date.parse(`${b.year}/${b.month}/${b.date}`)
        })
        for (let i = 0; i < arr.length; i++) {
            //把时间转换为时间戳
            if (i != 0) {
                var newDate_ = Date.parse(arr[i]); //当天
                var theOriginalTime_ = Date.parse(arr[i - 1]);
                //计算天
                let _day = parseInt(newDate_ - theOriginalTime_) / (1000 * 60 * 60);
                if (_day <= 24) {
                    _count += 1;
                } else {
                    _count = 0;
                }
            }
        }
        that.setData({
            continuous_daka_count: _count != 0 ? _count + 1 : 0,
        })
    },

    //查询有没有签到
    async onBindTap() {
        //获取今天零点时间
        let beforeDawn = new Date(new Date().toLocaleDateString()).getTime(); //获取当天凌晨的时间
        let date = new Date(beforeDawn);
        let uid = Parse.User.current().id;
        let TaskLog = new Parse.Query('TaskLog');
        TaskLog.equalTo('company', company);
        TaskLog.equalTo('user', uid);
        TaskLog.equalTo('task', this.data.task.objectId);
        TaskLog.greaterThan('createdAt', date);
        let taskLog = await TaskLog.first();
        if (taskLog && taskLog.id) {
            wx.showToast({
                title: '今日已签到',
                icon: 'none'
            })
            return
        } else {
            let DailyCheck = Parse.Object.extend('DailyCheck')
            let dailyCheck = new DailyCheck()
            dailyCheck.set("user", {
                __type: "Pointer",
                className: "_User",
                objectId: uid
            })
            dailyCheck.set("company", {
                __type: "Pointer",
                className: "Company",
                objectId: company
            })
            let check = await dailyCheck.save();
            if (check && check.id) {
                wx.showToast({
                    title: '签到成功',
                    icon: 'success'
                })
                this.setSignUp();
                this.inCredit();
            }
        }
    },

    async check() {
        let userid = Parse.User.current().id
        let start = new Date(new Date(new Date().toLocaleDateString()).getTime())
        let TaskLog = new Parse.Query('TaskLog')
        TaskLog.equalTo('user', userid)
        TaskLog.equalTo('task', this.data.task.objectId)
        TaskLog.equalTo('company', company)
        TaskLog.greaterThan('createdAt', start)
        let log = await TaskLog.first()
        if (log && log.id) {
            return
        } else {
            let credit = this.data.task.credit ? this.data.task.credit : 1
            let maxLength = this.data.task.increLength - 1
            let increasing = this.data.task.increasing
            if (increasing && !maxLength) {
                credit = credit + (increasing * this.data.continuous_daka_count)
            }
            if (increasing && maxLength) {
                if (this.data.continuous_daka_count < maxLength) {
                    credit = credit + (increasing * this.data.continuous_daka_count)
                } else {
                    credit = credit + (increasing * maxLength)
                }
            }
            this.createdLog(userid, this.data.task.objectId, credit)
        }
    },

    async createdLog(uid, tid, credit) {
        let TaskLog = Parse.Object.extend('TaskLog')
        let tasklog = new TaskLog()
        tasklog.set('user', {
            __type: "Pointer",
            className: '_User',
            objectId: uid
        })
        tasklog.set('task', {
            __type: "Pointer",
            className: 'Task',
            objectId: tid
        })
        tasklog.set('company', {
            __type: "Pointer",
            className: 'Company',
            objectId: company
        })
        tasklog.set('isReceive', false)
        tasklog.set('credit', credit)
        await tasklog.save()
        wx.showToast({
            title: '签到成功',
            icon: 'success'
        })
        await this.setSignUp()
        await this.inCredit(credit)
    },

    //签到给用户添加5积分
    async inCredit(credit) {
        let uid = Parse.User.current().id
        let Profile = new Parse.Query('Profile')
        Profile.equalTo('user', uid)
        Profile.equalTo('company', company)
        let profile = await Profile.first()
        let profileJSON = profile.toJSON()

        let Account = new Parse.Query('Account')
        Account.equalTo('company', company)
        Account.equalTo('user', uid)
        let account = await Account.first()
        let accountJSON = account.toJSON()
        let targetAccount = accountJSON.objectId

        let AccountLog = Parse.Object.extend('AccountLog')
        let accountLog = new AccountLog()
        accountLog.set('assetCount', credit)
        accountLog.set('targetAccount', { __type: 'Pointer', 'className': 'Account', objectId: targetAccount })
        accountLog.set('company', { __type: 'Pointer', className: 'Company', objectId: company })
        accountLog.set('fromAccountName', '南昌水业工会')
        accountLog.set('assetType', 'credit')
        if (credit == 1) {
            accountLog.set('desc', '签到获得积分')
        }
        if (credit == 2) {
            accountLog.set('desc', '连续签到2天获得积分')
        }
        if (credit >= 3) {
            accountLog.set('desc', '连续签到3天获得积分')
        }
        accountLog.set('profile', { __type: 'Pointer', className: 'Profile', objectId: profileJSON.objectId })
        accountLog.set('isVerified', false)
        accountLog.save().then((res) => {
            res.set('isVerified', true)
            res.save()
        })
    },


    // 获取当月共多少天
    getThisMonthDays: function (year, month) {
        return new Date(year, month, 0).getDate()
    },

    // 获取当月第一天星期几
    getFirstDayOfWeek: function (year, month) {
        return new Date(Date.UTC(year, month - 1, 1)).getDay();
    },

    // 计算当月1号前空了几个格子，把它填充在days数组的前面
    calculateEmptyGrids: function (year, month) {
        let that = this;
        //计算每个月时要清零
        that.setData({
            days: [],
        });
        const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
        if (firstDayOfWeek > 0) {
            for (let i = 0; i < firstDayOfWeek; i++) {
                let obj = {
                    date: null,
                    isSign: false //拒绝
                }
                that.data.days.push(obj);
            }
            this.setData({
                days: that.data.days,
            });
            //清空
        } else {
            this.setData({
                days: []
            });
        }
    },


    // 绘制当月天数占的格子，并把它放到days数组中
    calculateDays: function (year, month) {
        let that = this;
        const thisMonthDays = this.getThisMonthDays(year, month);
        for (let i = 1; i <= thisMonthDays; i++) {
            let obj = {
                date: i,
                isSign: false
            }
            that.data.days.push(obj);
        }
        this.setData({
            days: that.data.days
        });

    },

    // 切换控制年月，上一个月，下一个月
    handleCalendar: function (e) {
        let that = this;
        const handle = e.currentTarget.dataset.handle;
        const cur_year = that.data.cur_year;
        const cur_month = that.data.cur_month;

        if (handle === 'prev') {
            let newMonth = cur_month - 1;
            let newYear = cur_year;
            if (newMonth < 1) {
                newYear = cur_year - 1;
                newMonth = 12;
            }
            this.setData({
                cur_year: newYear,
                cur_month: newMonth
            })
            this.calculateEmptyGrids(newYear, newMonth);
            this.calculateDays(newYear, newMonth);
            this.onGetSignUp();
        } else {

            let newMonth = cur_month + 1;
            let newYear = cur_year;
            if (newMonth > 12) {
                newYear = cur_year + 1;
                newMonth = 1;
            }
            this.setData({
                cur_year: newYear,
                cur_month: newMonth
            })

            this.calculateEmptyGrids(newYear, newMonth);
            this.calculateDays(newYear, newMonth);
            this.onGetSignUp();
        }
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },
})
