import { Scene } from "../../module/views/Scene";
import Role from "./components/Role";
import { RES } from "../../module/RES";
import Cloud from "./components/Cloud";
import Word from "./components/word";
import { getWebData, WebNetName, sendWebNet, LOG_TYPE } from "../webNet";
import { showPanel, showToast, changeScene } from "../../module/ctrls";
import { GuidePanel } from "../panels/GuidePanel";
import { StartScene } from "./StartScene";
import { SuccessPanel } from "../panels/SuccessPanel";
import { FailPanel } from "../panels/FailPanel";
import { duiba_md5 } from "../../module/tools/security";
import { Tools } from "../Tools";
import { layers } from "../../module/views/layers";
import UI from "../UI";
import { getUrlParams } from "../../module/web/webTools";
import { GDispatcher } from "../Main";

const allWords:any = ['闲', '看', '晴', '云', '自', '卷', '舒', '静', '水', '流', '深', '心', '无', '意', '在', '休']
export class GameScene extends Scene {
    get groupNames() { return ["GameScene"] };
    get skinName() { return "GameScene" };

    bg: FYGE.Sprite;
    left;
    right;
    cdbg: FYGE.Sprite;

    bgCon; //背景移动
    _role; //人物
    wordList = this.getWordList(); // 待随机出现的列表
    collectList: any = []; // 已收集列表
    mapList = [];
    reset;
    time = Tools.configInfo.time;
    startLen = 12

    public static instance: GameScene;
    initUi() {

    }
    async start() {
        super.start();
        GameScene.instance = this
        // this.left = new FYGE.SvgaAni(await RES.getResAsync("left.svga"))
        // this.left = this.addChild(this.left)
        // this.left.position.set(8, 979);
        // this.left.startAniRange(1, 1, 1);
        // this.right = new FYGE.SvgaAni(await RES.getResAsync("right.svga"))
        // this.right = this.addChild(this.right)
        // this.right.position.set(524, 979);
        // this.right.startAniRange(1, 1, 1);
        this.left = UI.Sp(this, '点我按钮.png', 545, 1076)
        this.cdUIRender(this.time)

        // 创建模型, 云层
        this.bgCon = this.addChild(new FYGE.Container());
        this.setChildIndex(this.bgCon, 2)
        this.setChildIndex(this.reset, 3)
        this.initCloud();

        console.log("新手引导")
        showPanel(GuidePanel);
        // this.upDateInfo(); // 用于开始游戏 ----test

        this.reset.addEventListener(FYGE.MouseEvent.CLICK, () => {
            this.btnDelay(this.reset)
            this.onReset()
        }, this)

        // 添加指向的事件
        // this.left.addEventListener(FYGE.MouseEvent.CLICK, () => {
        //     this.btnDelay(this.left)
        //     let item = this._role.currentIndex < 0 ? this.mapList[0][0] : this.mapList[this._role.currentIndex][0]
        //     if (item.y + this.bgCon.y - 200 > 0 && !this._role.isMove && this._role.currentIndex % 2 == 0) {
        //         this.left.startAniRange(1, undefined, 1, () => {})
        //         console.log('this._role.currentIndex', this._role.currentIndex)
        //         this._role.leftMove({
        //             item: item
        //         }, this.collectWordTx.bind(this, item))
        //     }
        // }, this)
        // this.right.addEventListener(FYGE.MouseEvent.CLICK, () => {
        //     this.btnDelay(this.right)
        //     let item = this._role.currentIndex < 0 ? this.mapList[0][0] : this.mapList[this._role.currentIndex][0]
        //     if (item.y + this.bgCon.y - 200 > 0 && !this._role.isMove && this._role.currentIndex % 2 == 1) {
        //         this.right.startAniRange(1, undefined, 1, () => {})
        //         console.log('this._role.currentIndex', this._role.currentIndex)
        //         let item = this._role.currentIndex < 0 ? this.mapList[0][0] : this.mapList[this._role.currentIndex][0]
        //         console.log("播放完成")
        //         this._role.rightMove({
        //             item: item
        //         }, this.collectWordTx.bind(this, item))
        //     }
        // }, this)

        // 添加指向的事件
        this.left.addEventListener(FYGE.MouseEvent.CLICK, () => {
            let item = this._role.currentIndex < 0 ? this.mapList[0][0] : this.mapList[this._role.currentIndex][0]
            if (item.y + this.bgCon.y - 200 > 0) {
                this.left.anchor.set(170/2,174/2)
                FYGE.Tween.get(this.left)
                .to({ 
                    scaleX: 0.7,
                    scaleY: 0.7
                },100)
                .to({ 
                    scaleX: 1,
                    scaleY: 1
                },100)
                if (this._role.currentIndex % 2 == 0) {
                    this._role.leftMove({
                        item: item
                    }, this.collectWordTx.bind(this, item))
                } else {
                    this._role.rightMove({
                        item: item
                    }, this.collectWordTx.bind(this, item))
                }
            }
        }, this)
    }

