import {
    _decorator, EventKeyboard, Input, input, KeyCode, director, Camera, lerp, tween, Label, Node, UITransform
} from "cc";

import { Snake } from "./Snake";
import { Joystick } from "./Components/Joystick";
import { FastBtn } from "./Components/FastBtn";
import { ECard, EPropType, Events } from "./Common/Enums";
import gameStore from "../../store/gameStore";
import { Target } from "./Components/Target";
import { Global } from "./Global";

const { ccclass, property } = _decorator;

@ccclass("Player")
export class Player extends Snake {

    @property(Joystick)
    joystick: Joystick = null;

    @property(FastBtn)
    fastBtn: FastBtn = null;

    @property(Camera)
    camera: Camera = null;


    @property(Label)
    addLengthLabel: Label = null

    @property(Node)
    grayBg: Node = null

    get scale() {
        return this._scale;
    }

    set scale(value: number) {
        this._scale = value;
        this.camera.orthoHeight = lerp(375, 812, (value - 1) / 3);
    }

    get length() {
        return gameStore.gameInfo.length;
    }

    set length(value: number) {
        gameStore.gameInfo.length = value;
    }

    get luckNum() {
        return gameStore.gameInfo.luckNum;
    }

    set luckNum(value: number) {
        gameStore.gameInfo.luckNum = value;
    }

    get energy() {
        return this._energy;
    }

    set energy(value: number) {
        this._energy = value;
        gameStore.gameInfo.energy = value;
    }

    addCard(type: ECard): boolean {
        if (this.isComposed) {
            return false
        }
        let countA = (this.cardMap.get(EPropType.CARD_A) || 0)
        let countB = (this.cardMap.get(EPropType.CARD_B) || 0)
        let countC = (this.cardMap.get(EPropType.CARD_C) || 0)
        if (countA + countB + countC >= 2) {
            this.isComposed = true
        }
        super.addCard(type);

        return true

    }

    async checkCard(cardType: ECard) {
        Target.ins.updateCard(cardType);

        let countA = (this.cardMap.get(EPropType.CARD_A) || 0)
        let countB = (this.cardMap.get(EPropType.CARD_B) || 0)
        let countC = (this.cardMap.get(EPropType.CARD_C) || 0)
        if (countA + countB + countC >= 3) {
            this.cardMap.clear();

            // 3张零食卡A：获得加速卡
            // 3张零食卡B：获得护盾卡
            // 3张零食卡C：获得加长卡
            // 2张零食卡A + 1张任意卡：获得双倍卡
            // 2张零食卡B + 1张任意卡：获得护盾卡
            // 2张零食卡C + 1张任意卡：获得加长卡
            // 零食卡A.B.C各1张：获得复活卡1张
            if (countA >= 3) {
                // 3张零食卡A：获得加速卡
                // sp_agility_card
                await Target.ins.composeCard('获得一张加速卡')
                this.saveStoreCard('sp_agility_card')
                this.isComposed = false
                return
            }
            if (countB >= 3) {
                //sp_shield_card
                // 3张零食卡B：获得护盾卡
                await Target.ins.composeCard('获得一张护盾卡')
                this.saveStoreCard('sp_shield_card')
                this.isComposed = false
                return
            }
            if (countC >= 3) {
                //sp_add_length
                await Target.ins.composeCard('获得一张加长卡')
                this.saveStoreCard('sp_add_length')
                this.isComposed = false
                // 3张零食卡C：获得加长卡
                return
            }
            if (countA >= 2) {
                //sp_experience_card
                await Target.ins.composeCard('获得一张双倍卡')
                this.saveStoreCard('sp_experience_card')
                this.isComposed = false
                // 2张零食卡A + 1张任意卡：获得双倍卡
                return
            }
            if (countB >= 2) {
                //sp_shield_card
                await Target.ins.composeCard('获得一张护盾卡')
                this.saveStoreCard('sp_shield_card')
                this.isComposed = false
                // 2张零食卡B + 1张任意卡：获得护盾卡
                return
            }
            if (countC >= 2) {
                //sp_add_length
                await Target.ins.composeCard('获得一张加长卡')
                this.saveStoreCard('sp_add_length')
                this.isComposed = false
                // 2张零食卡C + 1张任意卡：获得加长卡
                return
            }
            await Target.ins.composeCard('获得一张复活卡')
            this.saveStoreCard('sp_revival_card')
            this.isComposed = false
            // sp_revival_card
            // 零食卡A.B.C各1张：获得复活卡1张

        }
    }

