import GamePlay from "../../GamePlay";
import { PROPTYPE, SURPRISETASKTYPE } from "../../data/Enum";
import GameLogic from "../../util/GameLogic";
import PoolMgr, { NODEPOOLPREFABTYPE } from "../../mgr/PoolMgr";
import GameConst from "../../data/GameConst";
import AniFinishDestroy from "../../util/common/AniFinishDestroy";
import EliminateScore from "../effect/EliminateScore";
import ScoreEnergy from "../effect/ScoreEnergy";
import { GameProp } from "../../../game/data/GameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CellItem extends cc.Component {

    /**cellItem的ani效果 */
    @property(cc.Animation)
    ani_cellItem: cc.Animation = null;
    /**cellItem的Icon图 */
    @property(cc.Sprite)
    spr_cellItemIcon: cc.Sprite = null;
    /**cellItem的Icon图 */
    @property(cc.Sprite)
    spr_redPackIcon: cc.Sprite = null;

    /**纵列数 */
    public x: number = 0;
    /**横列数 */
    public y: number = 0;
    /**类型 */
    public type: number = 0;
    /**是否移除 */
    public ifRemoved: boolean = false;

    /**是否有红包 */
    public ifRedPacket: boolean = false;

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
    }

    // update (dt) {}

    /**初始化
     * @param x 横坐标 
     * @param y 纵坐标
     */
    init(index_x: number, index_y: number) {

        this.x = index_x;
        this.y = index_y;
        this.ifRemoved = false;

        let endPos = this.getEndPos();
        this.node.x = endPos.x;
        this.node.y = cc.winSize.height * 0.5 + this.node.height + 50;

        this.ani_cellItem.play();

        //LogUtil.log("[CellItem] init", this.x, this.y, endPos);

        this.setType();

        cc.tween(this.node)
            .delay(0.2)
            .to(0.3, { y: endPos.y })

            .call(() => {

            }).start()
    }

    /**获取结束位置 */
    getEndPos(): cc.Vec2 {
        let endX = (this.x * this.node.width + this.node.width * 0.5) - GamePlay.Inst.node_content.width * 0.5;
        let endY = -(this.y * this.node.height + this.node.height * 0.5) + GamePlay.Inst.node_content.height * 0.5;
        return new cc.Vec2(endX, endY);
    }

    /**设置类型 */
    setType(type: number = null) {
        this.node.opacity = 255;
        let lastType = this.type;
        if (type) {
            //LogUtil.log("【cellItem】 重置重置动画动画！！！！！！！！！！！！！！！！！！！！")
            this.ani_cellItem.play("cellItem_reset");
            this.type = type;
        }
        else {

            let type: number = null;
            let level = gData.gameData.getProp(GameProp.levelNum);
            if (level != null && level != undefined) {
                //原先
                //type = GameConst.config_level[PlayerConst.levelNum][this.x][this.y];
                //现在(配置就对照游戏真实的布局)
                type = GameConst.config_level[level][this.y][this.x];
            }

            if (type) {
                this.type = type;
            }
            else {
                this.type = Math.floor(Math.random() * 5) + 1;
            }
            // LogUtil.log("typ111111", type, this.type);
        }
        this.spr_cellItemIcon.node.width = 75;
        this.spr_cellItemIcon.node.height = 75;
        // LogUtil.log("lastType", lastType);
        // LogUtil.log("type", type);
        if (!lastType || lastType != this.type) {
            mk.loader.load(`game/texture/cellItemIcon/${GameConst.iconIndex}/${this.type}`, cc.SpriteFrame).then((spriteFrame) => {
                this.spr_cellItemIcon.spriteFrame = spriteFrame;
            })
        }
    }

    /**重置 */
    reset() {
        //LogUtil.log("【cellItem】 重置重置动画动画！！！！！！！！！！！！！！！！！！！！")
        this.ani_cellItem.play("cellItem_reset");
        let type = Math.floor(Math.random() * 5) + 1;
        this.setType(type);
    }

    /**点击 */
    onClick() {
        //FC:是否可以点击
        if (!GamePlay.Inst.ifCouldClick) {
            return;
        }
        else {
            GamePlay.Inst.ifCouldClick = false;
        }

        //LogUtil.log("Game.Inst.cellItemDic", Game.Inst.cellItemDic, this.x, this.y);

        //重置提示
        GamePlay.Inst.intervalShowGuide();
        GamePlay.Inst.intervalShowInter();

        if (GamePlay.Inst.node_changeCellItemUI.active) {
            GamePlay.Inst.node_changeCellItemUI.active = false;
        }

        //重置
        GamePlay.Inst.cleanedVecArr = [];
        GamePlay.Inst.cleanXIndexArr = [];

        //更改颜色道具
        if (GamePlay.Inst.curPropType == PROPTYPE.Change) {

            GamePlay.Inst.curPropType = PROPTYPE.Null;

            GamePlay.Inst.curSelectCellItem = this;
            GamePlay.Inst.showChangeCellItemUI();
            this.node.opacity = 150;
            return;
        }
        //锤子道具
        else if (GamePlay.Inst.curPropType == PROPTYPE.Hammer) {
            GamePlay.Inst.curPropType = PROPTYPE.Null;
            GamePlay.Inst.curSelectCellItem = this;
            let aroundSameTypeNum = GameLogic.getAroundSameType(this.x, this.y, this.type, false).length;
            if (aroundSameTypeNum <= 0) {
                mk.console.log("周围没有相同的Item ----------------------------------------");
                GamePlay.Inst.cleanedVecArr.push(new cc.Vec2(this.x, this.y));
                //this.ifRemoved = true;
            }

        }

        GamePlay.Inst.curClickCellItem = this;

        //获取清除的CellItem的位置信息列表
        GameLogic.getCleanedVecList(this.x, this.y, this.type);

        //根据vec列表清理cellItem
        GamePlay.Inst.cleanCellItemByVecList();
    }

    /**
     * 向下移动
     * @param index_x x索引值
     * @param index_y 下移至的y索引值
     * @param moveIndex moveIndex
     * @param ifLastMoveCellItem 是否是最后一个移动的CellItem
     */
    moveDown(index_x: number, index_y: number, moveIndex: number, ifLastMoveCellItem: boolean = false) {


        //如果不需要移动就return
        if (this.y == index_y) {
            if (ifLastMoveCellItem) {
                GamePlay.Inst.checkMoveLeftCellItem();
            }
            return;
        }

        // LogUtil.log("[CellItem] index_x index_y", index_x, index_y);
        // LogUtil.log("Game.Inst.cellItemDic", Game.Inst.cellItemDic);

        //移动方块数
        let intervalNum = index_y - this.y;

        //将原来位置置空
        GamePlay.Inst.cellItemDic[this.x][this.y] = null;

        //重新赋值位置
        this.x = index_x;
        this.y = index_y;

        //给现在位置重新赋值
        GamePlay.Inst.cellItemDic[this.x][this.y] = this;

        //let endX = index_x * this.node.width + this.node.width * 0.5 - Game.Inst.node_content.width * 0.5;
        let endY = -(this.y * this.node.height + this.node.height * 0.5) + GamePlay.Inst.node_content.height * 0.5;

        let delayTime = moveIndex * 0.03;
        let moveDwonTime = intervalNum * 0.12;
        //LogUtil.log("delay moveIndex", moveIndex, delayTime);
        cc.tween(this.node)
            .delay(delayTime)
            .call(() => {
                this.ani_cellItem.play("cellItem_down1");
            })
            .to(moveDwonTime, { y: endY })
            .call(() => {
                this.ani_cellItem.play("cellItem_down2");

                //如果是最后一个移动
                if (ifLastMoveCellItem) {

                    mk.console.log("【CellItem】检测是否能消除 移动完毕最后一个");

                    GamePlay.Inst.checkMoveLeftCellItem();
                    //Game.Inst.ifCouldClick = true;
                }
            }).start()
    }

    moveLeft(index_x: number, index_y: number, ifLastCellItem: boolean = false) {

        if (this.x == index_x) {
            if (ifLastCellItem) {

            }
            return;
        }

        //将原来位置置空
        GamePlay.Inst.cellItemDic[this.x][this.y] = null;

        //重新赋值位置
        this.x = index_x;
        this.y = index_y;

        //给现在位置重新赋值
        GamePlay.Inst.cellItemDic[this.x][this.y] = this;

        let endX = index_x * this.node.width + this.node.width * 0.5 - GamePlay.Inst.node_content.width * 0.5;
        //let endY = Game.Inst.node_content.height * 0.5 - index_y * this.node.height + this.node.height * 0.5;

        cc.tween(this.node)
            .to(0.2, { x: endX })
            .call(() => {
                if (ifLastCellItem) {
                    mk.console.log("检测是否能消除！！！！！！！！！！！！！！！！！！！！！！！！！！最后移除");

                    //先注释 避免重复判断 
                    GamePlay.Inst.checkIfEliminate();

                    GamePlay.Inst.ifCouldClick = true;
                }
            }).start()
    }

    /**抖动 */
    shake() {
        this.ani_cellItem.play("cellItem_shake");
    }

    /**normal */
    normal() {
        // this.ifRemoved = false;
        this.node.opacity = 255;
        this.ani_cellItem.play();
    }

    /** */
    showRedPacket() {
        this.spr_redPackIcon.node.active = true;
    }

    /**
     * 回收
     * @param recycleType 回收类型 
     * @param ifLastEliminate 是否最后一个消除
     * @param ifShowEffect 是否显示特效 暴力解决 返回主界面进入 会再消除一遍问题 有时间可以好好研究
     */
    recycle(recycleType: boolean = false, ifLastEliminate: boolean = false, ifShowEffect: boolean = true) {


        //这边不置空的话
        GamePlay.Inst.cellItemDic[this.x][this.y] = null;

        // let index = Game.Inst.cellItemList.indexOf(this);
        // if (index != -1) {
        //     Game.Inst.cellItemList.splice(index, 1);
        // }

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

        if (GamePlay.Inst.curSelectCellItem == this) {
            GamePlay.Inst.curSelectCellItem = null;
            if (GamePlay.Inst.curPropType == PROPTYPE.Hammer) {
                GamePlay.Inst.curPropType = null;
                let node_hammer = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.Hammer);
                node_hammer.setPosition(pos_x, pos_y);
                GamePlay.Inst.node_effectUI.addChild(node_hammer);
            }
        }

        if (ifShowEffect) {
            //爆炸特效
            let node_baozha = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.Baozha);
            node_baozha.x = pos_x;
            node_baozha.y = pos_y;
            GamePlay.Inst.node_effectUI.addChild(node_baozha);
            node_baozha.getComponent(AniFinishDestroy).init();

            //LogUtil.log("10 + Game.Inst.cleanedVecArr.length * 5", 10 + Game.Inst.cleanedVecArr.length * 5);

            //得分
            let score = 10 + GamePlay.Inst.cleanedVecArr.length * 5;
            //得分特效
            let node_score = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.EliminateScore);
            //LogUtil.log("node_score", node_score);
            let x = this.node.x + GamePlay.Inst.node_content.x;
            let y = this.node.y + GamePlay.Inst.node_content.y + 30;
            node_score.getComponent(EliminateScore).init(new cc.Vec2(x, y), score);
            GamePlay.Inst.node_effectUI.addChild(node_score);

            if (recycleType) {
                GamePlay.Inst.curGetScore += score;
                GamePlay.Inst.finalGetScore += score;
                GamePlay.Inst.initScore();
            }
            else {
                let node_scoreEnergy = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.ScoreEnergy);
                node_scoreEnergy.getComponent(ScoreEnergy).init(x, y, score);
                GamePlay.Inst.node_effectUI.addChild(node_scoreEnergy);

                if (this.spr_redPackIcon.node.active && GamePlay.Inst.finalGetScore < GamePlay.Inst.targetScore) {
                    gData.reward.subType = 2;
                    mk.ui.openPanel("module/reward/rewardLuck");
                }
            }
        }
        if (this.spr_redPackIcon.node.active) {
            this.spr_redPackIcon.node.active = false;
        }
        //回收
        PoolMgr.Inst.recyclePoolPrefab(NODEPOOLPREFABTYPE.CellItem, this.node);
    }
}
