import { G_EVENT } from './../common/G_EVENT';
import { GTool } from './../../module/tools/GTool';
import { changeScene } from './../../module/ctrls/index';
import { hideWaiting } from './../../module/ctrls/waitingCtrl';
import { Tools } from './../Tools';
import { GDispatcher } from './../Main';
import { layers } from './../../module/views/layers';
import { arr } from './../../module/tools/GameConst';
import { Scene } from "../../module/views/Scene";
import { RES } from "../../module/RES";
import { showToast, showWaiting, showPanel } from "../../module/ctrls";
import GameConst from "../../module/tools/GameConst";
import resCanvasList from "../../resCanvasList"
import { ProgressBarS } from "../common/ProgressBarS"
export class StartScene extends Scene {

    bg
    cowBox
    rainBox
    UIBox
    guideBox
    scoreProgressBox
    scoreProgressBarBg
    scoreProgressBar
    countDownBox
    countDownBg
    countDownTxt
    scoreTips
    scoreTxt
    timerTxt

    redPacketTxt // 红包数量
    SPEED = 9;
    ADDSPEED = 0.015
    _emojiState = 0
    _score = 0
    _preTimerNum = 3
    _timerNum = 20
    skipGuideBtn
    rains = []
    hasLuckyBag = false
    pause = false
    playMusic = true
    resConfig = {
        playBg: "41f1aa61-feba-4f8f-ab73-3dd33a9b24ee",
        cow: "3225a506-2e78-49a8-8853-1beea73af645",
        cloud: "5b10683a-12b9-4862-9b2f-0fc60f920c53",
        guideLevel1: "f0c92a46-0e0e-48fb-8639-11f7ab0aac8b",
        guideLevel2: "18bb00b3-9596-489c-a8fe-43daeb6bc9ce",
        guideNextBtn: "2c5f50c8-46e1-463c-8831-0a6572177cec",
        guideEndBtn: "4ae63c2e-6797-4038-8f17-30f61a305207",
        countDownBg: "f0c8dd60-6c2a-49e7-b9cb-fb7786b87a2b",
        scoreProcessBg: "9e864c50-55f6-4d93-b884-075930a74d7f",
        fillProgressBar: "55eb0146-31e9-4996-9b87-0ac5d277a29a",
        redBag: "c5304981-0885-4e00-86f1-070f99a8c5cc",
        goldBag: "c87a85d8-9c8d-4b04-b552-27d5c8d30a02",
        timerBg: "3f5d636d-7e76-43fa-bdaa-dcb6330b06ff",
        luckyBag: "37edf171-b412-46ea-aa1d-92e9e27ce4e9",
        ingot: "b3b64916-14bd-46a1-8610-9fb2acf01c40",
        redPacket: "65176053-5c1c-4323-a145-069686739101",
    }
    private res(name: string) {
        let url = resCanvasList[this.resConfig[name]] ? resCanvasList[this.resConfig[name]].url : ""
        if (!url) {
            return ""
        }
        return RES.getRes(url)
    }

