import PanelPrize from "./PanelPrize";
import { NetManager } from "./NetManager";
import PanelRecord from "./PanelRecord";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Main extends cc.Component {
    @property(cc.Node)
    questionPanel: cc.Node = null;

    @property(cc.Node)
    lotteryPanel: cc.Node = null;

    @property(cc.Node)
    questionNode: cc.Node = null;

    @property(cc.Button)
    btnRoll: cc.Button = null;

    @property(cc.Node)
    btnPrev: cc.Node = null;

    @property(cc.Node)
    btnNext: cc.Node = null;

    @property(cc.Node)
    btnUpload: cc.Node = null;

    @property({ type: cc.AudioClip, displayName: "背景音乐" })
    bgm: cc.AudioClip = null;

    @property(cc.Node)
    musicBtnNode: cc.Node = null;

    @property(cc.Node)
    popNode: cc.Node = null;

    @property(cc.Label)
    labelTitle: cc.Label = null;

    @property(cc.Label)
    rewardType: cc.Label[] = [];

    @property(cc.Node)
    wheel: cc.Node = null;

    @property(cc.Prefab)
    preload: cc.Prefab[] = [];

    // @property(cc.Sprite)
    customImageSp: cc.Sprite[] = [];

    @property(cc.Prefab)
    optQuestionItem: cc.Prefab = null;

    @property(cc.Prefab)
    inputQuestionItem: cc.Prefab = null;

    private questionCompArr: any[] = [];
    private isUploading: boolean = false
    private curQNumber: number = 1;
    private curPageIndex: number = -1;
    private bgmAudioID = -1;
    private answerResult = {}

    private isRolling: boolean = false;
    private isMuted: boolean = false;

    private isPlayingPage: boolean = false;

    private MAX_QUESTION_NUM: number = 0
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.customImageSp.push(cc.find('bg', this.questionPanel).getComponent(cc.Sprite))
        this.customImageSp.push(cc.find('bg', this.lotteryPanel).getComponent(cc.Sprite))
        this.customImageSp.push(cc.find('title', this.lotteryPanel).getComponent(cc.Sprite))
        for (let i = 1; i <= 8; ++i) {
            this.customImageSp.push(cc.find('prize' + i, this.wheel).getComponent(cc.Sprite))
        }
        this.questionPanel.active = false
        this.lotteryPanel.active = false
        this.isPlayingPage = false
        this.questionNode.removeAllChildren()
        cc.log(this.customImageSp.length)
    }

    start() {
        NetManager.getInst().initNet(() => {

            this.setupCustomImage()
            this.initUI()
            this.reset()

            this.playBGM(true)

            if (NetManager.getInst().status > 0) {
                this.changeLotteryPanel()
            }
            //无需答题，直接进入抽奖
            // this.playBGM(true);
            // this.changeLotteryPanel();
        })
    }

    setupCustomImage() {
        let bg = NetManager.getInst().preloadImg['bg']
        let title = NetManager.getInst().preloadImg['title']

        if (bg) {
            this.customImageSp[0].spriteFrame = bg
            this.customImageSp[1].spriteFrame = bg
        }
        if (title) {
            this.customImageSp[2].spriteFrame = title
        }

        for (let i = 3; i < this.customImageSp.length; ++i) {
            let idx = i - 2
            let item = NetManager.getInst().preloadImg['item' + idx]
            if (item) {
                this.customImageSp[i].spriteFrame = item
            }
        }
    }

    initUI() {
        this.questionPanel.active = true;
        this.lotteryPanel.active = false;
        this.labelTitle.string = NetManager.getInst().activityName

        const questionData = NetManager.getInst().questions
        this.MAX_QUESTION_NUM = questionData.length
        for (let i = 0; i < questionData.length; ++i) {
            let itemData = questionData[i]

            let itemNode = cc.instantiate((itemData.type == 3) ? this.inputQuestionItem : this.optQuestionItem)
            this.questionNode.addChild(itemNode)

            let comp = itemNode.getComponent((itemData.type == 3) ? 'InputQuestionItem' : 'OptQuestionItem')
            comp.loadData(i + 1, itemData)
            this.questionCompArr.push(comp)
        }

        const rewardTypes = NetManager.getInst().lotteryItems;
        let index = 0
        for (let idx in rewardTypes) {
            this.rewardType[index++].string = rewardTypes[idx]
        }
    }

    reset() {
        this.questionPanel.active = true;
        this.lotteryPanel.active = false;
        this.answerResult = {}
        this.curPageIndex = -1

        for (let i = 0; i < this.questionCompArr.length; ++i) {
            this.questionCompArr[i].reset()
        }

        let visitSize: any = cc.visibleRect
        for (let i = 0; i < this.questionCompArr.length; ++i) {
            let widget = this.questionCompArr[i].node.getComponent(cc.Widget)
            widget.updateAlignment()
            widget.enabled = false

            this.questionCompArr[i].node.x = visitSize.width + 50
        }
        this.showQuestion(1)
    }

    showQuestion(idx: number = 1) {

        idx = idx >= this.MAX_QUESTION_NUM ? this.MAX_QUESTION_NUM : idx
        idx = idx <= 0 ? 1 : idx

        if (this.curPageIndex == idx) {
            return
        }

        let n = idx - 1
        let moveToLeft = idx > this.curPageIndex
        this.curQNumber = idx
        this.curPageIndex = idx
        this.isPlayingPage = true
        let visitSize: any = cc.visibleRect
        let curNode = moveToLeft ? this.questionCompArr[n].node : this.questionCompArr[n + 1].node;
        let backY = curNode.y
        if (moveToLeft) {
            curNode.x = visitSize.width + 50
            curNode.y = visitSize.height
            curNode.angle = -60
            cc.tween(curNode).sequence(
                cc.tween().to(0.3, { x: 0, y: backY, angle: 0 }),
                cc.callFunc(() => {
                    curNode.x = 0
                    curNode.y = backY
                    curNode.angle = 0
                    this.isPlayingPage = false
                })
            ).start()
        }
        else {
            cc.tween(curNode).sequence(
                cc.tween().to(0.3, { x: visitSize.width + 50, y: -visitSize.height, angle: 30 }),
                cc.callFunc(() => {
                    curNode.x = visitSize.width + 50
                    curNode.y = backY
                    curNode.angle = 0
                    this.isPlayingPage = false
                })
            ).start()
        }

        this.btnPrev.active = false
        this.btnNext.active = false
        this.btnUpload.active = false
        if (this.curQNumber == this.MAX_QUESTION_NUM) {
            this.btnPrev.active = (this.curQNumber != 1)
            this.btnUpload.active = true
        }
        else if (this.curQNumber == 1) {
            this.btnNext.active = true
        }
        else {
            this.btnPrev.active = true
            this.btnNext.active = true
        }
    }

    onClickNext() {
        if (this.isPlayingPage) {
            return
        }
        this.updateAnswerResult()
        this.showQuestion(++this.curQNumber)

        let animComp = this.musicBtnNode.getComponent(cc.Animation)
        if (this.bgmAudioID == -1 && !this.isMuted) {
            this.bgmAudioID = cc.audioEngine.play(this.bgm, true, 0.5);
            animComp.play()
        }
    }

    onClickPrev() {
        if (this.isPlayingPage) {
            return
        }
        this.updateAnswerResult()
        this.showQuestion(--this.curQNumber)
    }

    onClickUpload() {
        if (this.isUploading) {
            return
        }
        this.isUploading = true
        this.updateAnswerResult()
        NetManager.getInst().submitAnswer(this.answerResult, (data) => {
            this.isUploading = false
            if (data.code == 200) {
                if (data.data.lottery) {
                    this.loadPopUp("panelSuccess")
                }
                else {
                    this.loadPopUp("panelFailed", (node: cc.Node) => {
                        let label = cc.find("btnAgain/label", node).getComponent(cc.Label)
                        label.string = "本轮仅答对" + data.data.rightCount + "道题"
                    })
                }
            }
        })
    }

    onClickBGM(toggle: cc.Toggle) {
        if (toggle.isChecked) {
            this.playBGM(false)
            this.isMuted = true
        }
        else {
            this.playBGM(true)
            this.isMuted = false
        }
    }

    playBGM(play: boolean) {
        let animComp = this.musicBtnNode.getComponent(cc.Animation)
        if (this.bgmAudioID >= 0) {
            cc.audioEngine.stop(this.bgmAudioID);
            this.bgmAudioID = -1;
        }

        if (play) {
            if (this.bgmAudioID == -1) {
                this.bgmAudioID = cc.audioEngine.play(this.bgm, true, 0.5);
            }
            animComp.play()
        }
        else {
            this.musicBtnNode.angle = 0
            animComp.stop()
        }
    }

    updateAnswerResult() {
        if (!this.answerResult[this.curQNumber]) {
            this.answerResult[this.curQNumber] = {}
        }

        this.answerResult[this.curQNumber] = this.questionCompArr[this.curQNumber - 1].getResult()
    }

    loadPopUp(name: string, complete: Function = null) {
        cc.resources.load("prefabs/" + name, cc.Prefab, (err, prefab: cc.Prefab) => {
            if (!err) {
                let node = cc.instantiate(prefab);
                this.popNode.addChild(node);
                complete && complete(node)
            }
        });
    }

    changeLotteryPanel() {
        this.questionPanel.active = false;
        this.lotteryPanel.active = true;

        this.btnRoll.interactable = true
        if (NetManager.getInst().status > 0) {
            this.btnRoll.interactable = false
        }
    }

    randomNum(min: number, max: number) {
        var range = max - min;
        var rand = Math.random();
        if (Math.round(rand * range) == 0) {
            return min + 1;
        } else if (Math.round(rand * max) == max) {
            return max - 1;
        } else {
            var num = min + Math.round(rand * range) - 1;
            return num;
        }
    }

    getSpinAngle(rewardId: number) {
        var angle = 0;
        switch (rewardId) {
            case 8:
                //行家初遇  卡通猴支架
                angle = this.randomNum(320, 355);
                break;
            case 7:
                //行家初遇  电动牙刷
                angle = this.randomNum(275, 310);
                break;
            case 6:
                //乘风破浪  手工日历摆件
                angle = this.randomNum(230, 265);
                break;
            case 5:
                //行家初遇  立体钻石拼装小颗粒
                angle = this.randomNum(185, 220);
                break;
            case 4:
                //锦瑟年华  SKII前男友面膜
                angle = this.randomNum(140, 175);
                break;
            case 3:
                //行家初遇  ins卡通吊脚娃娃
                angle = this.randomNum(95, 130);
                break;
            case 2:
                //行家初遇  国潮手持风扇
                angle = this.randomNum(50, 80);
                break;
            case 1:
                //出类拔萃  HUAWEIFreeBudsPro
                angle = this.randomNum(5, 40);
                break;
        }

        return angle;
    }


    onClickLottery() {
        if (this.isRolling) {
            return;
        }

        if (!CC_DEV) {
            this.btnRoll.interactable = false
        }

        NetManager.getInst().rollItem((id: number, name: string) => {
            if (id > 0) {
                this.wheel.angle = 0;
                this.isRolling = true;
                NetManager.getInst().prize = id;
                NetManager.getInst().recordTime = new Date().Format("yyyy-MM-dd hh:mm:ss");

                // 转盘效果
                let ang = -this.getSpinAngle(id)
                cc.log("id = ", id, " angle = ", ang, " name = ", name)
                let rotateAngle = ang + 3600;

                cc.Tween.stopAll()
                cc.tween(this.wheel).sequence(
                    cc.tween().to(1.8, { angle: -rotateAngle }, { easing: 'cubicOut' }),
                    cc.tween().delay(0.3),
                    cc.callFunc(() => {
                        if (CC_DEV) {
                            this.isRolling = false
                        }
                        this.onShowRollResult();
                    })
                ).start()
            }
            else {
                this.btnRoll.interactable = true
                this.isRolling = false
            }
        })
    }


    private onShowRollResult() {

        let prize = NetManager.getInst().prize
        setTimeout(() => {
            let str = NetManager.getInst().lotteryPrize[prize]
            if (str == "谢谢参与") {
                this.loadPopUp("panelSorry")
            }
            else {
                this.loadPopUp("panelPrize", (node: cc.Node) => {
                    let comp = node.getComponent(PanelPrize)
                    comp.labelReward.string = "抽中了【" + NetManager.getInst().lotteryItems[prize] + "】"

                    let str = NetManager.getInst().lotteryPrize[prize]
                    str = str.replace(/[\r\n]/g, "");
                    // comp.labelPrize.string = "获得「" + str + "」"
                    comp.labelPrize.string = "「" + str + "」"
                })
            }
        }, 300);
    }

    private onClickRecord() {
        let prize = NetManager.getInst().prize
        let str = NetManager.getInst().lotteryPrize[prize]
        if (str == "谢谢参与") {
            this.loadPopUp("panelSorry")
            return
        }
        this.loadPopUp("panelRecord", (node: cc.Node) => {
            let comp = node.getComponent(PanelRecord)
            if (prize > 0) {
                comp.labelEmpty.node.active = false
                comp.recordInfoNode.active = true
                comp.labelPrize.string = NetManager.getInst().lotteryItems[prize]

                let str = NetManager.getInst().lotteryPrize[prize]
                str = str.replace(/[\r\n]/g, "");
                comp.labelReward.string = str

                comp.labelTime.string = NetManager.getInst().recordTime
            }
            else {
                comp.labelEmpty.node.active = true
                comp.recordInfoNode.active = false
            }
        })
    }

    onClickBack() {
        if (window['aladdin']) {
            window['aladdin'].navigator.back()
        }
    }
}
