import { _decorator, Component, Node } from 'cc';
import { PlayerTacticalItem } from './PlayerTacticalItem';
import { app } from '../../../App';
import PlayerTacticalData, { PlayerTacticalEvent } from '../../../data/PlayerTacticalData';
import JNodeDrag from '../../../../../extensions/ngame/assets/ngame/util/components/JNodeDrag';
import { EventTouch } from 'cc';
import { UITransform } from 'cc';
import { GUI } from '../../UIConfig';
const { ccclass, property } = _decorator;

/**
 * 玩家阵法
 */
@ccclass('PlayerTacticalView')
export class PlayerTacticalView extends Component {


    //阵法子节点列表
    items:PlayerTacticalItem[] = [];

    onLoad(){

        //阵法
        this.items = this.node.getComponentsInChildren(PlayerTacticalItem);
        this.items.forEach((item,index) => {
            item.onInit(index); //初始化阵法下标
            //添加移动事件
            item.addMoveEvent(this.onMoveItem.bind(this));
            //添加移动结束事件
            item.addMoveEndEvent(this.onMoveEndItem.bind(this));
        });

        this.onUpdateView();

        this.onEvent();

    }

    //移动子节点
    onMoveItem(root:PlayerTacticalItem,e:EventTouch){

        //获取接触的节点(除了自己)
        this.items.forEach(item => {

            //排除自己
            if(item == root) return;
            //排除在移动的节点
            if(!(item.node.position.equals(item.drag.original))) return;

            //检测接触
            if(item.getComponent(UITransform).isHit(e.getUILocation())){
                //如果手指接触了 则 将接触的阵法移动到自己
                item.onExchange(root);
            }

        })

    }

    //子节点移动结束
    async onMoveEndItem(){

        //移动结束则保存阵法
        let pets:number[] = PlayerTacticalData.getIns().getInitTacticalInfo();
        this.items.forEach(item => {
            pets[item.index] = item.petId || 0;
        })
        if(await PlayerTacticalData.getIns().UpdateTactical(pets)){
            app.layer.Open(GUI.Tips,{text:"保存阵法成功"});
        }
        
    }

    protected onDestroy(): void {
        this.offEvent();
    }

    //添加监听
    onEvent(){
        app.event.on(PlayerTacticalEvent.UPDATE_TACTICAL,this.onUpdateView,this);
    }

    //移除监听
    offEvent(){
        app.event.off(PlayerTacticalEvent.UPDATE_TACTICAL,this.onUpdateView,this);
    }

    //更新阵法显示
    onUpdateView(){

        this.items.forEach(item => {
            item.onUpdateView();
        })

    }


}