import Vue from 'vue'
import lib from 'lib'
import ext from 'extSdk'
import _ from 'underscore'

let uid = lib.getParam("uid")
let token = lib.getParam("token")
let upId = lib.getParam("upId")

class scrollCode {
    constructor(code){
        this.type = [
            [0,1,2,3,4,5,6,7,8,9],
            ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],
            ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        ]
        this.code = code
        this.codeArr = []
        this.typeArr = []
        this.init()
    }

    init(){
        let self = this

        _.each(this.code,(key)=>{
            self.typeArr.push(self.cheakCharacter(key))
        })
    }

    cheakCharacter(key){
        let reg1 = /\d/
        let reg2 = /[a-z]/
        let reg3 = /[A-Z]/
        let obj = {}
        let self = this

        if(reg1.test(key)) return 0
        if(reg2.test(key)) return 1
        if(reg3.test(key)) return 2
    }

    getRandomCharacter(index){
        let self = this
        let len = self.type[index].length
        let random = Math.floor(Math.random() * len)

        return self.type[index][random]
    }

    getRandomCode(){
        let self = this
        let arr = []
        _.each(this.typeArr,(type)=>{
            arr.push(self.getRandomCharacter(type))
        })

        return arr.join("")
    }
}

export default {
    methods: {
        getLotteryInfo(){ 
            let self = this 
            let url = `${lib.upAdminDomain}/act/lotteryInfo`;
            let param = {
                uid : uid,
                upId : upId,
                token : token
            }

            $.ajax({
                type: "get",
                url: url,
                data: param,
                dataType: "jsonp",
                success: (ret) => {
                    ret = lib.formatHttpProtocol(ret);

                    if(ret.code==0) {
                        let data = ret.data

                        self.bingoUsers = data.bingoUsers
                        self.reward = data.reward
                        self.userRecord = data.reward.userRecord
                        self.lotteryStatus = data.reward.lotteryStatus
                        self.upInfo = data.upInfo
                        self.lottoryId = data.reward.id

                        lib.setTitle(`${data.upInfo.name}的抽奖池`)

                        self.scrollTimer = window.setInterval(()=>{
                            self.scrollMenu()
                        },2000)
                        self.initLottoryTip()

                        if(data.reward.lotteryStatus==3) {
                            self.scrollCodeObj = new scrollCode(data.reward.userRecord.code)
                            self.changeCode()
                        }
                    } else {
                        lib.showTip(ret.msg);
                    }
                }
            });
        },
        doLottery(){

            let self = this 
            let url = `${lib.upAdminDomain}/act/doLottery`;
            let param = {
                uid : uid,
                token : token,
                id : self.lottoryId
            }
            let msg = `参与成功，今日抽奖将在${self.reward.rewardHour}：00开奖，为避免您错过开奖消息，建议您开启消息栏通知提醒。`

            $.ajax({
                type: "get",
                url: url,
                data: param,
                dataType: "jsonp",
                success: (ret)=>{
                    ret = lib.formatHttpProtocol(ret)

                    if(ret.code==0) {
                        self.getLotteryInfo()

                        setTimeout(()=>{
                            ext.openNotificationSettingIfNeeded(msg)
                        },800)
                    } else {
                        lib.showTip(ret.msg)
                    }
                }
            });
        },
        initLottoryTip(){
            let self = this
            let duration = ""

            //1未开始,2进行中,3,待开奖,4已结束,5没中奖,6中奖
            switch(self.lotteryStatus) {
                case 1 :
                    duration = self.getDuration(1)
                    self.lottoryTip = `距离抽奖还有 ${duration}`
                    break;
                case 2 :
                    self.lottoryTip = `今天抽奖剩余1次抽奖`
                    break;
                case 3 :
                    duration = self.getDuration(3)
                    self.lottoryTip = `距离开奖还有 ${duration}`
                    break;
                case 4 :
                case 5 :
                case 6 :
                    duration = self.getDuration(4)
                    self.lottoryTip = `距离下次抽奖还有 ${duration}`
                    break;
            }
        },
        getDuration(type){ //1未开始,3,待开奖,4已结束
            let self = this,duration
            let now = new Date()
            
            let todayStartTime = self.reward.dayStart*1000
            let todayRewardTime = self.reward.dayReward*1000
            let TomorrowStartTime = todayStartTime+24*60*60*1000
            let nowTime = now.getTime()

            switch(type) {
                case 1 :
                    duration = self.handldTime(todayStartTime-nowTime)
                    break;
                case 3 :
                    duration = self.handldTime(todayRewardTime-nowTime)
                    break;
                case 4 :
                    duration = self.handldTime(TomorrowStartTime-nowTime)
                    break;
            }

            return duration
        },
        handldTime(restTime) {
            restTime = restTime / 1000
            let hour = Math.floor(restTime%(60*60*24)/(60*60))
            let min = Math.floor(restTime%(60*60*24)%(60*60)/(60))

            if(hour>0) {
                return hour+" 小时 "+min+" 分钟"
            } else {
                return min+" 分钟"
            }
        },
        parseNum(num){
            return (num >= 10 ? num : "0"+num)
        },
        changeCode(){
            let self = this
            let timeLen = 800,timeInterval=50,timeStart=0
            
            let timer = window.setInterval(()=>{
                timeStart += timeInterval

                self.scrollCode = self.scrollCodeObj.getRandomCode()
                if(timeStart>=timeLen) {
                    self.scrollCode = self.userRecord.code
                    clearInterval(timer)
                }
            },timeInterval)
        },
        //中奖滚动
        scrollMenu(){
            let self = this
            let $list = $(".list-menu"),$item = $(".list-menu li"),$scroll=$(".menu-scroll")

            let listHeight = $list.height(),listLen = self.bingoUsers.length
            let itemHeight = listHeight / listLen 
            let viewHeight = $scroll.height()

            if(listLen <= 5) {
                clearInterval(self.scrollTimer)
                return
            }

            if(viewHeight-self.scrollHeight+10 > listHeight) {
                self.scrollHeight = 0;
            } else {
                self.scrollHeight = self.scrollHeight-itemHeight;
            }
        }
    },
    mounted () {
        let self = this

        self.getLotteryInfo()
    },
    watch: {
        
    },
    data() {
        return {
            scrollHeight : 0,
            scrollTimer : {},
            bingoUsers : [], //中奖名单
            reward : {}, //奖品
            upInfo : {}, //up主信息
            userRecord : {},
            lotteryStatus : 2, //1未开始,2进行中,3,待开奖,4已结束,5没中奖,6中奖
            lottoryTip : "",
            lottoryId : 0,
            scrollCode : '--------',
            scrollCodeObj : {}//滚动数字对象
        };
    },
    filters : {
        cutTime(value){
            return value ? value.substring(0,11) : ""
        }
    }
};