    saveStoreCard(key) {
        if (gameStore.gameInfo.composeSpList[key] == undefined) {
            gameStore.gameInfo.composeSpList[key] = 1
        } else {
            gameStore.gameInfo.composeSpList[key] += 1
        }
    }

    useMagnet() {
        super.useMagnet()
        Target.ins.updateProgress(EPropType.MAGNET, 1, Global.PROP_MAGNET_DUR_TIME)
    }

    useDouble(): void {
        super.useDouble()
        Target.ins.updateProgress(EPropType.DOUBLE_EXP, 1, Global.PROP_DOUBLE_EXP_DUR_TIME)
    }

    useSpeed(): void {
        super.useSpeed()
        Target.ins.updateProgress(EPropType.SPEED, 1, Global.PROP_SPEED_DUR_TIME)
    }

    useGrow() {
        const energy = Math.ceil(Global.PROP_ADD_LENGTH * this.energy)
        this.showGrowText(energy)
        this.fastGrow(energy)
    }

    useDefense(t = Global.PROP_SHIELD_DUR_TIME): void {
        super.useDefense(t);
        Target.ins.updateProgress(EPropType.SHIELD, 1, t)
    }

    breakDefense(showUI = true): void {
        if (this.invincibleTime <= Global.PROP_SHIELD_INVINCIBLE_TIME) return;

        super.breakDefense();
        if (showUI) {
            Target.ins.updateProgress(EPropType.SHIELD, Global.PROP_SHIELD_INVINCIBLE_TIME / Global.PROP_SHIELD_DUR_TIME, Global.PROP_SHIELD_INVINCIBLE_TIME)
        }
    }

    clearDouble(): void {
        super.clearDouble();
        Target.ins.updateProgress(EPropType.DOUBLE_EXP, 0, 0)
    }

    clearInvincible(): void {
        super.clearInvincible();
        Target.ins.updateProgress(EPropType.SHIELD, 0, 0)
    }

    clearSpeed(): void {
        super.clearSpeed();
        Target.ins.updateProgress(EPropType.SPEED, 0, 0)
    }

    clearMagnet(): void {
        super.clearMagnet();
        Target.ins.updateProgress(EPropType.MAGNET, 0, 0)
    }

    onLoad() {
        super.onLoad();
        this.tag = Snake.getTag();
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        this.fastBtn.node.on("fast", this.onFast, this);
    }

    onDestroy() {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
        this.fastBtn?.node?.off("fast", this.onFast, this);
    }

    onFast(isFast: boolean) {
        this.isFast = isFast;
    }

    revive() {
        this.isLife = true;
        this.init({
            tag: this.tag,
            initEnergy: this.energy,
            skinName: this.skinName,
            nickName: this.nickName,
        });

        // this.useDefense(Global.PROP_SHIELD_INVINCIBLE_TIME + 0.1);
        this.invincibleTime = Global.PROP_SHIELD_INVINCIBLE_TIME + 0.1;
        this.breakDefense(false);
    }

    death() {
        super.death();

        // this.length = 0;
        // 发送游戏结束事件
        director.emit(Events.Death);
    }

    keyArr: number[] = [];

    onKeyDown(event: EventKeyboard) {

        const keyArr = [KeyCode.KEY_W, KeyCode.KEY_S, KeyCode.KEY_A, KeyCode.KEY_D,];

        if (keyArr.indexOf(event.keyCode) > -1) {
            this.keyArr.push(event.keyCode);
        }

        if (event.keyCode == KeyCode.SPACE) {
            this.fastBtn.onTouchStart();
        }

        this.setDir();
    }

    onKeyUp(event: EventKeyboard) {
        const index = this.keyArr.indexOf(event.keyCode);
        if (index > -1) {
            this.keyArr.splice(index, 1);
        }

        if (event.keyCode == KeyCode.SPACE) {
            this.fastBtn.onTouchEnd();
        }
        this.setDir();
    }

    setDir() {
        if (!this.keyArr.length) return;
        this.joystick.angle = {
            [KeyCode.KEY_W]: 270,
            [KeyCode.KEY_S]: 90,
            [KeyCode.KEY_A]: 180,
            [KeyCode.KEY_D]: 0,
        }[this.keyArr[this.keyArr.length - 1]];
    }

    onUpdate(dt: number) {
        this.head.angle = (360 - this.joystick.angle) % 360;
        super.onUpdate(dt);
    }



    showGrowText(energy: number) {
        this.addLengthLabel.string = '增加长度' + energy
        this.grayBg.active = true
        this.grayBg.getComponent(UITransform).width = this.addLengthLabel.getComponent(UITransform).width + 50
        tween(this.node).delay(3).call(() => {
            this.grayBg.active = false
        }).start()


    }

}