    private guideLevel1
    private guideLevel2
    private guideNextBtn
    private guideEndBtn
    private _guideLevel: number = 0;
    get guideLevel() {
        return this._guideLevel
    }
    set guideLevel(num: number) {
        this._guideLevel = num;
        this.guideBox.visible = false
        this.guideLevel1.visible = false
        this.guideLevel2.visible = false
        this.guideNextBtn.visible = false
        this.guideEndBtn.visible = false
        switch (num + "") {
            case "0":
                this.guideBox.visible = true
                this.guideLevel1.visible = true
                this.guideNextBtn.visible = true
                break
            case "1":
                this.guideBox.visible = true
                this.guideLevel2.visible = true
                this.guideEndBtn.visible = true
                break
        }
    }
    initUi() {
        this.bg = this.addChild(new FYGE.Sprite(this.res("playBg")))
        this.bg.width = 750
        this.bg.height = 1624
        this.bg.y = layers.stageHeight - 1624

        this.cowBox = this.addChild(new FYGE.Container())
        this.cowBox.width = 60
        this.cowBox.height = 231

        this.cowBox.y = layers.stageHeight - 450
        this.cowBox.x = (750 - 60) / 2

        let cow = this.cowBox.addChild(new FYGE.Sprite(this.res('cow')))
        cow.x = -100
        cow.y = -100

        let cloud = this.addChild(new FYGE.Sprite(this.res("cloud")))
        cloud.y = 150

        this.rainBox = this.addChild(new FYGE.Container())

        this.UIBox = this.addChild(new FYGE.Container())

        let redBag = this.UIBox.addChild(new FYGE.Sprite(this.res('redBag')))
        redBag.x = 430
        redBag.y = 30
        let goldBag = this.UIBox.addChild(new FYGE.Sprite(this.res('goldBag')))
        goldBag.x = 620
        goldBag.y = 30

        this.scoreProgressBox = this.UIBox.addChild(new FYGE.Container())
        let progressBarBg = this.scoreProgressBox.addChild(new FYGE.Sprite(this.res("scoreProcessBg")))
        progressBarBg.x = 240
        progressBarBg.y = 130
        let progressBar = this.scoreProgressBox.addChild(new FYGE.Sprite(this.res("fillProgressBar")))
        progressBar.x = 240
        progressBar.y = 130
        this.scoreProgressBar = new ProgressBarS(progressBar)
        this.scoreProgressBar.value = (this.score / 200).toFixed(2)

        let scoreRect = this.scoreProgressBox.addChild(new FYGE.Shape())
        scoreRect.beginFill(0xff0000, 1)
        scoreRect.drawRect(460, 130, 5, 30)
        scoreRect.endFill()

        this.scoreTips = this.UIBox.addChild(new FYGE.TextField())
        this.scoreTips.x = 250
        this.scoreTips.y = 178
        this.scoreTips.size = 28
        this.scoreTips.fillColor = "#ff0000"
        this.scoreTips.text = `还差             点好运值得红福袋`

        this.scoreTxt = new FYGE.TextField()
        this.scoreTxt.x = 307
        this.scoreTxt.y = 168
        this.scoreTxt.text = this.score > 200 ? 0 : (this.score > 100 ? 200 - this.score : 100 - this.score) + ""
        this.scoreTxt.fillColor = "#ff0000"
        this.scoreTxt.textAlign = "center"
        this.scoreTxt.size = 55
        this.scoreTxt.textWidth = 100
        this.UIBox.addChild(this.scoreTxt)


        let timerBg = this.UIBox.addChild(new FYGE.Sprite(this.res('timerBg')))
        timerBg.x = 30
        timerBg.y = 30

        this.redPacketTxt = this.UIBox.addChild(new FYGE.TextField())
        this.redPacketTxt.y = 78
        this.redPacketTxt.x = 40
        this.redPacketTxt.textWidth = 200
        this.redPacketTxt.text = "0"
        this.redPacketTxt.textAlign = FYGE.TEXT_ALIGN.CENTER
        this.redPacketTxt.fillColor = "#FEEABB"
        this.redPacketTxt.size = 40

        let timerTips = this.UIBox.addChild(new FYGE.TextField())
        timerTips.size = 30
        timerTips.fillColor = "#ff0000"
        timerTips.textWidth = 200
        timerTips.textAlign = "center"
        timerTips.x = 15
        timerTips.y = 75
        timerTips.text = "倒计时"

        this.timerTxt = this.UIBox.addChild(new FYGE.TextField())
        this.timerTxt.text = this.timerNum
        this.timerTxt.size = 60
        this.timerTxt.fillColor = "#ff0000"
        this.timerTxt.textWidth = 200
        this.timerTxt.textAlign = "center"
        this.timerTxt.x = 15
        this.timerTxt.y = 115

        this.guideBox = this.addChild(new FYGE.Container())

        this.guideLevel1 = this.guideBox.addChild(new FYGE.Sprite(this.res("guideLevel1")))
        this.guideLevel1.y = (layers.stageHeight - this.guideLevel1.height)

        this.guideNextBtn = this.guideBox.addChild(new FYGE.Sprite(this.res("guideNextBtn")))
        this.guideNextBtn.x = (750 - this.guideNextBtn.width) / 2
        this.guideNextBtn.y = layers.stageHeight - 610

        this.guideLevel2 = this.guideBox.addChild(new FYGE.Sprite(this.res("guideLevel2")))
        this.guideLevel2.y = (layers.stageHeight - this.guideLevel2.height)

        this.guideEndBtn = this.guideBox.addChild(new FYGE.Sprite(this.res("guideEndBtn")))
        this.guideEndBtn.x = (750 - this.guideEndBtn.width) / 2 + 80
        this.guideEndBtn.y = layers.stageHeight - 760

        this.guideLevel = 0

        this.countDownBox = this.addChild(new FYGE.Container());
        this.countDownBox.x = 0
        this.countDownBox.y = (layers.stageHeight - 1624) / 2
        this.countDownBox.visible = false

        this.countDownBg = this.countDownBox.addChild(new FYGE.Sprite(this.res("countDownBg")));
        this.countDownTxt = this.countDownBox.addChild(new FYGE.TextField())
        this.countDownTxt.text = this.preTimerNum
        this.countDownTxt.size = 100
        this.countDownTxt.fillColor = "#ffffff"
        this.countDownTxt.textWidth = 200
        this.countDownTxt.textAlign = "center"
        this.countDownTxt.x = 275
        this.countDownTxt.y = 755


        this.pause = true

        if (GTool.readCache("isNQCTGuide")) {
            this.guideLevel = 2
            this.gamePreCountDown()
            // this.pause = false
            // this.gameStart()
        }


    }

