import GameReport from "../../FrameWork/Report/ZyZyReport";
import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import GMManager from "../Manager/GMManager";
import UserManager from "../Manager/UserManager";
import PrefabManage from "../PrefabManager/PrefabManage";
import GameBase from "../SCommon/GameBase";


const { ccclass, property } = cc._decorator;

enum BallPosIndex {
    StartPos,
    Pos1,
    Pos2,
    Pos3
}
let rateArray = {
    //默认
    DanKai_0: [50, 60, 75],
    ShuangKai_0: [60, 80, 80],
    //长白山WX_6
    DanKai_1: [45, 55, 65],
    ShuangKai_1: [50, 70, 80],
    //垃圾堆WX_8
    DanKai_2: [35, 45, 60],
    ShuangKai_2: [45, 60, 70],
    //快递站WX_11
    DanKai_3: [30, 40, 50],
    ShuangKai_3: [40, 50, 60],
    //松花江WX_13
    DanKai_4: [25, 35, 45],
    ShuangKai_4: [30, 40, 50],
    //冰雪世界WX_16
    DanKai_5: [15, 25, 35],
    ShuangKai_5: [20, 30, 40],
    //下水道DH_11
    DanKai_6: [10, 20, 30],
    ShuangKai_6: [15, 25, 35],

    MoneyRate: [0.1, 0.05, 0.01],
    GMDanKai: [100, 100, 100],
    GMShuangKai: [0, 100, 100]
}

@ccclass
export default class SanXianGuiDong extends GameBase {

    @property(cc.Node)
    ballNode: cc.Node = null;
    @property(cc.Node)
    spineMove: cc.Node = null;
    @property(cc.Node)
    successBox: cc.Node = null;
    @property(cc.Node)
    failBox: cc.Node = null;

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

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

    @property(cc.Node)
    btn_twice: cc.Node = null;
    @property(cc.Node)
    btn_restart: cc.Node = null;
    @property(cc.Node)
    btn_ad: cc.Node = null;

    @property(cc.Label)
    menkanLab: cc.Label = null


    touchArea1: cc.Node = null;
    touchArea2: cc.Node = null;
    touchArea3: cc.Node = null;

    ball: cc.Node = null;
    ballStartPos: cc.Node = null;
    ballPos1: cc.Node = null;
    ballPos2: cc.Node = null;
    ballPos3: cc.Node = null;


    // designRate:number = 0.34
    expendMoney: number = 1000
    awardMoney: number = 4000
    isFinishAni: boolean = true
    isCanSelectCup: boolean = false
    curChooseNode: cc.Node = null;
    curChooseBallIndex: number = 0

    tipsArray = [
        '搏一搏单车变摩托',
        '时也、命也,来一把',
    ]

    onDestroy(): void {
        super.onDestroy()
    }

    onLoad() {
        super.onLoad()
        Common5.playMusic("bg");
        this.touchArea1 = this.spineMove.getChildByName("touchArea1")
        this.touchArea2 = this.spineMove.getChildByName("touchArea2")
        this.touchArea3 = this.spineMove.getChildByName("touchArea3")

        this.ball = this.ballNode.getChildByName("ball")
        this.ballStartPos = this.ballNode.getChildByName("ballStartPos")
        this.ballPos1 = this.ballNode.getChildByName("ballPos1")
        this.ballPos2 = this.ballNode.getChildByName("ballPos2")
        this.ballPos3 = this.ballNode.getChildByName("ballPos3")

        this.initTouchEvent(this.touchArea1, "1")
        this.initTouchEvent(this.touchArea2, "2")
        this.initTouchEvent(this.touchArea3, "3")
        this.initGame()
        this.setBallPos(BallPosIndex.StartPos, false)
        this.refreshBtnStatus()
    }

    protected start(): void {
        // let qipao = this.node.getChildByName('qipao')
        // let lab = qipao.getChildByName('lab').getComponent(cc.Label)
        // lab.string = '还在犹豫什么?机会不要错过'
        // qipao.scale = 0.1
        // qipao.active = true
        let _rand = Common5.getRandomNum(0, 2)
        this.menkanLab.string = this.tipsArray[_rand]
    }


