import { AudioClip, AudioSourceComponent, ButtonComponent, Color, EventTouch, find, instantiate, LabelComponent, LayoutComponent, loader, Material, ModelComponent, Node, Prefab, Quat, SpriteComponent, SpriteFrame, systemEvent, SystemEventType, Touch, Vec2, view, _decorator } from 'cc';
import { GUIManager } from '../../../engines/gui/GUIManager';
import { GUIMediator } from '../../../engines/gui/GUIMediator';
import { DataModelEventType } from '../../../engines/models/DataModelEventType';
import { NoticeManager } from '../../../engines/notices/NoticeManager';
import { SceneManager } from '../../../engines/scenes/SceneManager';
import { SoundManager } from '../../../engines/sounds/SoundManager';
import GameConfigManager from '../../models/GameConfigManager';
import { GameModel } from '../../models/GameModel';
import { GamePropertys } from '../../models/GamePropertys';
import { WeaponCell } from '../../models/weapons/WeaponCell';
import { UIConst } from '../UIConst';
import { WeaponCellListView } from './WeaponCellListView';
import { WeaponCellScript } from './WeaponCellScript';
const { ccclass, property } = _decorator;

@ccclass('PrepareMediator')
export class PrepareMediator extends GUIMediator {

    @property({
        type:LabelComponent
    })
    glodLabel:LabelComponent=null;

    @property({
        type:LabelComponent
    })
    glodLabel1:LabelComponent=null;

    @property({
        type:LabelComponent
    })
    diamondLabel:LabelComponent=null;

    @property({
        type:LabelComponent
    })
    gunNameLabel:LabelComponent=null;

    @property({
        type:LabelComponent
    })
    levelLabel:LabelComponent=null;

    /**
     * 商城按钮
     */
    @property({
        type:ButtonComponent
    })
    shopButton:ButtonComponent=null;

    /**
     * 快捷购买武器按钮
     */
    @property({
        type:ButtonComponent
    })
    quickBuyButton:ButtonComponent=null;

    /**
     * 快捷购买武器ICON
     */
    @property({
        type:SpriteComponent
    })
    quickBuyWeaponIcon:SpriteComponent=null;

    /**
     * 快捷购买武器价格
     */
    @property({
        type:LabelComponent
    })
    quickBuyWeaponPriceLabel:LabelComponent=null;

    /**
     * 武器拖拽Icon
     */
    @property({
        type:SpriteComponent
    })
    weaponDragIcon:SpriteComponent=null;

    /**
     * 删除按钮节点（用于拖拽判断）
     */
    @property({
        type:Node
    })
    deleteWeaponNode:Node=null;

    /**
     * 装配武器节点（用于拖拽判断）
     */
    @property({
        type:Node
    })
    equipWeaponNode:Node=null;

    /**
     * 装配格子预制体
     */
    @property({
        type:Prefab
    })
    WeaponCellPrefab:Prefab=null;

    /**
     * 武器列表
     */
    @property({
        type:LayoutComponent
    })
    weaponList:LayoutComponent=null;

    private modelView:ModelComponent;

    private modelPrefab:Prefab;
    private prefabInstance:Node;
    private prefabModelComponent:ModelComponent;

    private weaponCellListView:WeaponCellListView;

    onLoad():void{
        this.weaponCellListView=new WeaponCellListView(this);
    }

    OnShow(data?:any):void{
        super.OnShow(data);
        this.RefreshGunModel();
        this.RefreshGlod();
        this.RefreshDiamond();
        this.RefreshLevel();
        this.RefreshQuickBuy();
        this.AddEvents();
        this.weaponCellListView.OnShow();
        
        SoundManager.single.PlayMusic("sounds/main");
    }

    /**
     * 初始化枪的模型
     */
    private RefreshGunModel():void{
        if(this.modelView==null){
            let modelNode:Node=find("ModelView",this.node);
            this.modelView=modelNode.getComponent(ModelComponent);
        }
        this.modelView.node.active=true;

        let weaponConfig:any=GameConfigManager.GetWeaponConfig(GameModel.single.currentWeaponId);
        if(this.prefabInstance){
            this.modelView.mesh=null;
            this.prefabInstance.destroy();
        }
        loader.loadRes(weaponConfig.prefab,Prefab,(err,prefab)=>{
            if(err){
                console.error("加载武器出错");
            }
            this.modelPrefab=prefab;
            this.prefabInstance=instantiate(prefab);
            this.prefabModelComponent=this.prefabInstance.getComponentInChildren(ModelComponent);
            //更换贴图
            let source=this.prefabModelComponent.materials[0];
            let target=this.modelView.materials[0];
            let texture=source.getProperty("mainTexture");
            target.setProperty("mainTexture",texture);
            //更换模型
            this.modelView.mesh=this.prefabModelComponent.mesh;
        });
        if(this.gunNameLabel!=null){
            this.gunNameLabel.string=weaponConfig.name;
        }
    }

    OnHide():void{
        this.RemoveEvents();

        this.modelView.mesh=null;
        this.modelView.setMaterial(null,0);
        if(this.prefabInstance){
            this.prefabInstance.destroy();
        }
        if(this.modelPrefab!=null){
            var deps=loader.getDependsRecursively(this.modelPrefab);
            loader.release(deps);
        }
        
        this.modelView.node.active=false;

        this.weaponCellListView.onHide();
    }