    set preTimerNum(val) {
        if (this._preTimerNum == val) {
            return
        }
        this._preTimerNum = val
        if (this.countDownTxt) {
            this.countDownTxt.text = this._preTimerNum + ""
        }
    }

    get preTimerNum() {
        return this._preTimerNum
    }

    set timerNum(val) {
        if (this._timerNum == val) {
            return
        }
        this._timerNum = val
        if (this.timerTxt) {
            this.timerTxt.text = this._timerNum + ""
        }
    }

    get timerNum() {
        return this._timerNum
    }




    set score(val) {
        if (this._score == val) {
            return
        }
        this._score = val
        if (this.scoreTxt) {
            this.scoreTxt.text = this.score >= 200 ? 0 + "" : (this.score >= 100 ? 200 - this.score : 100 - this.score) + ""
        }
        if (this.scoreTips) {
            this.scoreTips.text = this.score >= 100 ? `还差             点好运值得金福袋` : `还差             点好运值得红福袋`
        }
        if (this.scoreProgressBar) {
            this.scoreProgressBar.value = this.score > 200 ? 1 : (this.score / 200).toFixed(2)
        }
    }

    get score() {
        return this._score
    }


    initEvents() {
        this.addEventListener(FYGE.MouseEvent.MOUSE_DOWN, this.onDown_bottle, this)
        this.addEventListener(FYGE.MouseEvent.MOUSE_MOVE, this.onMove_bottle, this)
        this.addEventListener(FYGE.MouseEvent.MOUSE_UP, this.onUp_bottle, this)
        this.addEventListener(FYGE.MouseEvent.MOUSE_OUT, this.onUp_bottle, this)
        this.addEventListener(FYGE.MouseEvent.MOUSE_OVER, this.onUp_bottle, this)
        this.guideNextBtn.addEventListener(FYGE.MouseEvent.CLICK, this.nextGuide, this)
        this.guideEndBtn.addEventListener(FYGE.MouseEvent.CLICK, this.endGuide, this)
        this.addEventListener(FYGE.Event.ENTER_FRAME, this.raining, this)

        //添加onSHow事件
        GDispatcher.addEventListener(G_EVENT.ON_SHOW, this.onShow, this)

        GDispatcher.addEventListener(G_EVENT.ON_HIDE, this.onHide, this)
    }



    onShow() {

    }
    onHide() {

    }

    destroy() {
        this.onHide()
        GDispatcher.removeEventListener(G_EVENT.ON_SHOW, this.onShow, this)
        GDispatcher.removeEventListener(G_EVENT.ON_HIDE, this.onHide, this)
        super.destroy()
    }