    initGame() {
        let rateIndex = 1//User.getSanXianGuiDongRateIndex()
        let colorArray = ['ball_100', 'ball_50', 'ball_10']
        for (let i = 0; i < this.moveball.childrenCount; i++) {
            let qiuNode = this.moveball.children[i]
            let ballNode = qiuNode.getChildByName('ball')
            qiuNode['nodecolorTag'] = colorArray[i]
            // if(GMManager.getToggleStatus_SanXianGuiDong()){
            //     qiuNode['danRate'] = rateArray.GMDanKai[i]
            //     qiuNode['shuangRate'] = rateArray.GMShuangKai[i]
            // }else{
            qiuNode['danRate'] = rateArray['DanKai_' + rateIndex][i]
            qiuNode['shuangRate'] = rateArray['ShuangKai_' + rateIndex][i]
            // }

            qiuNode["moneyRate"] = rateArray.MoneyRate[i]
            if (i == 0) {
                qiuNode['needMoney'] = 'ALLIN'
            }
            this.openTouchEvent(qiuNode)
        }


    }

    onStartBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        if (!this.curChooseNode) {
            PrefabManage.showTextTips('请选择任意小球', 1)
            return
        }


        if (!this.isFinishAni) {
            return
        }



        if (UserManager.getCurMoney() < this.expendMoney) {
            PrefabManage.showTextTips('余额不足挣钱去吧', 1)
            return
        }
        // User.setSanXianGuiDongFreeNum(User.getSanXianGuiDongFreeNum() - 1)
        this.refreshBtnStatus()
        this.moveball.active = false

