import PlaySceneBase from "../../libs/new_wx/components/PlaySceneBase";
import showAlertPanel from "../../libs/new_wx/ctrls/showAlertPanel";
import MovieClipManager from "./../MovieClipManager"
import wait from "../../libs/new_tc/wait";
import { NetManager, DataManager } from "../../libs/tw/index";
import { GDispatcher } from "../../libs/tc/index";
import PanelCtrl from "./../../libs/new_wx/ctrls/panelCtrl";
import SceneCtrl from "./../../libs/new_wx/ctrls/sceneCtrl";
import { ModuleTypes } from "./../../libs/new_wx/types/sceneTypes";
import { Buried } from "../../libs/tw/index";
import { sendHome, sendDoJoin, sendSubmit } from "../Net";
import Loading from "../../libs/new_wx/components/Loading";
import { showToast } from "../../libs/new_wx/ctrls/toastCtrl";
import { newShowLog, newClickLog } from "../Main";

export default class PlayScene extends PlaySceneBase {


    public bowl: eui.Rect;
    public exemptionTxt: eui.Label;
    public image: eui.Image;
    public option_0: eui.Image;
    public option_1: eui.Image;
    public option_2: eui.Image;
    public option_3: eui.Image;
    public gameStep0: eui.Rect;
    public gameStep1: eui.Rect;
    public gameStep2: eui.Rect;
    public gameStep3: eui.Rect;
    public down_npc_1: eui.Image;
    public down_npc_2: eui.Image;
    public down_npc_3: eui.Image;
    public down_npc_4: eui.Image;
    public down_npc_5: eui.Image;
    public down_npc_6: eui.Image;
    public down_npc_7: eui.Image;
    public down_npc_8: eui.Image;
    public water_npc_1: eui.Image;
    public water_npc_2: eui.Image;
    public water_npc_3: eui.Image;
    public water_npc_4: eui.Image;
    public water_npc_5: eui.Image;
    public water_npc_6: eui.Image;
    public water_npc_7: eui.Image;
    public water_npc_8: eui.Image;
    public playBtn: eui.Rect;
    public boomBody: eui.Rect;

    public timesTxt: eui.Label;

    public playTips: eui.Image;



    private loadResTimeClear = []

    private Events = []

    private speed = window["speed"] || 2;

    //结束时间
    private endPhaseTime: number;
    //是否有资格参加
    private qualification: boolean;
    //活动次数
    private remainingNum: number

    //参与接口标记
    doJoinMark: boolean;