    gamePreTimer
    gamePreCountDown() {
        this.pause = true
        this.countDownBox.visible = true
        this.preTimerNum = 3
        clearInterval(this.gamePreTimer)
        this.gamePreTimer = setInterval(() => {
            if (this.preTimerNum <= 0) {
                clearInterval(this.gamePreTimer)
                this.countDownBox.visible = false
                this.pause = false
                this.gameStart()
            } else {
                this.preTimerNum -= 1
            }
        }, 1000)

    }

    gameTimer
    gameStart() {
        this.hasLuckyBag = false
        clearInterval(this.gameTimer)
        this.gameTimer = setInterval(() => {
            if (this.pause) {
                return
            }

            this.timerNum -= 1
            if (this.timerNum <= 0) {
                this.timerNum = 0
                this.gameOver()
            }
            if (this.timerNum < 10) {
                this.ADDSPEED = 0.045
                this.SPEED = 19
                // this.rainConfig = ['boom', 'boom', 'boom', 'boom', 'drop', 'drop', 'bigDrop']
            } else if (this.timerNum < 20) {
                this.ADDSPEED = 0.035
                this.SPEED = 17
                // this.rainConfig = ['boom', 'boom', 'drop', 'drop', 'bigDrop']
            } else if (this.timerNum < 30) {
                this.ADDSPEED = 0.025
                this.SPEED = 15
            }
        }, 1000)
        this.pause = false
    }

    isGameOver = false
    gameOver() {
        console.log("游戏结束")
        if (this.isGameOver) {
            return
        }
        this.pause = true
        this.isGameOver = true

        //发接口结束游戏
        GDispatcher.dispatchEvent("GAME_OVER", { score: this.score })
    }

    startX
    onDown_bottle(e) {
        if (this.pause) {
            return
        }
        this.startX = e.stageX
    }

    onMove_bottle(e) {
        if (this.pause) {
            return
        }
        if (!this.startX) {
            return
        }
        if (e.stageY > layers.stageHeight - 400) {

            let offsetX = e.stageX - this.startX
            this.cowBox.x += offsetX
            if (this.cowBox.x < 0) {
                this.cowBox.x = 0
            }
            if (this.cowBox.x > 750 - 103) {
                this.cowBox.x = 750 - 103
            }
            this.startX = e.stageX
        }
    }

    onUp_bottle(e) {
        if (this.pause) {
            return
        }
        this.startX = null
    }

    nextGuide() {
        this.guideLevel = 1
    }

    endGuide() {
        GTool.writeCache("isNQCTGuide", "true")
        this.guideLevel = 2
        this.pause = false
        this.gamePreCountDown()
    }

    // 发生碰撞
    checkGetRain() {
        for (let i = this.rains.length - 1; i >= 0; i--) {
            let rain = this.rains[i]
            let checkBox = { x: this.cowBox.x, y: this.cowBox.y, width: 130, height: this.cowBox.height }
            if (GameConst.collisionDetection(rain, checkBox)) {
                let addScoreTxt = new FYGE.TextField()
                addScoreTxt.size = 36
                addScoreTxt.fillColor = "#ff0000"
                // addScoreTxt.alpha = 0
                addScoreTxt.x = this.cowBox.x
                addScoreTxt.y = this.cowBox.y
                switch (rain.spType) {
                    case "luckyBag":
                        this.hasLuckyBag = true
                        this.rainLuckyBag = false
                        this.score += 20
                        addScoreTxt.text = "+20"
                        this.addChild(addScoreTxt)
                        FYGE.Tween.get(addScoreTxt)
                            .to({ alpha: 1, y: this.cowBox.y - 100 }, 170)
                            .to({ y: this.cowBox.y - 200 }, 170)
                            .call(() => {
                                this.removeChild(addScoreTxt)
                            })
                        break
                    case "ingot":
                        this.score += 10
                        addScoreTxt.text = "+10"
                        this.addChild(addScoreTxt)
                        FYGE.Tween.get(addScoreTxt)
                            .to({ alpha: 1, y: this.cowBox.y - 100 }, 170)
                            .to({ y: this.cowBox.y - 200 }, 170)
                            .call(() => {
                                this.removeChild(addScoreTxt)
                            })
                        break
                    case "redPacket":
                        this.score += 5
                        addScoreTxt.text = "+5"
                        this.redPacketTxt.text = "+5"
                        this.addChild(addScoreTxt)
                        FYGE.Tween.get(addScoreTxt)
                            .to({ alpha: 1, y: this.cowBox.y - 100 }, 170)
                            .to({ y: this.cowBox.y - 200 }, 170)
                            .call(() => {
                                this.removeChild(addScoreTxt)
                            })
                        break
                }
                this.rainBox.removeChild(rain)
                arr.removeEle(rain, this.rains)

            }
        }
    }

