import { _decorator, Component, Node, EventTouch, LayoutComponent, Vec2, Rect, Size, Vec3, loader, instantiate } from 'cc';
import { BaseView } from '../../../engines/gui/BaseView';
import { GUIMediator } from '../../../engines/gui/GUIMediator';
import { DataModelEventType } from '../../../engines/models/DataModelEventType';
import GameConfigManager from '../../models/GameConfigManager';
import { GameModel } from '../../models/GameModel';
import { GamePropertys } from '../../models/GamePropertys';
import { WeaponCell } from '../../models/weapons/WeaponCell';
import { PrepareMediator } from './PrepareMediator';
import { WeaponCellScript } from './WeaponCellScript';
const { ccclass, property } = _decorator;


export class WeaponCellListView extends BaseView{

    private currentSelect:WeaponCell;

    constructor(mediator:GUIMediator){
        super(mediator);
    }

    OnShow():void{
        this.mediator.weaponDragIcon.node.active=false;
        this.RefreshWeaponList();
        this.AddEvent();
    }

    onHide():void{
        this.RemoveEvent();
    }

    private AddEvent():void{
        this.mediator.node.on(Node.EventType.TOUCH_START,this.WeaponListTouchStartHandler,this);
        GameModel.single.AddEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged,0);
    }

    private RemoveEvent():void{
        this.mediator.node.off(Node.EventType.TOUCH_START,this.WeaponListTouchStartHandler,this);
        this.mediator.node.off(Node.EventType.TOUCH_MOVE,this.WeaponListTouchMoveHandler,this);
        this.mediator.node.off(Node.EventType.TOUCH_END,this.WeaponListTouchEndHandler,this);
        GameModel.single.RemoveEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged);
    }

    private GameModelPropertyChanged(key:string):void{
        switch (key) {
            case GamePropertys.WeaponCell:
                this.RefreshWeaponList();
                break;
        }
    }

    /**
     * 刷新武器列表
     */
    private RefreshWeaponList():void{
        let weaponCell:WeaponCell;
        let weaponCellView:Node;
        let weaponCellScript:WeaponCellScript;
        if(this.weaponList.node.children.length!=12){
            for (let index = 0; index < 12; index++) {
                weaponCellView=instantiate(this.mediator.WeaponCellPrefab);
                this.weaponList.node.addChild(weaponCellView);
            }   
        }
        let list:WeaponCell[]=GameModel.single.weaponCells;
        for (let index = 0; index < list.length; index++) {
            weaponCell = list[index];
            weaponCellView=this.weaponList.node.children[index];
            weaponCellScript=weaponCellView.getComponent(WeaponCellScript);
            weaponCellScript.UpdateWeaponCell(weaponCell);
        }
    }

    private CheckSelected(weaponCellData:WeaponCell):void{
        this.currentSelect=weaponCellData;
        let weaponCellScript:WeaponCellScript;
        let list:WeaponCell[]=GameModel.single.weaponCells;
        let weaponCell:WeaponCell;
        let weaponCellView:Node;
        for (let index = 0; index < list.length; index++) {
            weaponCell = list[index];
            weaponCellView=this.weaponList.node.children[index];
            weaponCellScript=weaponCellView.getComponent(WeaponCellScript);
            weaponCellScript.ChangeSelected(weaponCellData);
        }
    }

    private CheckMark():void{
        let weaponCellScript:WeaponCellScript;
        let list:WeaponCell[]=GameModel.single.weaponCells;
        let weaponCell:WeaponCell;
        let weaponCellView:Node;
        for (let index = 0; index < list.length; index++) {
            weaponCell = list[index];
            weaponCellView=this.weaponList.node.children[index];
            weaponCellScript=weaponCellView.getComponent(WeaponCellScript);
            if(this.currentSelect==null){
                weaponCellScript.Mark(false);
            }else{
                if(this.currentSelect==weaponCellScript.weaponCell){
                    continue;
                }
                if(this.currentSelect.weaponId==weaponCellScript.weaponCell.weaponId){
                    weaponCellScript.Mark(true);
                }else{
                    weaponCellScript.Mark(false);
                }
            }
        }
    }

    
    private startNode:Node;
    private startPos:Vec2=new Vec2();
    private tempPos:Vec2=new Vec2();
    private isDrag:boolean;
    private WeaponListTouchStartHandler(touch:EventTouch):void{
        touch.getUILocation(this.tempPos);
        this.startPos.x=this.tempPos.x;
        this.startPos.y=this.tempPos.y;
        this.startNode=this.FindTouchNode(this.weaponList.node,this.tempPos);
        if(this.startNode!=null){
            let weaponCellScript:WeaponCellScript=this.startNode.getComponent(WeaponCellScript);
            if(weaponCellScript==null){
                console.error("武器槽未挂载WeaponCellScript脚本");
                return;
            }
            if(weaponCellScript.weaponCell.weaponId<0){
                console.log("没有武器的武器槽不让选中也不让拖拽");
                return;
            }
            this.isDrag=false;
            this.mediator.node.on(Node.EventType.TOUCH_MOVE,this.WeaponListTouchMoveHandler,this);
            this.mediator.node.on(Node.EventType.TOUCH_END,this.WeaponListTouchEndHandler,this);
            this.CheckSelected(weaponCellScript.weaponCell);
        }
    }

    private FindTouchNode(root:Node,touchPos:Vec2):Node{
        for (let index = 0; index < root.children.length; index++) {
            const element = root.children[index];
            if(this.HitNode(element,touchPos)){
                return element;
            }
        }
        return null;
    }

    /**
     * 判断是否击中该节点
     * @param node 
     * @param touchPos 
     */
    private HitNode(node:Node,touchPos:Vec2):boolean{
        let childSize:Size;
        let childPos:Vec2=new Vec2();
        let childRect:Rect=new Rect();
        this.getNodePos(node,childPos);
        childSize=node.getContentSize();
        childRect.x=childPos.x
        childRect.y=childPos.y;
        childRect.width=childSize.x;
        childRect.height=childSize.y;
        if(childRect.contains(touchPos)){
            return true;
        }
        return false;
    }

    private WeaponListTouchMoveHandler(touch:EventTouch):void{
        touch.getUILocation(this.tempPos);
        let dis:number=Vec2.distance(this.startPos,this.tempPos);
        if(dis>5){
            if(this.isDrag==false){
                this.isDrag=true;
                this.CheckMark();
                //拖拽图标
                this.mediator.weaponDragIcon.node.active=true;
                let weaponCellScript:WeaponCellScript=this.startNode.getComponent(WeaponCellScript);
                this.mediator.weaponDragIcon.spriteFrame=weaponCellScript.iconLoader.spriteFrame;
            }
            this.mediator.weaponDragIcon.node.setPosition(this.tempPos.x,this.tempPos.y,0);
            // console.log("拖拽移动到："+target.name);
        }
    }

    private WeaponListTouchEndHandler(touch:EventTouch):void{
        touch.getUILocation(this.tempPos);
        this.mediator.node.off(Node.EventType.TOUCH_MOVE,this.WeaponListTouchMoveHandler,this);
        this.mediator.node.off(Node.EventType.TOUCH_END,this.WeaponListTouchEndHandler,this);
        
        if(this.isDrag){
            this.mediator.weaponDragIcon.node.active=false;
            
            //优先判断武器槽
            let target:Node=this.FindTouchNode(this.weaponList.node,this.tempPos);
            if(target==null){
                //删除
                if(this.HitNode(this.mediator.deleteWeaponNode,this.tempPos)){
                    GameModel.single.RemoveWeapon(this.currentSelect.cellId);
                }else if(this.HitNode(this.mediator.equipWeaponNode,this.tempPos))
                {//装配武器
                    GameModel.single.EquipWeapon(this.currentSelect);
                }
            }else{
                if(this.startNode!=target){
                    if(GameConfigManager.WeaponIsMaxLevel(this.currentSelect.weaponId)){
                        console.log("武器已到达最高等级")
                        return;
                    }
                    let weaponCellScript:WeaponCellScript=target.getComponent(WeaponCellScript);
                    if(weaponCellScript!=null){
                        console.log("合成");
                        GameModel.single.SynthesisWeapon(this.currentSelect.cellId,weaponCellScript.weaponCell.cellId);
                    }
                }
            }
            this.currentSelect=null;
            this.CheckMark();
        }else{
            console.log("点击");
        }
    }

    OnDestory():void{

    }

    private getNodePos(node:Node,out:Vec2):void{
        let nodePos:Vec3=new Vec3();
        let parentPos:Vec3=new Vec3();
        let anchorPoint:Vec2=new Vec2();
        node.getAnchorPoint(anchorPoint);
        let nodeSize:Size=node.getContentSize();
        while(node){
            node.getPosition(parentPos);
            nodePos.x+=parentPos.x;
            nodePos.y+=parentPos.y;
            node=node.parent;
        }
        out.x=nodePos.x-anchorPoint.x*nodeSize.width;
        out.y=nodePos.y-anchorPoint.y*nodeSize.height;
    }

    private get weaponList():LayoutComponent{
        return this.mediator.weaponList;
    }
    private get mediator():PrepareMediator{
        return this.__mediator as PrepareMediator;
    }
}