    start(data?) {
        super.start();

        //曝光埋点
        newShowLog(1);
        newShowLog(2);
        newShowLog(3);

        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            newClickLog(2)
            PanelCtrl.instance.show(ModuleTypes.RULE_PANEL)
        }, this)

        this.recordBtn.once(egret.TouchEvent.TOUCH_TAP, () => {
            newClickLog(3)
            setTimeout(() => {
                window.location.href = window["recordUrl"]
            }, 1000)
        }, this)



        // alert()
        MovieClipManager.instance.init();

        //禁用
        this.playBtn.enabled = false;

        this.updateScene();

    }

    updateScene() {
        Loading.instace.show();
        sendHome((s, res) => {
            if (s) {
                Loading.instace.hide();
                this.endPhaseTime = res.data.endPhaseTime;
                console.log(res.data.endPhaseTime)
                this.qualification = res.data.qualification;
                //修改文案
                if (res.data.qualification && res.data.remainingNum) {
                    this.timesTxt.text = "游戏次数：" + res.data.remainingNum + "次";
                    this.remainingNum = res.data.remainingNum;
                } else {
                    this.timesTxt.text = "游戏次数：0次";
                    this.remainingNum = 0;
                }
            } else {
                //不成功转圈不消失
            }
        })
    }

    //每次结束后重置
    reset() {
        this.playBtn.enabled = true;
        this.doJoinMark = false;
    }



    initEvents() {
        super.initEvents()
        this.addEventListener(egret.Event.ENTER_FRAME, this.enterFrame, this)
        this.playBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.Tap_playBtn, this)
        GDispatcher.addEvent("loadClipSuccess", this.Events["loadClipSuccess"] = this.overMovieClipLoad.bind(this), this)
    }
    removeEvents() {
        super.removeEvents();
        this.removeEventListener(egret.Event.ENTER_FRAME, this.enterFrame, this)
        this.playBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.Tap_playBtn, this)
        // GDispatcher.removeEvent("loadClipSuccess",this.Events["loadClipSuccess"],this)

        this.clearTime.forEach((clear) => {
            clearInterval(clear);
            clearTimeout(clear);
        })
    }

    private Tap_playBtn() {
        //非白名单用户
        if (!this.qualification) {
            showToast("仅限特定用户参与");
            return
        }
        //时间已结束用户
        if (Date.now() > this.endPhaseTime) {
            showToast("活动已结束");
            return
        }
        //次数不足用户
        if (!this.remainingNum) {
            showToast("今日已没有次数了");
            return
        }
        // NetManager.ins.clickLog(this.exposure["playBtn"]);
        this.playBtn.enabled = false;

        this.setPlayerGo();

    }

    //  exposure=[]
    public doloseGameBuried() {
        Buried.init();
        var appId = DataManager.ins.gameCfgData.appInfo.appId;
        var oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
        var dpmcloseBtn = appId + '.110.6.1';
        var dcmcloseBtn = "202." + oaId + ".0.0";
        this.exposure["loseGame"] = Buried.createExposure(dpmcloseBtn, dcmcloseBtn);
        NetManager.ins.showLog(this.exposure["loseGame"]);
    }

    private enterFrame() {
        this.npcBody.forEach((npc, j) => {
            for (var i = 0; i <= 3; i++) {
                if (this.collide(this[`option_${i}`], npc)) {
                    if (!npc.targetState) {
                        clearTimeout(this.clearTime["down_npcA1"])
                        clearTimeout(this.clearTime["down_npcA2"])
                        clearTimeout(this.clearTime["down_npcA3"])
                        npc.targetGift = `option_${i}`
                        npc.targetState = true;
                        this[`option_${i}`].targetGift = npc;
                        this.npc[j].alpha = 0;
                        this[`down_npc_${j + 1}`].alpha = 0;
                        this[`water_npc_${j + 1}`].alpha = 0;
                        this.npcd[j].alpha = 1;
                        egret.Tween.pauseTweens(npc)
                        egret.Tween.pauseTweens(npc.anmation)
                        // this.onGift(i)

                        //逻辑待写//中了发接口
                        setTimeout(() => {
                            this.lot();
                        }, 500)

                    }
                }
            }

            if (npc.targetState == true) {
                npc.x = this[npc.targetGift].x + 80;
                npc.y = this[npc.targetGift].y + 120;

                if (this[npc.targetGift].x < -200) {
                    npc.targetState = false;
                    npc.targetGift = ``
                    npc.x = -400;
                    npc.y = -400;
                }
            }
        })

    }



    private collide(rect1, rect2) {
        var _rect1 = {
            x: rect1.x,
            y: rect1.y,
            width: rect1.width - 10,
            height: rect1.height - 10,
        }

        var maxX, maxY, minX, minY
        maxX = _rect1.x + _rect1.width >= rect2.x + rect2.width ? _rect1.x + rect1.width : rect2.x + rect2.width
        maxY = _rect1.y + _rect1.height >= rect2.y + rect2.height ? _rect1.y + rect1.height : rect2.y + rect2.height
        minX = _rect1.x <= rect2.x ? _rect1.x : rect2.x
        minY = _rect1.y <= rect2.y ? _rect1.y : rect2.y

        if (maxX - minX <= _rect1.width + rect2.width && maxY - minY <= _rect1.height + rect2.height) {
            return true
        } else {
            return false
        }
        // var condition = 

        // return Math.abs(rect1.y -  rect2.y) < (rect2.height + rect1.height) * 0.4
        // && Math.abs(rect1.x - rect2.x) < (rect2.width + rect1.width) * 0.4;
    }


    playAnimation() {
        super.playAnimation()
    }
    private npc = []
    private npcd = []
    private npcBody = []
    private bowlAn
    private spray
    private boom

    private overMovieClipLoad() {

        localStorage.gameState = "";
        localStorage.gameState2 = ""

        //延时
        setTimeout(() => {
            this.playBtn.enabled = true;
        }, 1000)

        this.bowlAn = MovieClipManager.instance.getMovieClipByName(`bowlAn_0`)
        this.bowl.addChild(this.bowlAn)

        this.spray = MovieClipManager.instance.getMovieClipByName(`spray_0`)
        this.bowl.addChild(this.spray)

        this.boom = MovieClipManager.instance.getMovieClipByName(`boom_0`)
        this.boom.x = 0;
        this.boom.y = 0;
        this.boom.anchorOffsetX = 315;
        this.boom.anchorOffsetY = 210;
        this.boomBody.addChild(this.boom)
        //this.boom.gotoAndPlay(0,-1);



        for (var i = 0; i < 8; i++) {
            this.npc[i] = MovieClipManager.instance.getMovieClipByName(`npc${i + 1}_0`)
            this.npc[i].anchorOffsetX = 90;
            this.npc[i].anchorOffsetY = 180;
            this.npc[i].x = 0;
            this.npc[i].y = 0;
            this.npc[i].gotoAndPlay(0, -1);
            this.npcBody[i] = new eui.Group();
            this.npcBody[i].id = "body" + i;
            // console.log(this.npcBody[i].width)
            this.addChildAt(this.npcBody[i], 12)
            // console.log(i)


            this[`down_npc_${i + 1}`].anchorOffsetX = 60;
            this[`down_npc_${i + 1}`].anchorOffsetY = 70;
            this[`down_npc_${i + 1}`].x = 0;
            this[`down_npc_${i + 1}`].y = 0;

            this[`water_npc_${i + 1}`].anchorOffsetX = 60;
            this[`water_npc_${i + 1}`].anchorOffsetY = 40;
            this[`water_npc_${i + 1}`].x = 0;
            this[`water_npc_${i + 1}`].y = 0;

            this.npcd[i] = MovieClipManager.instance.getMovieClipByName(`npcd${i + 1}_0`)
            this.npcd[i].anchorOffsetX = 160;
            this.npcd[i].anchorOffsetY = 40;
            this.npcd[i].x = 0;
            this.npcd[i].y = 0;
            this.npcd[i].gotoAndPlay(0, -1);


            this.npcBody[i].addChildAt(this.npc[i], 12)
            this.npcBody[i].addChildAt(this.npcd[i], 12)
            this.npcBody[i].addChildAt(this[`down_npc_${i + 1}`], 12)
            this.npcBody[i].addChildAt(this[`water_npc_${i + 1}`], 12)
            this.npcBody[i].x = -400;
            this.npcBody[i].y = -400;
        }
        this.stepInit()
        this.setOptions()

    }

    private setOptions() {
        for (var i = 0; i < 4; i++) {
            this[`option_${i}`].x = 800
        }
        var _j = 0
        this.clearTime["setOptions"] = setInterval(() => {
            egret.Tween.get(this[`option_${_j}`]).set({ x: 800, y: 650 }).to({ x: -300, y: 650 }, 2500 * this.speed);
            _j++
            if (_j > 3) {
                _j = 0
            }
        }, 1000 * this.speed * 1.2)
    }

    private _j = 0;

    private stepInit() {
        this.npcBody.forEach((npc, i) => {
            this.setNpcStep(npc, -1, i)
            this.setNpcStep(npc, i - 5, i)
        })
    }

    private setPlayerGo() {
        this.npcBody.forEach((npc, i) => {
            if (npc["stepNum"] >= 3) {
                this.setNpcStep(npc, -5, i)
            }
            this.setNpcStep(npc, npc["stepNum"] + 1, i)
        })
    }

    private setNpcStep(body, num, i) {
        // console.log(i)
        body.stepNum = num;
        this.npc[i].alpha = 0;
        this[`down_npc_${i + 1}`].alpha = 0;
        this[`water_npc_${i + 1}`].alpha = 0;
        this.npcd[i].alpha = 0;
        if (num == 0) {
            body.x = this.gameStep0.x;
            body.y = this.gameStep0.y;
            this.npc[i].alpha = 1;
        } else if (num == 1) {
            this.npc[i].alpha = 1;
            egret.Tween.get(body).to({ x: this.gameStep1.x, y: this.gameStep1.y }, 1000, egret.Ease.quintOut);
        } else if (num == 2) {
            this.npc[i].alpha = 1;
            egret.Tween.get(body).to({ x: this.gameStep2.x, y: this.gameStep2.y }, 1000, egret.Ease.quintOut);
        } else if (num == 3) {
            this.npc[i].alpha = 1;
            this[`down_npc_${i + 1}`].alpha = 0;
            egret.Tween.get(body).to({ x: body.x + 100, y: body.y - 50 }, 300);
            this.clearTime["down_npcA1"] = setTimeout(() => {
                this.clearTime["down_npcA2"] = setTimeout(() => {
                    this.npc[i].alpha = 0;
                    this[`down_npc_${i + 1}`].alpha = 1;
                }, 600)
                body.anmation = egret.Tween.get(body).to({ x: this.gameStep3.x, y: this.gameStep3.y }, 1000, egret.Ease.backIn);
                //egret.Tween.removeTweens(body.anmation)
                this.clearTime["down_npcA3"] = setTimeout(() => {
                    console.log("掉入碗中")

                    // this["remove1An"].play(0)
                    this.bowlAn.gotoAndPlay(0);
                    this.spray.gotoAndPlay(0);
                    this[`down_npc_${i + 1}`].alpha = 0;
                    this[`water_npc_${i + 1}`].alpha = 1;

                    //扣次数
                    setTimeout(() => {
                        this.countTimes();
                    }, 1000)
                }, 1000)
            }, 300)
        } else if (num < 0) {
            body.x = this.gameStep0.x - 400;
            body.y = this.gameStep0.y;

        }
    }

    //抽奖
    lot() {
        Loading.instace.show();
        //扣次数
        sendDoJoin((s, res) => {
            if (s) {
                //修改次数，更新文案
                this.timesTxt.text = "游戏次数：" + res.data/*.remainingNum*/ + "次";
                this.remainingNum = res.data//.remainingNum;
                //抽奖
                sendSubmit((ss, ress) => {
                    Loading.instace.hide();
                    this.playBtn.enabled = true;
                    if (ss &&
                        ress.data &&
                        ress.data.prizeId != "thanks" &&
                        ress.data.prizeType) {
                        //出中奖的
                        PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, ress.data);
                    } else {//510003已经中奖过的
                        //出没中奖的
                        PanelCtrl.instance.show(ModuleTypes.NOPRIZE_PANEL,{notimes:!this.remainingNum});
                    }
                })
            } else {
                Loading.instace.hide();
                this.playBtn.enabled = true;
                showToast("网络异常");
                //请求home接口
                this.updateScene();
            }
        })
    }
    //扣次数
    countTimes() {
        Loading.instace.show()
        sendDoJoin((s, res) => {
            Loading.instace.hide();
            this.playBtn.enabled = true;
            if (s) {
                //更新文案
                this.timesTxt.text = "游戏次数：" + res.data/*.remainingNum*/ + "次";
                this.remainingNum = res.data//.remainingNum;
                //根据剩余次数
                if (this.remainingNum) {
                    PanelCtrl.instance.show(ModuleTypes.HASTIMES_PANEL);
                } else {
                    PanelCtrl.instance.show(ModuleTypes.NOTIMES_PANEL);
                }
            } else {
                showToast("网络异常");
                //请求home接口
                this.updateScene();
            }
        })
    }
}