    count = 0
    rainLuckyBag = false
    // rainConfig = ['redPacket', 'redPacket', 'redPacket', 'redPacket', 'redPacket', 'luckyBag', 'ingot', 'ingot']
    rainConfig = ['redPacket', 'redPacket', 'luckyBag', 'ingot', 'ingot']
    lastTime
    raining() {
        if (this.pause) {
            return
        }
        var now = Date.now();
        var delta = this.lastTime ? now - this.lastTime : 16.7;
        this.lastTime = now;
        if (delta > 1000) delta = 16.7;
        var scale = delta / 16.7;

        this.checkGetRain()

        this.count++
        let rainNum = layers.stageHeight >= 1334 ? 30 : 20
        if (this.rains.length < rainNum && this.count % 50 == 0) {
            let rain = this.rainBox.addChild(new FYGE.Sprite(this.res("redPacket")))

            rain.y = -200
            rain.x = Math.max(10 * Math.random(), 680 * Math.random())
            rain['speed'] = Math.max(this.SPEED * Math.random(), 6)
            let type = arr.getRandomOne(this.rainConfig)

            if (type == "luckyBag" && (this.hasLuckyBag || this.rainLuckyBag)) {
                type = "redPacket"
            }
            if (type == "luckyBag") {
                this.rainLuckyBag = true
            }
            switch (type) {
                case "luckyBag":
                    rain.texture = this.res("luckyBag")
                    rain.width = 123
                    rain.height = 132
                    rain['spType'] = "luckyBag"
                    break
                case "ingot":
                    rain.texture = this.res("ingot")
                    rain.width = 135
                    rain.height = 97
                    rain['spType'] = "ingot"
                    break
                case "redPacket":
                    rain.texture = this.res("redPacket")
                    rain.width = 95
                    rain.height = 131
                    rain['spType'] = "redPacket"
                    break
            }

            this.rains.push(rain)
        }

        if (this.rains.length > 0) {
            for (let i = this.rains.length - 1; i >= 0; i--) {
                this.rains[i].y += this.rains[i].speed * scale
                this.rains[i].speed += this.ADDSPEED
                this.rains[i].alpha = (this.rains[i].y < layers.stageHeight - 300 ? 1 : (layers.stageHeight - this.rains[i].y - 100) / 300)
                if (this.rains[i].y > 1800) {
                    if (this.rains[i].type == "luckyBag") {
                        this.rainLuckyBag = false
                    }
                    this.rainBox.removeChild(this.rains[i])
                    arr.removeEle(this.rains[i], this.rains)
                }
            }
        }

    }


    removeEvents() {
        this.removeEventListener(FYGE.MouseEvent.MOUSE_DOWN, this.onDown_bottle, this)
        this.removeEventListener(FYGE.MouseEvent.MOUSE_MOVE, this.onMove_bottle, this)
        this.removeEventListener(FYGE.MouseEvent.MOUSE_UP, this.onUp_bottle, this)
        this.removeEventListener(FYGE.MouseEvent.MOUSE_OUT, this.onUp_bottle, this)
        this.removeEventListener(FYGE.MouseEvent.MOUSE_OVER, this.onUp_bottle, this)
        this.guideNextBtn.removeEventListener(FYGE.MouseEvent.CLICK, this.nextGuide, this)
        this.guideEndBtn.removeEventListener(FYGE.MouseEvent.CLICK, this.endGuide, this)
        this.removeEventListener(FYGE.Event.ENTER_FRAME, this.raining, this)
    }
}