    getWordList() {
        let dataInfo = getWebData(WebNetName.indexInfo).data.dataInfo;
        let hasWordList:any = [];
        let noWordList:any = [];
        dataInfo.forEach(item => {
            if (item.context) {
                hasWordList = hasWordList.concat(item.context.split(""))
            }
        })
        allWords.forEach(item => {
            if (!hasWordList.includes(item) && !noWordList.includes(item)) {
                noWordList.push(item)
            }
        })
        return noWordList
    }

    upDateInfo() {
        this.time = Tools.configInfo.time;
        this.cdUIRender(this.time)
        this.startGame()
        this.countDown(this.time)
    }

    // 数据重置
    onReset() {
        changeScene(StartScene)
        // this.removeEventListener(FYGE.Event.ENTER_FRAME, this.onFarm, this);
        // this.wordList = this.getWordList();
        // this.collectList = [];
        // this.mapList = [];
        // this.time = Tools.configInfo.time;
        // this.outIndex = 0;
        // this.removeChild(this.bgCon);
        // clearTimeout(this.timer);
        // this.bgCon = this.addChild(new FYGE.Container());
        // this.setChildIndex(this.bgCon, 2)
        // this.initCloud();
        // this.upDateInfo()
    }

    startGame() {
        this.addEventListener(FYGE.Event.ENTER_FRAME, this.onFarm, this);
    }
    
