import CellItem from "./view/uiItem/CellItem";
import { PROPTYPE, CHECKDIR, SURPRISETASKTYPE } from "./data/Enum";
import PoolMgr, { NODEPOOLPREFABTYPE } from "./mgr/PoolMgr";
import GameConst from "./data/GameConst";
import GameLogic from "./util/GameLogic";
import ArtNum from "./util/common/ArtNum";
import BonusTip from "./view/effect/BonusTip";
import PlayerConst from "./data/PlayerConst";
import DataMgr from "./mgr/DataMgr";
import EffectMgr, { TIP_SPRITEITEM_TYPE } from "./mgr/EffectMgr";
import GameMgr, { UI_NAME } from "./mgr/GameMgr";
import { AUDIO_TYPE, EVENT_TYPE, GameProp } from "../game/data/GameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GamePlay extends cc.Component {

    /**单例模式 */
    public static Inst: GamePlay = null;

    /**背景 */
    @property(cc.Node)
    node_bg: cc.Node = null;

    /**标题 */
    @property(cc.Node)
    node_top: cc.Node = null;

    @property(cc.Label)
    label_level: cc.Label = null;
    @property(cc.Node)
    node_redPacketIcon: cc.Node = null;
    @property({ type: cc.Node, displayName: "气泡红包1" })
    btn_gameGetRed1: cc.Node = null;
    @property({ type: cc.Node, displayName: "气泡红包2" })
    btn_gameGetRed2: cc.Node = null;
    @property({ type: cc.Node, displayName: "气泡红包3" })
    btn_gameGetRed3: cc.Node = null;
    @property({ type: cc.Node, displayName: "气泡红包3" })
    btn_gameGetRed4: cc.Node = null;

    /**内容 */
    @property(cc.Node)
    node_content: cc.Node = null;
    /**cell背景块 */
    @property(cc.Node)
    node_cellBg: cc.Node = null;

    /**暂停按钮 */
    @property(cc.Node)
    node_pauseBtn: cc.Node = null;

    /**进度条UI */
    @property(cc.Node)
    node_progressUI: cc.Node = null;
    @property(cc.Sprite)
    spr_progress: cc.Sprite = null;

    /**重置按钮 */
    @property(cc.Node)
    node_resetBtn: cc.Node = null;
    @property(cc.Label)
    label_resetPropNum: cc.Label = null;
    /**锤子按钮 */
    @property(cc.Node)
    node_hammerBtn: cc.Node = null;
    @property(cc.Label)
    label_hammerPropNum: cc.Label = null;
    /**变色按钮 */
    @property(cc.Node)
    node_changeBtn: cc.Node = null;
    @property(cc.Label)
    label_changePropNum: cc.Label = null;

    /**更改CellItemUI */
    @property(cc.Node)
    node_changeCellItemUI: cc.Node = null;

    /**特效UI */
    @property(cc.Node)
    node_effectUI: cc.Node = null;

    /**关卡红包UI */
    @property(cc.Node)
    node_levelRedPacketUI: cc.Node = null;

    /**点击检测遮罩 */
    @property(cc.Node)
    node_touchListenMask: cc.Node = null;

    /**当前进度得分 */
    public curProgressScore: number = 0;
    /**当前得分 */
    public curGetScore: number = 0;
    /**目标分数 */
    public targetScore: number = 100000;
    /**最终得分 */
    public finalGetScore: number = 0;
    /**增加得分速度 */
    public addScoreSpeed: number = 4;

    // /**道具类型 */
    // public curPropType: PROPTYPE = PROPTYPE.Null;

    /**消消的方块数组
     * @param：key index_x
     * @param: value 整个纵列数组
     */
    public cellItemDic: { [key: number]: CellItem[] } = {};

    public cellItemArr: CellItem[] = [];

    /**清理CellItem的Vec数组 */
    public cleanedVecArr: cc.Vec2[] = [];

    /**能够清理的vecArr组 */
    public couldCleanVecArr: cc.Vec2[] = [];

    /**清理纵列的x */
    public cleanXIndexArr: number[] = [];
    /**所有的清理 */
    public allCleanedXArr: number[] = [];
    /**剩余未移除的xIndex */
    public leftXIndexArr: number[] = [];

    /**当前选择的cellItem */
    public curSelectCellItem: CellItem = null;

    /**当前点击得cellItem */
    public curClickCellItem: CellItem = null;

    /**当前选择的道具按钮 */
    public curSelectPropBtn: cc.Node = null;

    /**是否可以点击 */
    public ifCouldClick: boolean = true;

    /**是否已经通关 */
    public ifPass: boolean = false;
    /**是否获取后台回调 */
    public ifGetPass: boolean = false;

    /**当前的道具类型 */
    private _curPropType: PROPTYPE;
    public get curPropType(): PROPTYPE {
        return this._curPropType;
    }
    public set curPropType(v: PROPTYPE) {
        //LogUtil.log("this.curSelectPropBtn", this.curSelectPropBtn);
        let ani = null;
        if (this.curSelectPropBtn) {
            mk.console.log("this.curSelectPropBtn", this.curSelectPropBtn);
            ani = this.curSelectPropBtn.children[1].getComponent(cc.Animation);
        }
        if (v == PROPTYPE.Null) {
            if (ani) {
                ani.play("ani_normalBtn");
            }
            this.setPropBtnNormalTip(this.curSelectPropBtn)
        }
        else {
            if (ani) {
                ani.play("ani_selectBtn");
            }
            this.setPropBtnSelectTip(this.curSelectPropBtn)
        }
        this._curPropType = v;
    }

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        GamePlay.Inst = this;
    }

    public start() {
        PoolMgr.Inst.initPoolPrefab();
        GameConst.loadConfig().then(() => {
            this.adapt();

            // AudioMgr.Inst.playMusic(AUDIO_CLIP_NAME.bg_game);
            mk.audio.playMusic("music_gameBg");

            this.initView();
            this.initEvent();

            this.intervalShowGuide();
            this.intervalShowInter();

            cc.tween(this.btn_gameGetRed1).delay(0.2).to(1, { y: 60 }, { easing: "" }).to(1, { y: 0 }, { easing: "" }).union().repeatForever().start();
            cc.tween(this.btn_gameGetRed2).delay(0.4).to(1, { y: 60 }, { easing: "" }).to(1, { y: 0 }, { easing: "" }).union().repeatForever().start();
            cc.tween(this.btn_gameGetRed3).delay(0.2).to(1, { y: 60 }, { easing: "" }).to(1, { y: 0 }, { easing: "" }).union().repeatForever().start();
            cc.tween(this.btn_gameGetRed4).delay(0.4).to(1, { y: 60 }, { easing: "" }).to(1, { y: 0 }, { easing: "" }).union().repeatForever().start();

        }).catch();
    }

    onEnable() {
        mk.console.log("PROPTYPE[PROPTYPE.Change]", PROPTYPE.Change);
        GameMgr.Inst.sendEvent(UI_NAME.Game, "进入游戏界面");
        // this.initLevel();
    }

    onDisable() {
        //退出游戏归置下道具状态
        this.curPropType = PROPTYPE.Null;
        if (this.curSelectCellItem) {
            this.curSelectCellItem.normal();
        }
        if (this.node_changeCellItemUI.active = true) {
            this.node_changeCellItemUI.active = false;
        }
        //this.clearSurpriseTask();
    }

    adapt() {
        mk.console.log("进行适配！！！！！！！！！！！！！！！！");
        //背景适配
        this.node_bg.setContentSize(new cc.Size(cc.winSize.width, cc.winSize.height));
        // this.node_top.y = (cc.winSize.height - this.node_top.height) * 0.5 + 5;
        const world_pos = gData.gameData.gameStyle.node_top_ui.parent.convertToWorldSpaceAR(gData.gameData.gameStyle.node_top_ui.getPosition());
        const node_pos = this.node_top.parent.convertToNodeSpaceAR(world_pos);
        this.node_top.y = node_pos.y - 40;
    }

    update(dt) {
        if (this.curProgressScore >= this.curGetScore) {
            if (this.curProgressScore == 0) {
                this.spr_progress.fillRange = 0;
            }
            return;
        }
        else {
            if (this.curProgressScore >= this.targetScore) {
                this.curProgressScore = this.curGetScore;
                this.initScore();
            }
            else {

                let nextProgressScore: number = this.curProgressScore + this.addScoreSpeed;

                if (this.curProgressScore < GamePlay.Inst.targetScore && nextProgressScore >= GamePlay.Inst.targetScore) {
                    let node_getTargetScoreTip = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.GetTargetScoreTip);
                    GamePlay.Inst.node_effectUI.addChild(node_getTargetScoreTip);
                }

                this.curProgressScore = nextProgressScore;
                if (this.curProgressScore >= this.curGetScore) {
                    this.curProgressScore = this.curGetScore;
                }
                this.initScore();
            }
        }
    }

    /**初始化视图 */
    initView() {
        this.initLevel();
        this.initTotalScore();
        this.initScore();
        this.initProgress();
        this.initHammerPropNum();
        this.setPropBtnNormalTip(this.node_hammerBtn);
        this.initResetPropNum();
        this.setPropBtnNormalTip(this.node_resetBtn);
        this.initChanegPropNum();
        this.setPropBtnNormalTip(this.node_changeBtn);
        this.initCellBg();
        this.initCell();
    }

    /**初始化事件 */
    initEvent() {
        this.node_pauseBtn.on(cc.Node.EventType.TOUCH_END, this.onClickBtn, this);
        this.node_resetBtn.on(cc.Node.EventType.TOUCH_END, this.onClickBtn, this);
        this.node_hammerBtn.on(cc.Node.EventType.TOUCH_END, this.onClickBtn, this);
        this.node_changeBtn.on(cc.Node.EventType.TOUCH_END, this.onClickBtn, this);

        this.node_redPacketIcon.on(cc.Node.EventType.TOUCH_END, this.onClickRedPacketIcon, this);

        if (!GameConst.isAuth) {
            mk.event.register(EVENT_TYPE.BACK_WxAuth, this.onWxAuthBack, this);
        }
    }

    /**初始化关卡数目 */
    initLevel() {
        mk.console.log("[Game] levelNum", gData.gameData.getProp(GameProp.levelNum));
        let level = gData.gameData.getProp(GameProp.levelNum);
        this.label_level.string = `第${level + 1}关`
    }

    /**初始化总分数 */
    initTotalScore() {
        let level = gData.gameData.getProp(GameProp.levelNum);
        //加入一些随机值，而不是都能获得过关红包
        this.targetScore = 450 + level * (5 + Math.floor(Math.random() * 15));
        // //测试切换
        // this.targetScore = 5000;
        this.addScoreSpeed = Math.floor(this.targetScore / 400) * 2 + 4;
        mk.console.log("this.addScoreSpeed", this.addScoreSpeed);
    }

    /**初始化得分 */
    initScore() {
        this.initProgress();
    }

    /**初始化进度 */
    initProgress() {
        let progress = this.curProgressScore / this.targetScore;
        progress = progress > 1 ? 1 : progress;
        this.spr_progress.fillRange = progress;
        if (progress >= 1) {
            this.pass();
            mk.ui.openPanel("module/reward/rewardMission");
        }
        // LogUtil.log("progressprogressprogressprogressprogressprogress", progress);
    }

    /**初始化道具 */
    initPropNum() {
        this.initHammerPropNum();
        this.initResetPropNum();
        this.initChanegPropNum();
    }

    /**初始化锤子道具数目 */
    initHammerPropNum() {
        let hammerPropNum = gData.gameData.getProp(GameProp.hammerPropNum);
        if (hammerPropNum) {
            this.label_hammerPropNum.string = hammerPropNum.toString();
        }
        else {
            this.label_hammerPropNum.string = "+";
        }
    }

    /**初始化重置道具数目 */
    initResetPropNum() {
        let resetPropNum = gData.gameData.getProp(GameProp.resetPropNum);
        if (resetPropNum) {
            this.label_resetPropNum.string = resetPropNum.toString();
        }
        else {
            this.label_resetPropNum.string = "+";
        }
    }

    /**初始化替换道具数目 */
    initChanegPropNum() {
        let changePropNum = gData.gameData.getProp(GameProp.changePropNum);
        if (changePropNum) {
            this.label_changePropNum.string = changePropNum.toString();
        }
        else {
            this.label_changePropNum.string = "+";
        }
    }

    // update (dt) {}

    /**初始化cellBg */
    initCellBg() {
        for (var i = 0; i < GameConst.col_num; i++) {
            for (var j = 0; j < GameConst.row_num; j++) {
                let prefab_cellBg = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.CellBg);
                // LogUtil.log("prefab_cellBg", prefab_cellBg);
                let node_cellBg = cc.instantiate(prefab_cellBg);
                this.node_cellBg.addChild(node_cellBg);
            }
        }
    }

    /**初始化cell */
    public initCell() {
        this.addCellItemFuc = () => { this.addCellItem(); };
        this.schedule(this.addCellItemFuc, 0.05);
    }

    public addCellItemFuc: Function = null;

    public curXIndex: number = 0;
    public curYIndex: number = 7;

    /**添加CellItem */
    public addCellItem() {
        mk.console.log("addCellItem!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        this.addColCellItem();
        this.curXIndex++;
        if (this.curXIndex >= GameConst.col_num) {
            this.unschedule(this.addCellItemFuc);
            this.getStartRedPacketCellItem();
        }
    }

    /**添加纵列的cellItem */
    public addColCellItem() {
        this.cellItemDic[this.curXIndex] = [];
        for (var i = GameConst.row_num - 1; i >= 0; i--) {
            let prefab_cellItem = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.CellItem);
            let node_prefab = cc.instantiate(prefab_cellItem);
            let cellItem = node_prefab.getComponent(CellItem);
            cellItem.init(this.curXIndex, i);
            this.cellItemDic[this.curXIndex][i] = cellItem;
            this.cellItemArr.push(cellItem);
            this.node_content.addChild(node_prefab);
        }
    }

    /**点击按钮 */
    onClickBtn(event: cc.Event.EventTouch) {

        this.intervalShowGuide();
        this.intervalShowInter();

        //是否已经通关
        if (this.ifPass) {
            EffectMgr.Inst.addTip("通关结算啦,请稍后操作哈")
            return;
        }

        // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.buttonClick);
        mk.audio.playEffect("button");

        switch (event.currentTarget) {
            case this.node_pauseBtn:
                this.onClickPauseBtn();
                break;
            case this.node_hammerBtn:
                this.onClickHammerBtn();
                break;
            case this.node_changeBtn:
                this.onClickChangeBtn();
                break;
            case this.node_resetBtn:
                this.onClickResetBtn();
                break;
        }
    }

    /**点击暂停按钮 */
    onClickPauseBtn() {
        GameMgr.Inst.sendEvent(UI_NAME.Game, "点击暂停按钮");
        mk.ui.openPanel("game/prefab/uiPanel/PauseUI")
    }


    /**点击重置按钮 */
    onClickResetBtn() {
        //this.intervalShowGuide();
        GameMgr.Inst.sendEvent(UI_NAME.Game, "点击重置道具按钮");

        //设置当前选择的道具按钮
        this.setCurSelectPropBtn(this.node_resetBtn);

        this.curPropType = PROPTYPE.Reset;

        let resetPropNum = gData.gameData.getProp(GameProp.resetPropNum);
        if (!resetPropNum || resetPropNum <= 0) {
            mk.ui.openPanel("game/prefab/uiPanel/GetPropUI");
            return;
        }

        // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.refresh);
        mk.audio.playEffect("ef_refresh");

        let keys = Object.keys(this.cellItemDic);
        for (var i = 0; i < keys.length; i++) {
            let key = Number(keys[i]);
            let colCellItemArr = this.cellItemDic[key];
            for (var j = 0; j < colCellItemArr.length; j++) {
                let cellItem = colCellItemArr[j];
                if (cellItem) {
                    cellItem.reset();
                }
            }
        }

        //暂时不扣
        DataMgr.Inst.updatePropNum(2, GamePlay.Inst.curPropType, -1);

        this.curPropType = PROPTYPE.Null;

        //this.recycleAllCellItem();
    }

    //点击锤子按钮
    onClickHammerBtn() {
        GameMgr.Inst.sendEvent(UI_NAME.Game, "点击消除锤道具按钮");
        //this.intervalShowGuide();

        //设置当前选择的道具按钮
        this.setCurSelectPropBtn(this.node_hammerBtn);

        this.curPropType = PROPTYPE.Hammer;

        let hammerPropNum = gData.gameData.getProp(GameProp.hammerPropNum);
        if (!hammerPropNum || hammerPropNum <= 0) {
            mk.ui.openPanel("game/prefab/uiPanel/GetPropUI");
            return;
        }

        DataMgr.Inst.updatePropNum(2, GamePlay.Inst.curPropType, -1);
    }

    //点击更换按钮
    onClickChangeBtn() {
        GameMgr.Inst.sendEvent(UI_NAME.Game, "点击变化方块按钮");
        //this.intervalShowGuide();

        //设置当前选择的道具按钮
        this.setCurSelectPropBtn(this.node_changeBtn);

        this.curPropType = PROPTYPE.Change;
        let changePropNum = gData.gameData.getProp(GameProp.changePropNum);
        if (!changePropNum || changePropNum <= 0) {
            mk.ui.openPanel("game/prefab/uiPanel/GetPropUI");
            return;
        }

        DataMgr.Inst.updatePropNum(2, GamePlay.Inst.curPropType, -1);
    }

    /**更改cellItem类型
     * @param cellItemType
     */
    changeCellItemType(cellItemType: number) {

        let pos_x = this.curSelectCellItem.node.x + GamePlay.Inst.node_content.x;
        let pos_y = this.curSelectCellItem.node.y + GamePlay.Inst.node_content.y;

        let node_change = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.Change);
        node_change.setPosition(pos_x, pos_y);
        GamePlay.Inst.node_effectUI.addChild(node_change);

        this.curSelectCellItem.setType(cellItemType)

        // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.change);
        mk.audio.playEffect("ef_change");


        this.curSelectCellItem = null;
    }

    /**设置当前 */
    setCurSelectPropBtn(propBtn: cc.Node) {
        if (this.curSelectPropBtn) {
            let node_ani = this.curSelectPropBtn.children[1];
            if (node_ani) {
                let ani = node_ani.getComponent(cc.Animation);
                if (ani) {
                    ani.play("ani_normalBtn");
                }
            }
            this.setPropBtnNormalTip(this.curSelectPropBtn);
        }
        this.curSelectPropBtn = propBtn;
    }

    /**设置道具普通提示 */
    setPropBtnNormalTip(propBtn: cc.Node) {

        if (!propBtn) {
            return;
        }

        let node_tip = propBtn.children[2];
        if (node_tip) {
            let label = null;
            switch (propBtn) {
                case this.node_hammerBtn:
                    label = this.label_hammerPropNum;
                    break;
                case this.node_resetBtn:
                    label = this.label_resetPropNum;
                    break;
                case this.node_changeBtn:
                    label = this.label_changePropNum;
                    break;
            }
            let str = label.string;
            let num = Number(str);
            let label_tip = node_tip.getComponent(cc.Label);
            mk.console.log("propBtn.name", propBtn.name);
            mk.console.log("num", num);
            if (num && num >= 1) {
                label_tip.string = "";
            }
            else {
                label_tip.string = "点我领取";
            }
        }
    }

    /**设置道具使用提示 */
    setPropBtnSelectTip(propBtn: cc.Node) {
        if (!propBtn) {
            return;
        }
        let node_tip = propBtn.children[2];
        if (node_tip) {
            let label = node_tip.getComponent(cc.Label)
            label.string = "道具使用中";
        }
    }

    /**显示CellItemUI */
    showChangeCellItemUI() {

        let cruSelectCellItem = this.curSelectCellItem;
        GamePlay.Inst.node_changeCellItemUI.active = true;
        // let min_x = -this.node_content.width * 0.5 + this.node_changeCellItemUI.width * 0.5;
        // let max_x = this.node_content.width * 0.5 + this.node_changeCellItemUI.width * 0.5;
        GamePlay.Inst.node_changeCellItemUI.y = cruSelectCellItem.node.y + cruSelectCellItem.node.height * 0.5 + GamePlay.Inst.node_changeCellItemUI.height * 0.5 + 20;
    }

    //onClick
    onClickRedPacketIcon() {
        if (this.spr_progress.fillRange == 1) {
            EffectMgr.Inst.addTip("已达成目标啦,过关发放哦");
        }
        else {
            EffectMgr.Inst.addTip("达到目标分数,才能领取哦");
        }
    }

    //找到红包的那个水果
    /**
     * 获取红包cellItem
     */
    public getStartRedPacketCellItem() {
        let totalCellItemArr: CellItem[] = this.cellItemArr.concat();
        let largeCellItemVec: cc.Vec2[] = [];
        for (var i = 0; i < totalCellItemArr.length; i++) {
            let cellItem = totalCellItemArr[i];
            if (!!cellItem) {
                GameLogic.getCouldCleanVecList(cellItem.x, cellItem.y, cellItem.type, true);
                // console.log("this.couldCleanVecArr", this.couldCleanVecArr);
                console.log("largeCellItemVec.length", largeCellItemVec.length)
                if (largeCellItemVec.length < this.couldCleanVecArr.length) {
                    largeCellItemVec = this.couldCleanVecArr;

                }
                this.couldCleanVecArr.forEach(element => {
                    let index = GameConst.col_num * element.x + (GameConst.row_num - 1 - element.y);
                    totalCellItemArr[index] = null;
                    this.cellItemDic[element.x][element.y].ifRemoved = false;
                });
                this.couldCleanVecArr = [];
            }
        }
        console.log("FC------------------------------------------------------------");
        let random_index = mk.math.random(0, largeCellItemVec.length - 1);
        let vec = largeCellItemVec[random_index];
        let redPcaketCellItem: CellItem = this.cellItemDic[vec.x][vec.y];
        redPcaketCellItem.showRedPacket();
        return redPcaketCellItem;
    }

    //自定义事件---------------------------------------------------------------------
    /**微信授权返回 */
    onWxAuthBack() {
        if (this.node.active) {
            this.restart(false);
            //
            let node_redPacketUI = mk.ui.getCurOnPanel("RedPacketUI")
            if (node_redPacketUI) {
                mk.ui.closePanel("RedPacketUI");
            }
        }

        this.initLevel();
        this.initTotalScore();
        this.initPropNum();

        mk.event.remove(EVENT_TYPE.BACK_WxAuth, this.onWxAuthBack, this);
    }

    //其他显示或逻辑项-------------------------------------------------------------------
    /**根据vecList清除cellItem */
    public cleanCellItemByVecList() {

        //LogUtil.log("[Game] Game.Inst.cleanCellItemVecArr", Game.Inst.cleanCellItemVecArr);

        //没有可清清除
        if (GamePlay.Inst.cleanedVecArr.length <= 0) {
            //FC:+ 是否可以点击
            this.ifCouldClick = true;
            EffectMgr.Inst.addTip("点击两个或以上消除哦");
            return;
        }

        //区分消除音效
        if (GamePlay.Inst.cleanedVecArr.length >= 4) {
            // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.eliminate_bonus);
            mk.audio.playEffect("ef_eliminate_bonus");
        }
        else {
            //AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.eliminate);
            mk.audio.playEffect("ef_eliminate");
        }

        // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.fly);
        mk.audio.playEffect("ef_fly");

        //同时消除
        for (var i = 0; i < GamePlay.Inst.cleanedVecArr.length; i++) {
            let vec = GamePlay.Inst.cleanedVecArr[i];

            //最后一个判定
            if (i == GamePlay.Inst.cleanedVecArr.length - 1) {
                this.checkBonusNum(GamePlay.Inst.cleanedVecArr.length);
                GamePlay.Inst.cellItemDic[vec.x][vec.y].recycle(false, true);
            }
            else {
                GamePlay.Inst.cellItemDic[vec.x][vec.y].recycle();
            }

            //回收 注释 改成如上
            //Game.Inst.cellItemDic[vec.x][vec.y].recycle();

            //Game.Inst.cellItemDic[vec.x][vec.y] = null;

            if (this.cleanXIndexArr.indexOf(vec.x) == -1) {
                this.cleanXIndexArr.push(vec.x);
            }
        }
        this.cleanXIndexArr.sort();

        //计算下全部移除的
        this.allCleanedXArr = GameLogic.getAllCleanXIndex(this.cleanXIndexArr);

        //FC:移除完,检测下落
        this.scheduleOnce(() => {
            //检测下落
            this.checkMoveDownCellItem();
        }, 0.2)
    }

    /**检测向下移动的cellItem */
    checkMoveDownCellItem() {
        mk.console.log("this.cleanXIndexArr", this.cleanXIndexArr);
        for (var i = 0; i < this.cleanXIndexArr.length; i++) {
            let xIndex = this.cleanXIndexArr[i];
            this.moveYCellItem(xIndex);
        }
    }

    /**移动
     * @param xIndex 移除的纵列
     * @param removedYIndex 移除的横向index
     */
    public moveYCellItem(xIndex: number) {

        // LogUtil.log("moveYCellItem x", xIndex, this.allCleanedXArr);

        /**移动的次序(第几个移动的用来控制延迟移动的时间) */
        let movedIndex: number = 0;
        //移动位置间隔(比如前面两个空位就移动两格)
        let intervalNum: number = 0;

        /**是否是全部清理的x */
        let ifAllCleanedX: boolean = this.allCleanedXArr.indexOf(xIndex) != -1;
        /**是否是最后清理的x(全部清理完才开始左移) */
        let ifLastCleanX: boolean = (xIndex == this.cleanXIndexArr[this.cleanXIndexArr.length - 1]);

        let cellItemDic = GamePlay.Inst.cellItemDic[xIndex];

        //计算y方向移动的最后一位（这样只计算一次不用循环)
        let lastMoveCellItemY: number = null;
        let leftLastCellItemY: number = null;
        if (ifLastCleanX) {
            let lastCellItemArrSort = this.cleanedVecArr.filter((vec) => vec.x == xIndex).sort();
            lastMoveCellItemY = lastCellItemArrSort[0].y;
            // LogUtil.log("lastCellItemY", xIndex, lastMoveCellItemY, lastCellItemArrSort);

            for (var i = 0; i < GameConst.row_num; i++) {
                if (cellItemDic) {
                    let cellItem = cellItemDic[i];
                    if (cellItem) {
                        leftLastCellItemY = cellItem.y;
                        // LogUtil.log("leftLastCellItemY", leftLastCellItemY);
                        break;
                    }
                }
            }
            // let leftCellItemArrSort = this.cl
        }

        //如果最后一行 并且 是被全部清除的x
        if (ifLastCleanX && ifAllCleanedX) {
            // LogUtil.log("【checkMoveLeftCellItem】检测消除 全部消除的一列就是消除xIndex中最后一列");
            this.checkMoveLeftCellItem();
            return;
        }
        //y方向从下至上循环排查

        for (var i = GameConst.row_num - 1; i >= 0; i--) {
            if (cellItemDic) {
                let cellItem = cellItemDic[i];
                //该xIndex纵列没有全部移除
                if (cellItem) {
                    if (ifLastCleanX && i == leftLastCellItemY) {
                        // LogUtil.log("【checkMoveLeftCellItem】检测消除 移除了最后一个");
                        cellItem.moveDown(xIndex, i + intervalNum, movedIndex, true);
                    }
                    else {
                        cellItem.moveDown(xIndex, i + intervalNum, movedIndex);
                    }
                    movedIndex++;
                }
                else {
                    intervalNum += 1;
                }
            }
            else {
                continue;
            }
        }
    }

    /**检测向左移动的cellItem */
    checkMoveLeftCellItem() {

        //计算消除的纵列中,有没有被全部移除
        //let allCleanedXArr = GameUtil.getAllCleanXIndex(this.cleanXIndexArr);
        // LogUtil.log("[Game] checkMoveLeftCellItem  allCleanXArr ---------------------", this.allCleanedXArr);

        //如果没有全部移除得就return
        if (this.allCleanedXArr.length <= 0) {
            //LogUtil.log("【checkMoveLeftCellItem】检测是否能消除 没有全部移除的");
            GamePlay.Inst.ifCouldClick = true;
            GamePlay.Inst.checkIfEliminate();
            return;
        }

        //剩余一列未移除的xIndex
        let leftXIndexArr: number[] = GameLogic.getLeftXIndexArr();
        let leftMaxXIndex: number = leftXIndexArr[leftXIndexArr.length - 1];

        if (leftXIndexArr.length <= 0) {
            //检测是否移除
            this.checkIfEliminate();
        }
        else {
            mk.console.log("leftXIndexArr", leftXIndexArr);
            let intervalNum: number = 0;
            for (var i = 0; i < GameConst.col_num; i++) {
                let cellItemArr = GamePlay.Inst.cellItemDic[i];
                if (this.allCleanedXArr.indexOf(i) == -1) {
                    //剩余存在的cellItem
                    let leftCellItemArr = cellItemArr.filter((cellItem) => cellItem != null);

                    if (intervalNum > 0) {
                        for (var j = 0; j < cellItemArr.length; j++) {
                            let cellItem = cellItemArr[j];
                            if (cellItem) {
                                if (i == leftMaxXIndex && j == (leftCellItemArr[0].y)) {
                                    mk.console.log("i,j,intervalNum", i, j, intervalNum);
                                    cellItem.moveLeft(i - intervalNum, j, true);
                                }
                                else {
                                    cellItem.moveLeft(i - intervalNum, j);
                                }
                            }
                        }
                    }
                    else {
                        //对应 1 2 3 列 中 3全部消除
                        if (i == leftMaxXIndex) {
                            GamePlay.Inst.ifCouldClick = true;
                            GamePlay.Inst.checkIfEliminate();
                        }
                    }
                }
                else {
                    intervalNum += 1;
                }
            }
        }
    }

    public timeout_pass: number = 0;

    /**检测是否能移除 */
    checkIfEliminate() {
        mk.console.log("开始检测是否还能够消除！！！！！！！！！！！！！！！！！！！！！");

        //FC:测试替换
        GameLogic.getCouldCleanVec();
        if (this.couldCleanVecArr.length <= 0 && !this.ifPass) {
            this.ifPass = true;
            EffectMgr.Inst.addSpriteTip(TIP_SPRITEITEM_TYPE.NormalPass);
            let timeOut = setTimeout(() => {
                this.pass();
                clearTimeout(timeOut);
            }, 1500);
        }

        //FC:正式使用
        // let timeOut = setTimeout(() => {
        //     GameUtil.getCouldCleanVec();
        //     if (this.couldCleanVecArr.length <= 0 && !this.ifPass) {
        //         this.pass();
        //     }
        //     clearTimeout(timeOut);
        // }, 1500);
    }

    getCouldCleanCellItem() {
        for (var i = 0; this.cellItemArr.length; i++) {
            let cellItem = this.cellItemArr[i];
            let aroundSameType = GameLogic.getAroundSameType(cellItem.x, cellItem.y, cellItem.type, false);
            if (aroundSameType.length > 0) {
                return;
            }
        }
        //this.nextLevel();
        this.pass();
        //this.recycleAllCellItem();
    }

    /**restart
     * @param 是否扣除体力
     */
    restart(ifMinusEnergy: boolean = false) {
        mk.console.log("restart！！！！！！！！！！！！！！！")
        this.refreshGame();
    }

    /**下一关 */
    nextLevel(ifMinusEnergy: boolean = false) {
        mk.console.log("nextLevel！！！！！！！！！！！！！！！")
        this.refreshGame();
    }

    /**刷新关卡 */
    refreshGame() {
        this.recycleAllCellItem();
        this.ifPass = false;
        this.ifGetPass = false;
        this.ifCouldClick = true;
        this.initLevel();
        this.initTotalScore();
        this.curProgressScore = 0;
        this.curGetScore = 0;
        this.finalGetScore = 0;
        this.initScore();
    }

    /**回收所有的 */
    recycleAllCellItem() {
        for (var i = 0; i < GameConst.col_num; i++) {
            for (var j = 0; j < GameConst.row_num; j++) {
                let cellItem = this.cellItemDic[i][j];
                if (cellItem) {
                    // mk.console.log("回收把>>>>>>>>>>>>>>>>>>>>>>");
                    cellItem.recycle(true, false, false);
                }
            }
        }
        // while (this.cellItemList.length > 0) {
        //     this.cellItemList.splice(0, 1);
        //     this.cellItemList[0].recycle();
        // }
        this.cellItemArr = [];
        this.cellItemDic = {};
        this.curXIndex = 0;
        this.curYIndex = GameConst.row_num - 1;

        this.initCell();
    }

    /**通关 */
    pass() {

        //这边会多次进入
        if (GamePlay.Inst.node.active == false || this.ifPass) {
            return;
        }

        this.ifPass = true;

        GamePlay.Inst.ifGetPass = false;

        let levelNum = gData.gameData.getProp(GameProp.levelNum);
        mk.console.log("[Game]pass passLevelNum", levelNum);
        GamePlay.Inst.ifGetPass = true;
        gData.gameData.setProp(GameProp.levelNum, ++levelNum);
        //游戏结算
        this.gameCount();
        console.log("gData.gameData.getProp(GameProp.levelNum)", gData.gameData.getProp(GameProp.levelNum));
    }

    /**游戏结算 */
    gameCount() {

        let node_getPropUI = mk.ui.getCurOnPanel("GetPropUI");
        if (node_getPropUI) {
            mk.ui.closePanel("GetPropUI");
        }

        let node_rewardLcuk = mk.ui.getCurOnPanel("rewardLuck")
        if (node_rewardLcuk) {
            mk.ui.closePanel("rewardLuck")
        }

        this.gameOver();
    }

    /**游戏结束 */
    gameOver() {
        mk.ui.openPanel("module/reward/rewardMission");
    }

    checkBonusNum(cleanCellItemNum: number) {

        if (cleanCellItemNum >= 4) {
            let node_bonusTip = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.BonusTip);
            let bonusTip = node_bonusTip.getComponent(BonusTip);
            //LogUtil.log("bonusTip",bonusTip);
            if (cleanCellItemNum == 4) {
                bonusTip.init(4);
                mk.audio.playEffect("ef_bonus4");
            }
            else if (cleanCellItemNum == 5) {
                bonusTip.init(5);
                mk.audio.playEffect("ef_bonus5");
            }
            else if (cleanCellItemNum == 6) {
                bonusTip.init(6);
                mk.audio.playEffect("ef_bonus6");
            }
            else if (cleanCellItemNum == 7) {
                bonusTip.init(7);
                mk.audio.playEffect("ef_bonus7");
            }
            else if (cleanCellItemNum == 8) {
                bonusTip.init(8);
                mk.audio.playEffect("ef_bonus8");
            }
            else {
                bonusTip.init(8);
                mk.audio.playEffect("ef_bonus8");
            }

            this.node_effectUI.addChild(node_bonusTip);
        }
    }

    checkAddLevelRedPacket(eliminateNum: number): boolean {
        let chance = (eliminateNum - 3) * 0.2;
        let random = Math.random();
        if (random < chance) {
            return true;
        }
        else {
            return false;
        }
    }

    public interval_ShowGuide: number = null;
    //间隔显示
    intervalShowGuide() {
        this.cancelShowCouldCleanCellItem();
        this.interval_ShowGuide = setInterval(() => {
            this.showCouldCleanCellItem();
        }, 10000);
    }

    /**显示 */
    showCouldCleanCellItem() {
        if (mk.ui.getCurOnPanel("RedPacketUI") || mk.ui.getCurOnPanel("GameOverUI") || !this.couldCleanVecArr || !this.cellItemDic) {
            return;
        }
        if (this.couldCleanVecArr.length <= 0) {
            GameLogic.getCouldCleanVec();
        }
        if (this.couldCleanVecArr.length > 0) {
            for (var i = 0; i < this.couldCleanVecArr.length; i++) {
                let vec = this.couldCleanVecArr[i];
                if (this.cellItemDic[vec.x]) {
                    let cellItem = this.cellItemDic[vec.x][vec.y];
                    if (cellItem) {
                        cellItem.shake();
                    }
                }
                else {

                }
            }
        }
    }

    /**取消显示 */
    cancelShowCouldCleanCellItem() {
        if (this.interval_ShowGuide) {
            clearInterval(this.interval_ShowGuide);
            this.interval_ShowGuide = null;
            if (this.couldCleanVecArr.length > 0) {
                for (var i = 0; i < this.couldCleanVecArr.length; i++) {
                    let vec = this.couldCleanVecArr[i];
                    let cellItem = this.cellItemDic[vec.x][vec.y];
                    if (cellItem) {
                        cellItem.normal();
                    }
                }
            }
            this.couldCleanVecArr = [];
        }
    }

    public interval_ShowInter: number = null;
    //间隔显示
    intervalShowInter() {
        this.cancelShowInter();
        this.interval_ShowGuide = setInterval(() => {
            mk.ad.showInterAd(0);
        }, 15000);
    }

    cancelShowInter() {
        if (this.interval_ShowGuide) {
            clearInterval(this.interval_ShowGuide);
        }
    }
}
