import { find, Node, tween, UITransform, v3, Vec3, _decorator } from 'cc';
import { BaseLayer } from '../../common/BaseLayer';
import { cocosUtil } from '../../utils/cocosUtil';
import { constants } from '../data/constants';
import { msgac } from '../data/msgac';
import { RoleItem } from '../item/RoleItem';
import { eventManager } from '../manager/eventManager';
import { levelManager } from '../manager/levelManager';
const { ccclass, property } = _decorator;

@ccclass('FightLayer')
export class FightLayer extends BaseLayer {

    stageLayer: Node;

    // 玩家原先的父节点
    playerNodeParent: Node;
    // 玩家原先的世界坐标
    playerWorldPos: Vec3;
    // 玩家立绘原先的缩放
    playerBodyScale: Vec3;

    // 怪物id
    monsterId: number;
    // 怪物节点
    monsterNode: Node;
    // 怪物原先的父节点
    monsterNodeParent: Node;
    // 怪物原先的世界坐标
    monsterWorldPos: Vec3;
    // 怪物立绘原先的缩放
    monsterBodyScale: Vec3;

    onLoad() {
        super.onLoad();

        this.stageLayer = this.getNodeByPath("stage");
    }

    startFight(data: any) {
        let playerRoleItem = levelManager.instance.playerRoleItem;
        let playerNode = playerRoleItem.node;
        let monsterRoleItem = data.monsterRoleItem;
        let monsterNode = monsterRoleItem.node;
        this.monsterNode = monsterNode;

        let atkCount = 0;
        if (playerRoleItem.atk > monsterRoleItem.atk) {
            // 打赢
            let monsterAtk = monsterRoleItem.atk;
            playerRoleItem.playAnimation(constants.animations.attack, true, () => {
                atkCount++;
                if (atkCount >= constants.atkAniTotal) {
                    // playerRoleItem.playAnimation(constants.animations.win, true);
                    // 加战力
                    levelManager.instance.addAtk(monsterAtk);
                    playerRoleItem.playAnimation(constants.animations.standBy, true);
                    this.hideLayer();
                }
            });
            let hitCount = 0;
            monsterRoleItem.scheduleOnce(() => {
                monsterRoleItem.playAnimation(constants.animations.hit, true, () => {
                    hitCount++;
                    if (hitCount >= 1) {
                        let obj: any = {};
                        obj.parentNode = this.monsterNodeParent;
                        obj.worldPos = this.monsterWorldPos;
                        monsterRoleItem.showDeadEffect(null, obj);
                    }
                });
            }, 1.5);
            return;
        }

        // 打输了
        let tmpCb = () => {
            // levelManager.instance.addHitEffect(playerNode);
            playerRoleItem.playAnimation(constants.animations.hit, true);
        };
        playerRoleItem.scheduleOnce(tmpCb, 0.3);
        monsterRoleItem.playAnimation(constants.animations.attack, true, () => {
            playerRoleItem.unschedule(tmpCb);
            atkCount++;
            if (atkCount >= constants.atkAniTotal) {
                monsterRoleItem.playAnimation(constants.animations.standBy, true);
                playerRoleItem.showDeadEffect(() => {
                    this.hideLayer();
                });
            }
        });
    }

    hideLayer() {
        // 玩家位置
        let playerNode = levelManager.instance.playerRoleItem.node;
        playerNode.parent = this.playerNodeParent;
        let p = cocosUtil.convertToNodeSpace(playerNode, this.playerWorldPos);
        playerNode.setPosition(p);
        find("body", playerNode).setScale(this.playerBodyScale);

        // 怪物位置
        let monsterNode = this.monsterNode;
        if (cocosUtil.isNodeValid(monsterNode)) {
            monsterNode.parent = this.monsterNodeParent;
            p = cocosUtil.convertToNodeSpace(monsterNode, this.monsterWorldPos);
            monsterNode.setPosition(p);
            find("body", monsterNode).setScale(this.monsterBodyScale);
        }

        levelManager.instance.canClickGoOn = true;
        this.node.active = false;
        // 镜头跟随
        eventManager.instance.send(msgac.adjustPlayerInCenter);

        // 战斗结束
        let obj: any = {};
        obj.isWin = true;
        obj.monsterId = this.monsterId;
        if (levelManager.instance.playerRoleItem.isDead()) {
            // 玩家战斗失败
            obj.isWin = false;
        }
        eventManager.instance.send(msgac.fightEnd, obj);
    }

    loadFightData(data: any) {
        let playerRoleItem = levelManager.instance.playerRoleItem;
        let playerNode = playerRoleItem.node;
        let monsterRoleItem = data.monsterRoleItem;
        let monsterNode = monsterRoleItem.node;

        this.monsterWorldPos = cocosUtil.convertToWorldSpace(monsterNode);
        let monsterBody = find("body", monsterNode);
        this.monsterBodyScale = monsterBody.getScale();
        this.monsterNodeParent = monsterNode.parent;
        this.monsterId = monsterNode.getComponent(RoleItem).roleTypeP1;

        this.playerWorldPos = cocosUtil.convertToWorldSpace(playerNode);
        let playerBody = find("body", playerNode);
        this.playerBodyScale = playerBody.getScale();
        this.playerNodeParent = playerNode.parent;

        // 玩家左移和怪物右移的距离（相对中间点）
        let dx = 0;
        if (playerRoleItem.atk > monsterRoleItem.atk) {
            // 玩家攻击怪物，弓箭手要拉开点间距
            dx = 75;
        }

        monsterRoleItem.node.parent = this.stageLayer;
        let tf = monsterNode.getComponent(UITransform);
        let pos = monsterNode.getPosition();
        pos.x = dx + tf.width * tf.anchorX;
        pos.y = 0;
        let maxX = 280 - tf.width * (1 - tf.anchorX);
        if (pos.x > maxX) {
            pos.x = maxX;
        }
        monsterNode.setPosition(pos);
        let scale = monsterBody.getScale();
        scale.x = Math.abs(scale.x);
        monsterBody.setScale(scale);

        playerRoleItem.node.parent = this.stageLayer;
        tf = playerNode.getComponent(UITransform);
        pos = playerNode.getPosition();
        pos.x = -(dx + tf.width * (1 - tf.anchorX));
        if (playerRoleItem.atk > monsterRoleItem.atk) {
            // 打赢情况下，再拉开点距离
            pos.x -= 50;
        }
        pos.y = 0;
        playerNode.setPosition(pos);
        scale = playerBody.getScale();
        scale.x = Math.abs(scale.x);
        playerBody.setScale(scale);

        this.stageLayer.setScale(0, 0);
        tween(this.stageLayer).to(0.2, {
            scale: v3(1, 1)
        }).call(() => {
            this.startFight(data);
        }).start();

    }

    onButtonClick(node: Node, name: string) {
        switch (name) {
            default:
                break;
        }
    }

}