    timer = null;
    countDown(time) {
        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            if (this.time <= 0) {
                clearTimeout(this.timer);
                this.gameOver()
                return
            }
            this.time = this.time - 1;
            this.cdUIRender(this.time)
            this.countDown(this.time)
        }, 1000)
    }

    cdUIRender(num = 60) {
        // 先清除所有节点
        this.cdbg.removeChildren();
        let str = num + 's';
        let arr = str.split("");
        let startPos = (130 - (30 * arr.length)) / 2
        arr.forEach((item, index) => {
            UI.Sp(this.cdbg, `num_${item}.png`, startPos + (index * 30), 38)
        })

    }
    firstCoud;
    initCloud() {
        let stageHeight = this.stage.stageHeight;

        let offset = (1624 - this.stage.viewRect.height) / 2;
        // 渲染人物脚下的一朵云层
        this.firstCoud = UI.Sp(this.bgCon, 'cloud2.png', 190, 1150 - offset)

        // 创建角色
        this.addRole()

        // 开始循环添加
        for (let i = 0; i < this.startLen; i++) {
            this.createCloudItem(stageHeight - (500 + 150 * i), i + 1, i % 2 == 0 ? 'left' : 'right');
        }
    }

    /**
     * 添加云朵
     * @param h 
     * @param direction 方向 left right
     * @param isprop 
     */
    createCloudItem(h, index, direction?: string) {
        // 0 - wordList长度之间的随机数
        let len = this.wordList.length
        let randomIndex;
        if (len > 0) {
            randomIndex = Math.floor(Math.random() * len);
        }
        let wordItem = new Word({
            wordTx: len == 0 ? '' : this.wordList[randomIndex],
            index: index
        })
        // 偏差值
        let deviation = Math.floor(Math.random() * 200) - 100;
        wordItem.fx = (direction === 'left' ? 88 : 440) + deviation + 100;
        wordItem.fy = h + 5
        this.bgCon.addChildAt(wordItem, 0)

        let cloudItem = new Cloud({
            direction
        });
        cloudItem.fx = (direction === 'left' ? 88 : 440) + deviation;
        cloudItem.fy = h
        this.bgCon.addChildAt(cloudItem, 0)
        this.mapList.push([wordItem, cloudItem])
    }

    // 添加角色
    addRole() {
        let offset = (1624 - this.stage.viewRect.height) / 2;
        let role = this._role = new Role();
        role.fx = 380;
        role.fy = 1150 - offset;

        this.bgCon.addChild(role);
    }

    outIndex = 0;
    onFarm() {
        this.moveMap();

        // 判断是否超出屏幕
        let stageHeight = this.stage.stageHeight;
        // console.log('this.mapList[0]', this.mapList[0].y + this.bgCon.y, this.stage.stageHeight)
        if (this.mapList[this.outIndex][0].y + this.bgCon.y - 200 > stageHeight) {
            if (this.firstCoud) {
                this.bgCon.removeChild(this.firstCoud)
            }
            let _index = this.outIndex;
            this.outIndex++
            // console.log("超出屏幕")
            this.bgCon.removeChild(this.mapList[_index][0])
            this.bgCon.removeChild(this.mapList[_index][1])

            let i = this.mapList[this.mapList.length - 1][0].index
            // console.log(this.mapList[this.mapList.length - 1][0].index)
            this.createCloudItem(stageHeight - (500 + 150 * i), i + 1, i % 2 == 0 ? 'left' : 'right')
        }

        // 判断人物是否超出
        if (this._role.y + this.bgCon.y - 305 > stageHeight) {
            let item = this.mapList[this.outIndex + 7][0]
            this._role.onFreeFall({
                x: item.x,
                y: item.y
            }, {
                item: item
            }, this.collectWordTx.bind(this, item))
        }

    }
    moveMap() {
        this.bgCon.y = this.bgCon.y + 1.7
    }
    collectWordTx(item) {
        this.bgCon.removeChild(item)
        if (item.wordTx && !this.collectList.includes(item.wordTx)) {
            this.collectList.push(item.wordTx);
            let _i = this.wordList.indexOf(item.wordTx);
            if (_i > -1) {
                this.wordList.splice(_i, 1)
            }
        }
        if (item.wordTx) {
            if (!this.mapList[item.index][0].wordTx) {
                clearTimeout(this.timer);
                this.gameOver()
            }
        }
    }

    async gameOver() {
        this.removeEventListener(FYGE.Event.ENTER_FRAME, this.onFarm, this);
        let activityId = getUrlParams('activityId')
        let startId = getWebData(WebNetName.startGame).data.startId;
        let timestamp = new Date().getTime();
        let type = 3
        let sign = duiba_md5(String(activityId) + String(timestamp) + String(startId) + String(type) + 'posf3usrjjnd9sd4w21ln3p');
        let dataArr = this.getDataArr();
        const { success, data, desc } = await sendWebNet(WebNetName.submitGame, {
            activityId,
            type,
            startId,
            timestamp,
            sign,
            longitude: Tools.configInfo.longitude,
            latitude: Tools.configInfo.latitude,
            data: dataArr
        })
        if (success) {
            GDispatcher.dispatchEvent("openGameEnd", {
                point: data.point || 0
            });
        } else {
            showToast(desc || "网络开小差了，稍后再试")
        }
    }

    getDataArr() {
        console.log('this.collectList', this.collectList)
        let arr = ["闲看晴云自卷舒", "静水流深", "云卷舒", "心无意", "自在休闲"];
        let tempData = []
        arr.forEach((item, index) => {
            let words = [];
            item.split("").forEach(val => {
                if (this.collectList.includes(val)) {
                    if (words.indexOf(val) == -1) {
                        words.push(val)
                    }
                }
            })
            tempData.push({
                num: index + 1,
                context: words.join(',')
            })
        })
        return tempData
    }
    closeGame() {
        changeScene(StartScene)
    }
    initEvents() {
        super.initEvents();
        GDispatcher.addEventListener("closeGame", this.closeGame, this);
    }
    removeEvents() {
        super.removeEvents();
        clearTimeout(this.timer);
        GDispatcher.removeEventListener("closeGame", this.closeGame, this);
    }
}