        this.isFinishAni = false
        UserManager.subMoney(this.expendMoney)
        User.setYunshiChallenge(User.getYunshiChallenge() + 1)
        this.spineMove.getComponent(sp.Skeleton).setAnimation(0, "kaishi", false)
        cc.tween(this.node)
            .delay(0.5)
            .call(() => {
                this.setBallPos(BallPosIndex.StartPos, false)
            })
            .delay(2.2)
            .call(() => {
                this.isCanSelectCup = true
            })
            .start()
    }
    onBtnGetTimesAdClick() {
        if (!this.isFinishAni) {
            return
        }
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    Common5.ReportDY("inLevel", '时来运转-AD-获取次数');
                    // User.setSanXianGuiDongFreeNum(3)
                    // User.setSanXianGuiDongVDTime(User.getSanXianGuiDongVDTime()+1)
                    this.refreshBtnStatus()
                }
                else {
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }
    refreshBtnStatus() {
        let freeNum = 1//User.getSanXianGuiDongFreeNum()
        if (freeNum > 0) {
            this.btn_restart.active = true
            this.btn_ad.active = false
            // this.btn_restart.getChildByName("leftNums").getComponent(cc.Label).string = `开始(${freeNum}/3)`
            this.btn_restart.getChildByName("leftNums").getComponent(cc.Label).string = `开始`
        } else {

            // let vdTime = User.getSanXianGuiDongVDTime()
            // if(vdTime>=3){
            //     this.btn_restart.active = true
            //     this.btn_ad.active = false
            //     this.btn_restart.getChildByName("leftNums").getComponent(cc.Label).string = `开始`
            // }else{
            this.btn_restart.active = false
            this.btn_ad.active = true
            // this.btn_ad.getChildByName("freeNums").getComponent(cc.Label).string =  `免费畅玩(${vdTime}/3)` 
            // }

        }
    }
    countOpenTwice() {
        let arr = [0, 1, 2]
        let randomArr = Common5.getNumberFromArray(0, 3, 2)
        let openOneIndex = randomArr[0]
        let openTwoIndex = randomArr[1]
        let leftIndex = 0
        let temp = []
        temp.push(openOneIndex)
        temp.push(openTwoIndex)
        for (var i = 0; i < 3; i++) {
            if (arr[i] != openOneIndex && arr[i] != openTwoIndex) {
                leftIndex = arr[i]
            }
        }
        console.log("开第1个杯子=", openOneIndex)
        console.log("开第2个杯子=", openTwoIndex)

        let ballIndex = 0
        let num = Math.floor(Math.random() * 100)
        console.log("num=", num)
        if (num < this.curChooseNode['shuangRate']) {
            ballIndex = temp[Math.floor(Math.random() * 2)]
            console.log("中了", ballIndex)
        } else {
            ballIndex = leftIndex
            console.log("没中", leftIndex)
        }

        let spineStr = ""
        if ((openOneIndex == 0 && openTwoIndex == 1) || (openOneIndex == 1 && openTwoIndex == 0)) {
            spineStr = "erlian1"
        } else if ((openOneIndex == 1 && openTwoIndex == 2) || (openOneIndex == 2 && openTwoIndex == 1)) {
            spineStr = "erlian2"
        } else {
            spineStr = "erlian3"
        }
        this.setBallPos(BallPosIndex["Pos" + (ballIndex + 1)], true)
        this.spineMove.getComponent(sp.Skeleton).setAnimation(0, spineStr, false)
        this.scheduleOnce(() => {
            this.isFinishAni = true
            //选中了
            if (ballIndex == openOneIndex || ballIndex == openTwoIndex) {
                this.successBox.active = true
                //恭喜您选对了,获得4000元!
                let aaa = Common5.getNumberChangeHanzi(this.awardMoney) + ""
                this.successlab.string = '恭喜您选对了,获得' + aaa + "元!"
                Common5.showInterstitialAd()

            } else {
                this.failBox.active = true
            }
        }, 3)
    }
    onTwiceBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        if (!this.curChooseNode) {
            PrefabManage.showTextTips('请选择任意小球', 1)
            return
        }

        let needMoney = this.curChooseNode['needMoney']
        // if(needMoney == 'ALLIN'){
        //     PrefabManage.showTextTips('ALLIN不可二连开',1)
        //     return

        // }
        if (UserManager.getCurMoney() < this.expendMoney) {
            PrefabManage.showTextTips('余额不足挣钱去吧', 1)
            return
        }
        if (!this.isFinishAni) {
            return
        }
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    UserManager.subMoney(this.expendMoney)
                    this.reportKey(() => {
                        GameReport.ADReport('时来运转二连开', 1)
                    })
                    Common5.ReportDY("inLevel", '时来运转-AD-二连开');
                    User.setYunshiChallenge(User.getYunshiChallenge() + 1)
                    this.moveball.active = false
                    this.isFinishAni = false
                    this.spineMove.getComponent(sp.Skeleton).setAnimation(0, "kaishi", false)
                    cc.tween(this.node)
                        .delay(0.5)
                        .call(() => {
                            this.setBallPos(BallPosIndex.StartPos, false)
                        })
                        .delay(2.2)
                        .call(() => {
                            // this.isCanSelectCup = true
                            this.countOpenTwice()
                        })
                        .start()
                }
                else {
                    this.reportKey(() => {
                        GameReport.ADReport('时来运转二连开', 0)
                    })
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }
    initTouchEvent(node, index) {
        node.on(cc.Node.EventType.TOUCH_START, this.touchStartEvent, this, true);
        node.attr({ idIndex: index })
    }
    touchStartEvent(event) {
        Common5.playEffect("CommonRes/sound/按键点击")
        if (!this.isFinishAni && this.isCanSelectCup) {
            this.isCanSelectCup = false
            let selectId = event.target.idIndex
            let bSelect = this.countIsSelectTure()
            if (bSelect) {
                this.setBallPos(BallPosIndex["Pos" + selectId], true)
                this.spineMove.getComponent(sp.Skeleton).setAnimation(0, "kai" + selectId, false)
                console.log("选择正确")
            } else {
                console.log("选择错误")
                this.spineMove.getComponent(sp.Skeleton).setAnimation(0, "kai" + selectId, false)
            }
            this.scheduleOnce(() => {
                this.isFinishAni = true
                if (bSelect) {
                    this.successBox.active = true
                    //恭喜您选对了,获得4000元!
                    let aaa = Common5.getNumberChangeHanzi(this.awardMoney) + ""
                    this.successlab.string = '恭喜您选对了,获得' + aaa + "元!"
                    Common5.showInterstitialAd()
                } else {
                    this.failBox.active = true
                }
            }, 1)
        }
    }

    onSuccessSureBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        this.successBox.active = false
        UserManager.addMoney(this.awardMoney)
        // Common5.showMoneyFlyParticle(this.successBox)
        this.refreshAniStatus()
    }
    onFailSureBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        this.failBox.active = false
        this.refreshAniStatus()
    }
    onFanQianBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    this.reportKey(() => {
                        GameReport.ADReport('时来运转返钱50%', 1)
                    })
                    Common5.ReportDY("inLevel", '时来运转-AD-返钱50%');
                    this.failBox.active = false
                    this.refreshAniStatus()
                    UserManager.addMoney(Math.floor(this.expendMoney * 0.5))
                }
                else {
                    this.reportKey(() => {
                        GameReport.ADReport('时来运转返钱50%', 0)
                    })
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }

    onAdBtnClick() {
        Common5.playEffect("CommonRes/sound/按键点击")
        let tab = {
            onClose: (finish) => {
                if (finish) {

                    this.successBox.active = false
                    UserManager.addMoney(this.awardMoney * 2)
                    // Common5.showMoneyFlyParticle(this.saleGet)
                    this.refreshAniStatus()
                }
                else {
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }
    refreshAniStatus() {
        this.curChooseNode = null
        this.moveball.active = true
        for (let i = 0; i < this.moveball.childrenCount; i++) {
            let qiuNode = this.moveball.children[i]
            let ballNode = qiuNode.getChildByName('ball')
            ballNode.active = true
        }

        this.setBallPos(BallPosIndex.StartPos, false)
        this.spineMove.getComponent(sp.Skeleton).clearTracks()
        this.spineMove.getComponent(sp.Skeleton).setToSetupPose()
    }
    setBallPos(pos, isShow) {
        let parentNode = null
        if (pos == BallPosIndex.StartPos) {
            parentNode = this.ballStartPos
        } else if (pos == BallPosIndex.Pos1) {
            parentNode = this.ballPos1
        } else if (pos == BallPosIndex.Pos2) {
            parentNode = this.ballPos2
        } else if (pos == BallPosIndex.Pos3) {
            parentNode = this.ballPos3
        }
        this.ball.setPosition(0, 0)
        this.ball.active = isShow
        this.ball.setParent(parentNode)
    }
    //计算是否中奖
    countIsSelectTure() {
        let num = Math.floor(Math.random() * 100)
        console.log("Random num==", num)

        if (num < this.curChooseNode['danRate']) {
            return true
        } else {
            return false
        }
    }

    openTouchEvent(node) {
        node.on(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)

        node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEndNode, this)
        node.on(cc.Node.EventType.TOUCH_END, this.touchEndNode, this)
    }

    closeTouchEvent(node: cc.Node) {
        node.off(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)

        node.off(cc.Node.EventType.TOUCH_CANCEL, this.touchEndNode, this)
        node.off(cc.Node.EventType.TOUCH_END, this.touchEndNode, this)
    }

    touchStartNode(event) {
        //
        Common5.playEffect("CommonRes/sound/按键点击")
        let target = event.target
        target.scale = 1.05
    }


    touchEndNode(event) {

        let target = event.target
        target.scale = 1.0
        if (this.curChooseNode == target) {
            console.log('一样的')
            return
        }
        if (User.getMoney() <= 0) {
            PrefabManage.showTextTips('去地摊或商人处换钱再来', 1)
            return
        }

        // let needMoneySpec =  target['needMoney']
        // if(needMoneySpec == 'ALLIN'){
        //     if(User.getMoney()<2000000){
        //         Common5.showTips_customTime('最低限额200万ALLIN',2)
        //         return
        //     }
        //     this.btn_twice.active = false
        // }else{
        //     this.btn_twice.active = true
        // }


        for (let i = 0; i < this.moveball.childrenCount; i++) {
            let qiuNode = this.moveball.children[i]
            let ballNode = qiuNode.getChildByName('ball')
            ballNode.active = true
        }

        for (let i = 0; i < this.moveball.childrenCount; i++) {
            let qiuNode = this.moveball.children[i]
            if (qiuNode == target) {
                let ballNode = qiuNode.getChildByName('ball')
                ballNode.active = false
            }
        }

        this.curChooseNode = target

        this.ball.active = true
        for (let i = 0; i < this.ball.childrenCount; i++) {
            let qiuNode = this.ball.children[i]
            qiuNode.active = false
        }
        //copynode节点
        let samllballNode = target.getChildByName('ball')
        var prefabNode = cc.instantiate(samllballNode);


        prefabNode.parent = target.parent;
        prefabNode.active = true
        let posi = Common5.getNodeToTargetPos(prefabNode, this.ball)

        prefabNode.setPosition(target.getPosition())
        cc.tween(prefabNode)
            .to(0.2, { x: posi.x, y: posi.y })
            .call(() => {
                //小球变化
                let needMoney = Math.floor(this.curChooseNode['moneyRate'] * User.getMoney())
                let nodecolorTag = this.curChooseNode['nodecolorTag']

                this.awardMoney = needMoney * 2
                this.expendMoney = needMoney
                for (let i = 0; i < this.ball.childrenCount; i++) {
                    let node_ = this.ball.children[i]
                    node_.active = false
                }
                let nodeball_ = this.ball.getChildByName(nodecolorTag)
                nodeball_.active = true


                prefabNode.removeFromParent()
            })
            .start()
    }
}