// pages/signIn/index.js
import SignIn from '../../../api/signIn'
import Statistics from '../../../components/statistics/index'
import { isEmpty } from '../../../utils/util'
import { getMobileCache, getPhoneNumberNew as getPhoneNumberSync } from '../../../utils/user'
const app = getApp();
 
Page({
    /**
     * 页面的初始数据
     */
    data: {
        showPage: false,
        showTaskCard: false,
        showSignInSuccessDlg: false,
        activity: {},
        signInNodes: [{ pos: 1, text: '星期一' }, 
                      { pos: 2,  text: '星期二' }, 
                      { pos: 3, text: '星期三' }, 
                      { pos: 4, text: '星期四' }, 
                      { pos: 5, text: '星期五' }, 
                      { pos: 6, text: '星期六' }],
        lastSignInNode: { pos: 7, text: '星期天' },
        todayIsSigned: false,
        notUseNum: 0,
        signInId: '',
        department: '',
        appletCode: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.log(options)
      if(options && options.signId) {
        this.setData({
          signInId: options.signId,
          department: options.department,
          appletCode: 1,
        })
        console.log(options.signId) //abcd
      }
    },

        /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            isLogin: getMobileCache() != "",
        })
        this.data.dayOfWeek = this.getDayOfWeek()
        this.startLoadActivityData()
    },

    startLoadActivityData() {
      let data = {
        signInId: this.data.signInId,
        mobile: getMobileCache(),
      }
        SignIn.getActivityData(data).then(res => {
            if (res.code == 200) {
                this.setData({
                    activity: res.data
                })
                this.mapToView(res.data)

                Statistics.done({
                    module: 'signin',
                    action: 'visit',
                    businessId: res.data.id,
                    department: this.data.department,
                })

            }
        }).catch(_ => {

        }).finally(_ => {
            this.setData({
                showPage: true
            })
        })
        if (this.data.isLogin) {
            SignIn.getUserAwardCouponNum({
                mobile: getMobileCache()
            }).then( res => {
                if (res.code == 200) {
                    this.setData({
                        notUseNum: res.data.notUseNum || 0
                    })
                }
                console.log(res)
            }).catch(_ => {})
        }
        
    },

    mapToView(data) {
        this.setColors(data.color)
        if (data.dayAwardList && data.dayAwardList.length > 0) {
            data.dayAwardList.forEach(item => {
                if (item.dayNo == 7) {
                    this.preDealItemData(this.data.lastSignInNode, item);
                } else {
                    if (this.data.signInNodes[item.dayNo - 1]) {
                        this.preDealItemData(this.data.signInNodes[item.dayNo - 1], item)
                    }
                }
            });
            let showTaskCard = false
            if (data.taskAwardList && data.taskAwardList.length > 0) {
                showTaskCard = true
            }

            this.setData({
                signInNodes: this.data.signInNodes,
                lastSignInNode: this.data.lastSignInNode,
                showTaskCard,
            })
        }
    },

    preDealItemData(target, item) {
        // 未签到的情况下，计算是否属于过签
        Object.assign(target, item);
        if (target.isSignIn == 0 && target.pos < this.data.dayOfWeek) {
            target.isSignIn = -1;
            target.textBgGround = this.data.grayBackGroudStyle
        } else {
            target.textBgGround = this.data.backGroundStyle
        }
        if (target.pos == this.data.dayOfWeek) {
            this.setData({
                todayIsSigned: target.isSignIn == 1
            })
        }
    },

    getDayOfWeek(date) {
        var now = date || new Date();
        var day = now.getDay();
        if (day == 0) {
            return 7
        }
        return day;
    },

    setColors(color) {
        if (isEmpty(color)) {
            color = "#EE5A5A"
        }
        if (color.length == 4) {
            color = color.replace(/#(.)(.)(.)$/, "#$1$1$2$2$3$3")
        }
        let newColor = "#";
        for (let i = 1; i <= 6; i++) {
            if (color.charAt(i) == 'a' || color.charAt(i) == 'A') {
                newColor += "9"
            } else if (color.charAt(i) == '0') {
                newColor += "0"
            } else {
                newColor += String.fromCharCode(color.charCodeAt(i) - 1)
            }
        }
        this.setData({
            mainColor: color,
            secColor: newColor,
            thirdColor: "rgb(" + this.toRGB(color) + ", 0.3)",
            backGroundStyle:  "background: linear-gradient(" +color+", "+ newColor+ ", "+color+");",
            grayBackGroudStyle: "background: #c6c6c6"
        })
    },

    toRGB(hex) {
        const list = [hex.substr(1,2), hex.substr(3,2), hex.substr(5,2)]
        list[0] = parseInt(list[0] , 16)
        list[1] = parseInt(list[1] , 16)
        list[2] = parseInt(list[2] , 16)
        return list.join(',')
    },

    popMessage(message) {
        app.showToast(message, "none")
    },

    tapSignIn: function() {
        if (!this.data.isLogin) {
            return;
        }
        if (!this.data.activity.id) {
            this.popMessage("未找到签到活动")
            return;
        }

        if (this.isLocked) {
            return
        }
        this.isLocked = true

        SignIn.triggerSignIn(this.data.activity.id, getMobileCache(), this.data.appletCode).then(res => {
            console.log(res)
            if (res.code == 200) {
                this.dealSignResult(res.data)
                this.startLoadActivityData()
            }
        }).catch(_ => {
            console.log(_)
        }).finally(_ => {
            this.isLocked = false
        })

        Statistics.done({
            module: 'signin',
            action: 'click',
            businessId: this.data.activity.id,
            department: this.data.department,
        })
    },

    /**
     * 处理签到结果
     */
    dealSignResult(data) {
        if (data.isHit == 0 || data.coupon == null) {
            // 没有配置奖品的情况下
            this.popMessage("签到成功！")
            return
        }

        const hitResult = data.coupon;

        if (hitResult.couponType == "C") {
            // 现金券
            if (hitResult.formatReduceCost.length >= 3) {
                hitResult._classSmallStyle = "_small"
            }

        } else if (hitResult.couponType == "D") {
            // 折扣券
            if (hitResult.formatDiscount.length >= 3) {
                hitResult._classSmallStyle = "_small"
            }
        }
        if (hitResult.formatLeastCost == "0") {
            hitResult.formatLeastCostStr = "无门槛使用"
        } else {
            hitResult.formatLeastCostStr = "满" + hitResult.formatLeastCost + "元使用"
        }

        this.setData({
            hitResult: hitResult,
            showSignInSuccessDlg: true
        })
    },

    // 授权手机号
    getPhoneNumber(e) {
        getPhoneNumberSync(e, _ => {
            this.setData({ isLogin: true })
            this.startLoadActivityData()
        })
    },

    closeDlg() {
        this.setData({
            showSignInSuccessDlg: false
        })
    },

    toRecordDetailPage() {
        wx.navigateTo({
          url: '../record/record',
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },
    handlePageSizes(e) {
        // console.log(e)
    }
})