// pages/luckDraw/detail.js
import LuckDraw from '../../api/luck-draw'
import Common from './common'
import Statistics from '../../components/statistics/index'
import {getMobileCache, getPhoneNumberNew as getPhoneNumberSync} from '../../utils/user'

const app = getApp();

const DEFAULT_GIFTS = [
    { icoUrl: '', text: '' }, { iconUrl: '', text: '' },{ icoUrl: '', text: '' }, { icoUrl: '', text: ''},
    { icoUrl: '', text: ''}, { icoUrl: '', text: '' }, { icoUrl: '', text: ''}, { icoUrl: '', text: '' }
];
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pointerPos: 0,
        hitPos: null,
        isHit: null,
        activityId: 0,
        forbidTurn: false,
        giftList: DEFAULT_GIFTS,
        allNum: 0,
        remainNum: 0,
        remainNumSplits: [],
        showHitPrizeDlg: false,
        showNoHitPrizeDlg: false,
        showNeedShareDlg: false,
        showPage: false,
        isLogin: false,
        hitResult: null,
        noHitResult: null,
        hitRecordList: [],
        showCustomPreview: false,
        themePic: '', // 来个默认值
        popBgPic: '',
        boxBgPic: '',
        bgColor: '',
    },

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

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

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.log(options)
        Object.assign(this, Common)
        if (!options.id) {
            this.popMessage ('入参错误');
            wx.navigateTo({
              url: './index',
            })
            return
        }
        this.setData({
            isLogin: getMobileCache() != ''
        })
        this.data.activityId = options.id
        this.loadActivity()
        this.getDrawTimes()
        // 获取中奖名单
        this.getHitRecord()

        Statistics.done({
            module: 'luckdraw',
            action: 'visit',
            businessId: this.data.activityId
        })
    },
    loadActivity: function() {
        LuckDraw.getActivityDetail(this.data.activityId).then(resp => {
            if (resp.code == 200 && resp.data != null) {
                this.mapDataToView(resp.data)
            }
       }).catch(err => {
           this.setData({
             errMessage: err.data.msg
           })
       }).finally(_ => {
           this.setData({
               showPage: true
           })
       })
    },

    /**
     * 获取次数
     */
    getDrawTimes: function() {
        if (!this.data.isLogin) {
            this.setData({
                remainNum: 0,
                allNum: 0
            })
            this.setRemainNumSplits()
            return
        }
        LuckDraw.getTimes(this.data.activityId, getMobileCache()).then(res => {
            if (res.code == 200) {
                this.setData({
                    remainNum: res.data.remainTimes,
                    allNum: res.data.allTimes,
                })
                this.setRemainNumSplits()
            }
        }).catch(_ => {})
    },

    /**
     * 活动数据映射
     */
    mapDataToView: function(activity) {
        activity.goodsItemList.forEach(v => {
            const pos = parseInt(v.pos || 0)
            if (pos > 0) {
                if (this.data.giftList[pos-1].isLoaded) {
                    return true
                }
                this.data.giftList[pos - 1].isLoaded = true
                this.data.giftList[pos - 1].text = v.goodsName
                this.data.giftList[pos - 1].iconUrl = v.goodsSmallImage
                this.data.giftList[pos - 1].hitIconUrl = v.goodsBigImage
                this.data.giftList[pos - 1].goodsId = v.goodsId
                this.data.giftList[pos - 1].couponId = v.couponId
                this.data.giftList[pos - 1].isSpecial = v.isSpecial
                this.data.giftList[pos - 1].hitDesc = v.hitDesc
                this.data.giftList[pos - 1].active = false
            }
        })
        this.setData({
            activityTitle: activity.activityTitle,
            showBeginTime: activity.showBeginTime,
            showEndTime: activity.showEndTime,
            beginTime: activity.beginTime,
            endTime: activity.endTime,
            timeType: activity.timeType,
            dayBeginTime: activity.dayBeginTime,
            dayEndTime: activity.dayEndTime,
            giftList: this.data.giftList,
            ruleDesc: activity.ruleDesc || '',
            forbidTurn: activity.status != 2,
            opptyInitialVal: activity.opptyInitialVal || 0,
            opptyMaxVal: activity.opptyMaxVal || 0,
            status: activity.status,
            themePic: activity.themePic || 'https://dy.shpr.top/welfareGo/head-bg-draw.png', // 来个默认值
            popBgPic: activity.popBgPic || 'https://ks3-cn-shanghai.ksyun.com/pb001/web/hsay/publicPath/7e45b12e-43c5-490a-885d-d81b7b0917c2.png',
            boxBgPic: activity.boxBgPic || 'https://dy.shpr.top/welfareGo/gift-box.png',
            bgColor: activity.bgColor || '#BF2637',
        })

        if (activity.status == 1 || activity.status ==4 || activity.status == 5) {

            this.tmpTimeObject = {
                beginTime: activity.beginTime,
                endTime: activity.endTime,
                timeType: activity.timeType,
                dayBeginTime: activity.dayBeginTime,
                dayEndTime: activity.dayEndTime
            }
            this.countDownTimer = setInterval(this.calcCountDownTime, 1000)
            this.calcCountDownTime()
        }
    },
    calcCountDownTime() {
        this.setActivityCountdownTime(new Date(), this.tmpTimeObject)
        this.setData({
            countDownTime: this.tmpTimeObject.countDownTime,
            status: this.tmpTimeObject.status
        })
        // 删除定时器
        if (this.tmpTimeObject.status == 2 || this.tmpTimeObject.status == 3 && this.countDownTimer != null) {
            clearInterval(this.countDownTimer)
        }
    },
    /**
     * 开始转动奖品，抽奖
     */
    turnPrize: function() {
        console.log("开始抽奖")
        if (this.isLock || !this.data.isLogin) {
            return
        }
        // 预处理
        if (this.data.remainNum <= 0) {
            if (this.data.noHitResult != null ) {
                // 可以通过分享获取
                if (this.data.noHitResult.canShareGetTimes == 1) {
                    this.popNeedShareDlg()
                    return
                } 
                if (this.isSniffAgain) {
                    this.popMessage('抱歉，您的抽奖机会已用完');
                    return
                }
            }
        }
        this.isLock = true
        this.isSniffAgain = false
        let remainNum = this.data.remainNum - 1
        if (remainNum < 0) {
            this.isSniffAgain = true
            remainNum = 0
        }
        this.setData({ remainNum })
        this.setRemainNumSplits()
        // 开始动画，开始是快阶段
        this.data.duration = 50
        this.data.hitPos = -1
        this.data.hitTime = 0
        this.data.isHit = null;
        this.data.stopNotify = false
        if (this.isSniffAgain) {
            this.data.hitTime = new Date().getTime()
            this.requestDrawPrize()
            this.isLock = false;
        } else {
            this.startTurnAnimationFast()
            // 开始调用后台
            setTimeout(_ => {
                this.data.hitTime = new Date().getTime()
                this.requestDrawPrize()
            }, (Math.random() + 1)*1000)
        }

        Statistics.done({
            module: 'luckdraw',
            action: 'click',
            businessId: this.data.activityId
        })
    },
    
    requestDrawPrize: function() {
        LuckDraw.drawPrize(this.data.activityId, getMobileCache()).then(res => {
            if (res.code == 200) {
                this.hitPrizeMapData(res.data)
            }
        }).catch(_ => {
            console.log(_)
            this.data.stopNotify = true
            this.isLock = false
            this.getDrawTimes()
        })
    },

    hitPrizeMapData: function(hitData) {
        if (hitData.isHit == 1) {
            // 中奖
            const hitResult = hitData.hitResult;
            this.data.giftList.forEach((v, i) => {
                if (v.goodsId == hitResult.goodsId) {
                    // 设置中奖
                    this.data.hitPos = i
                    return false
                }
            })
            this.setData({
                hitResult,
                isHit: 1,
            })
        } else {
            // 未中奖
            const noHitResult = hitData.noHitResult || {};
            if (noHitResult.canShareGetTimes == 1) {
                // 分享可获取抽奖机会，停止转动
                this.data.stopNotify = true
                this.setData({
                    noHitResult,
                    isHit: 0
                })
                this.isLock = false
                this.popNeedShareDlg()
            } else {
                this.data.giftList.forEach((v, i) => {
                    if (v.goodsId == noHitResult.goodsId) {
                        // 设置中奖
                        this.data.hitPos = i
                        return false
                    }
                })
                this.setData({
                    noHitResult,
                    isHit: 0,
                })
                if (this.data.hitPos == -1) {
                    this.data.stopNotify = true
                    this.setData({
                        showNoHitPrizeDlg: true
                    })
                    this.isLock = false
                }
            }
        }
        // 重刷次数
        this.getDrawTimes()
    },

    popNeedShareDlg: function() {
        this.setData({
            showNeedShareDlg: true
        })
    },

    // 授权手机号
    getPhoneNumber(e) {

        getPhoneNumberSync(e, _ => {
            this.setData({ isLogin: true })
            this.getDrawTimes()
        })
    },
    nextPos() {
        let pos = 0
        switch(this.data.pointerPos) {
            case 0:
                pos = 1
                break
            case 1:
                pos = 2
                break
            case 2:
                pos = 4
                break
            case 4:
                pos = 7
                break
            case 7:
                pos = 6
                break  
            case 6:
                pos = 5
                break
            case 5:
                pos = 3
                break
            case 3:
                pos = 0
                break                 
        }
        this.data.pointerPos = pos
    },

    startTurnAnimationFast: function() {
        if (this.data.stopNotify) {
            // 异常停止转动
            this.setActiveGift(-1)
            this.timer&&clearTimeout(this.timer)
            return
        }
        const endTime = new Date().getTime()
        const step = 10
        this.timer = setTimeout(_ => {
            this.setActiveGift(this.data.pointerPos)
            if (this.data.hitPos == -1) {
                this.nextPos()
                this.startTurnAnimationFast()
            } else {
                // 收到抽中信号了，依然需要跑一段时间
                if (endTime - this.data.hitTime < (Math.random() + 1)*1000) {
                    this.data.duration += step
                    this.nextPos()
                    this.startTurnAnimationFast()
                } else {
                    // 可以定位了
                    if (this.data.hitPos == this.data.pointerPos) {
                        // 删除定时器，抽奖动作结束，开始回调
                        this.timer && clearTimeout(this.timer)
                        this.setActiveGift(this.data.pointerPos)
                        this.dealHitResult()
                    } else {
                        this.data.duration += (step * 2)
                        this.nextPos()
                        this.startTurnAnimationFast()
                    }
                }
            }
        }, this.data.duration)
    },

    setActiveGift(pos) {
        this.data.giftList.forEach((v, i) => {
            if (i == pos) {
                v.active = true
            } else {
                v.active = false
            }
        })
        this.setData({
            giftList: this.data.giftList
        })
    },

    dealHitResult: function() {
        setTimeout(_ => {
            if (this.data.isHit == 1) {
                this.setData({
                    showHitPrizeDlg: true
                })
            } else {
                this.setData({
                    showNoHitPrizeDlg: true
                })
            }
            this.isLock = false
        }, 500)

        // 刷新一下中奖名单
        this.getHitRecord()
    },

    /**
     * 中奖名单
     */
    getHitRecord: function() {
        LuckDraw.getHitList(this.data.activityId).then(res => {
            if (res.code == 200) {
                this.setHitRecordDataMap(res.data)
            }
        }).catch(_ => {})
    },
    setHitRecordDataMap: function(hitRecordList) {
        this.setData({
            hitRecordList
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        LuckDraw.shareActivity(this.data.activityId, getMobileCache(), res.from != 'button').then(res => {
            if (res.code == 200) {
                this.getDrawTimes()
            }
        }).catch(_ => {})
        return {
            title: this.data.activityTitle,
            path: "/pages/luckDraw/detail?id=" + this.data.activityId
        }
    },

    setRemainNumSplits: function() {
        this.setData({
            remainNumSplits: (this.data.remainNum || 0).toString().split("")
        })
    },

    closeDlg: function() {
        this.setData({
            showHitPrizeDlg: false,
            showNoHitPrizeDlg: false,
            showNeedShareDlg: false,
        })
    },

    toLuckDrawPage: function() {
        wx.navigateTo({
          url: '/pages/luckDraw/recordPrize?activityId=' + this.data.activityId,
        })
    },

    turnActivityListPage() {
        let pages = getCurrentPages()
        if (pages.length > 5 || pages.length == 1) {
            wx.reLaunch({
              url: '/pages/welfareMall/index/index',
            })
            return
        }
        wx.navigateBack({
            delta: 1  
        })
    },

    toLookHitPhoto() {
        let url = '';
        if (this.data.hitResult.goodsData && this.data.hitResult.goodsData.fullPhotoUrl) {
            url = this.data.hitResult.goodsData.fullPhotoUrl
        } else {
            url = this.data.hitResult.goodsBigImage
        }
        this.setData({
            showCustomPreview: true,
            previewImgSrc: url
        })
    },
    closePreviewImage() {
        this.setData({
            showCustomPreview: false
        })
    }
})