    private AddEvents():void{
        this.equipWeaponNode.on(Node.EventType.TOUCH_START,this.TouchStartHandler,this);
        this.equipWeaponNode.on(Node.EventType.TOUCH_MOVE,this.TouchMoveHandler,this);
        this.equipWeaponNode.on(Node.EventType.TOUCH_END,this.TouchEndHandler,this);

        GameModel.single.AddEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged,0);

        this.quickBuyButton.node.on(ButtonComponent.EventType.CLICK,this.QickBuyButtonClickHandler,this);
        this.shopButton.node.on(ButtonComponent.EventType.CLICK,this.ShopButtonClickHandler,this);
    }

    private RemoveEvents():void{
        this.equipWeaponNode.off(SystemEventType.TOUCH_START,this.TouchStartHandler,this);
        this.equipWeaponNode.off(SystemEventType.TOUCH_MOVE,this.TouchMoveHandler,this);
        this.equipWeaponNode.off(SystemEventType.TOUCH_END,this.TouchEndHandler,this);
        GameModel.single.RemoveEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged);

        this.quickBuyButton.node.on(ButtonComponent.EventType.CLICK,this.QickBuyButtonClickHandler,this);
    }

    private GameModelPropertyChanged(key:string):void{
        switch (key) {
            case GamePropertys.gold:
                this.CallNextFrame(this.RefreshGlod.bind(this));
                this.CallNextFrame(this.RefreshQuickBuy.bind(this));
                break;
            case GamePropertys.diamond:
                this.CallNextFrame(this.RefreshDiamond.bind(this));
                break;
            case GamePropertys.currentWeaponId:
                this.CallNextFrame(this.RefreshGunModel.bind(this));
                break;
            case GamePropertys.currentLevel:
                this.CallNextFrame(this.RefreshLevel.bind(this));
                break;
            case GamePropertys.synthesisMaxWeaponId:
                this.CallNextFrame(this.RefreshQuickBuy.bind(this));
                break;
        }
    }

    private RefreshLevel():void{
        this.levelLabel.string="第"+GameModel.single.currentLevel.toString()+"关";
    }

    private RefreshGlod():void{
        if(this.glodLabel!=null){
            this.glodLabel.string=GameModel.single.gold.toString();
        }
        this.glodLabel1.string=GameModel.single.fullEarnings.toString()+"/秒";
    }

    private RefreshDiamond():void{
        if(this.diamondLabel!=null){
            this.diamondLabel.string=GameModel.single.diamond.toString();
        }
    }

    private weaponIcon:SpriteFrame;
    /**
     * 刷新快速购买按钮
     */
    private RefreshQuickBuy():void{
        this.quickBuyWeaponIcon.spriteFrame=this.weaponIcon;
        //价格
        let price:number=GameModel.single.GetQuickBuyPrice();
        // if(GameModel.single.gold<price){
        //     this.quickBuyWeaponPriceLabel.color.set(Color.RED);
        // }else{
        //     this.quickBuyWeaponPriceLabel.color.set(Color.WHITE);
        // }
        this.quickBuyWeaponPriceLabel.string=GameModel.single.GetQuickBuyPrice().toString();

        let weaponConfig:any=GameConfigManager.GetWeaponConfig(GameModel.single.CurrentQuickBuyWeaponId);
        loader.loadRes(weaponConfig.icon+"/spriteFrame",SpriteFrame,(err:Error,asset:SpriteFrame)=>{
            if(err!=null){
                console.error("加载武器ICON出错！");
            }
            this.quickBuyWeaponIcon.spriteFrame=this.weaponIcon=asset;
        })
    }

    /**
     * 购买武器
     */
    private QickBuyButtonClickHandler():void{
        if(GameModel.single.FindWeaponEmptyCell()==null){
            NoticeManager.ShowPrompt("没有武器槽位了！");
            return;
        }
        //价格
        let price:number=GameModel.single.GetQuickBuyPrice();
        //钱不够
        if(GameModel.single.gold<price){
            NoticeManager.ShowPrompt("金币不足");
            return;
        }
        GameModel.single.BuyWeapon(0,GameModel.single.CurrentQuickBuyWeaponId);
    }

    private ShopButtonClickHandler():void{
        GUIManager.single.Show(UIConst.SHOP_UI);
        this.HideSelf();
    }

    private startRotation:Quat=new Quat();
    private currentRotation:Quat=new Quat();
    private startPoint:Vec2=new Vec2();
    private currentPoint:Vec2=new Vec2();

    private TouchStartHandler(touch:Touch,touchEvent):void{
        let pos:Vec2=touch.getUILocation();
        console.log(pos);
        this.startPoint.set(pos.x,pos.y);
        this.startRotation.x=this.modelView.node.rotation.x;
        this.startRotation.set(this.modelView.node.rotation.x,this.modelView.node.rotation.y,this.modelView.node.rotation.z,this.modelView.node.rotation.w);
    }

    private TouchMoveHandler(touch:EventTouch,touchEvent):void{
        let pos:Vec2=touch.getUILocation();
        this.currentPoint.set(pos.x,pos.y);
        let dis:number=Vec2.distance(this.currentPoint,this.startPoint);
        let value:number=dis/view.getCanvasSize().width;
        if(this.currentPoint.x<this.startPoint.x){
            value=-value;
        }
        Quat.rotateY(this.currentRotation,this.startRotation,value);
        
        Quat.normalize(this.currentRotation,this.currentRotation);
        
        this.modelView.node.setRotation(this.currentRotation);
    }



    private TouchEndHandler(...arg):void{
        console.log("拖拽模型结束");
    }

    StartGame():void{
        this.HideSelf();
        SceneManager.single.Swicth("FightingScene");
    }
}