import { ButtonComponent, EventTouch, find, instantiate, LabelComponent, LayoutComponent, loader, ModelComponent, Node, Prefab, Quat, SpriteComponent, SpriteFrame, SystemEventType, Touch, Vec2, view, _decorator } from 'cc';
import BufferManager from '../../../engines/buffers/BufferManager';
import IBuffer from '../../../engines/buffers/IBuffer';
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 { SoundManager } from '../../../engines/sounds/SoundManager';
import StringUtils from '../../../engines/utils/StringUtils';
import { PlatformManager } from '../../../Platform/PlatformManager';
import { branchIdType } from '../../../Platform/WeChat/branchIdType';
import { WeChatPlatform } from '../../../Platform/WeChat/WeChatPlatform';
import GameConfigManager from '../../models/GameConfigManager';
import { GameModel } from '../../models/GameModel';
import { GamePropertys } from '../../models/GamePropertys';
import { UIConst } from '../UIConst';
import { WeaponCellListView } from './WeaponCellListView';
const { ccclass, property } = _decorator;

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

    @property({
        type: Node
    })
    HandTip: Node = null;

    @property({
        type: Node
    })
    bufferNode: Node = null;

    @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: LabelComponent
    })
    weaponInfoLabel: LabelComponent = null;

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


    /**
     * 自动合成文本
     */
    @property({
        type: LabelComponent
    })
    autoSynthesisLabel: LabelComponent = 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;

    private isNew:boolean=true;
    private get isNewPlayer():boolean{
        return this.isNew&&GameModel.single.isNewPlayer;
    }

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

    OnShow(data?: any): void {
        //清空试用栅栏
        GameModel.single.trialFenceId=-1;
        super.OnShow(data);
        this.RefreshGunModel();
        this.RefreshGlod();
        this.RefreshDiamond();
        this.RefreshLevel();
        this.RefreshQuickBuy();
        this.AddEvents();
        this.weaponCellListView.OnShow();

        SoundManager.single.PlayMusic("sounds/main");
        PlatformManager.showBanner();
        if(this.isNewPlayer){
            this.HandTip.active=true;
        }else{
            this.HandTip.active=false;
        }
    }

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

        if (this.modelPrefab) {
            this.modelView.mesh = null;
            let target=this.modelView.materials[0];
            target.setProperty("mainTexture", null);

            this.prefabInstance.destroy();
            this.prefabInstance=null;
            let deps:string[]=loader.getDependsRecursively(this.modelPrefab);
            loader.release(deps);
            this.modelPrefab=null;
        }

        //武器为空
        if(GameModel.single.currentWeaponId<0){
            this.modelView.node.active = false;
            this.gunNameLabel.string="";
            this.weaponInfoLabel.string="";
            return;
        }else{
            this.modelView.node.active = true;
            let weaponConfig: any = GameConfigManager.GetWeaponConfig(GameModel.single.currentWeaponId);
            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;
            }
            //描述
            this.weaponInfoLabel.string=weaponConfig.desc;
        }
        
    }

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

        this.modelView.mesh = null;
        let target=this.modelView.materials[0];
        target.setProperty("mainTexture", null);
        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;
            case GamePropertys.WeaponCell:
                this.HandTip.active=false;
                this.isNew=false;
            break;
        }
    }

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

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

    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 = StringUtils.numberUtilsEn(GameModel.single.GetQuickBuyPrice());

        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();
    }


    /**
     * 自动合成按钮点击
     */
    AutoSynthesisButtonClickHandler():void{
        GUIManager.single.Show(UIConst.AUTO_SYNTHETIC_UI);
        this.HideSelf();
    }

    /**
     * 加速Buffer;
     */
    AccelerateButtonClickHandler():void{
        GUIManager.single.Show(UIConst.ACCELERATE_UI);
        this.HideSelf();
    }

    /**
     * 兑换界面
     */
    ExchangeButtonClickHandler():void{
        GUIManager.single.Show(UIConst.EXCHANGE_UI);
        this.HideSelf();
    }

     /**
     * 签到
     */
    SignButtonClickHandler():void{
        GUIManager.single.Show(UIConst.SIGN_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 {
        if(GameModel.single.currentWeaponCell==null||GameModel.single.currentWeaponId<0){
            NoticeManager.ShowPrompt("请装配武器后再试！");
            return;
        }
        GUIManager.single.Show(UIConst.FREE_FENCE_UI);
        // if(GameConfigManager.GetNextFenceID(GameModel.single.currentFenceId)>0){
            // GUIManager.single.Show(UIConst.FREE_FENCE_UI);
            // return;
        // }
        // //隐藏
        // this.HideSelf();
        // PlatformManager.hideBanner();
        // SceneManager.single.Swicth("FightingScene");
        // let weChat = PlatformManager.impl as WeChatPlatform
        // if(weChat instanceof WeChatPlatform){
        //     weChat.startBranchAnalytics(String(GameModel.single.currentLevel));
        // }
    }

    /**
     * 免费金币
     */
    getAdGold(): void {
        PlatformManager.showRewardedVideo(()=>{
            GameModel.single.gold += GameModel.single.fullEarnings * 600;
            NoticeManager.ShowPrompt(`获得${StringUtils.numberUtilsEn(GameModel.single.fullEarnings * 600)}金币`);
            let weChat = PlatformManager.impl as WeChatPlatform;
            if(weChat instanceof WeChatPlatform){
                weChat.branchAnalytics(branchIdType.FreeGold)
            }
        },()=>{
            NoticeManager.ShowPrompt(`未看完广告，无奖励`);
        })
    }

    /**
     * 心跳
     * @param dt 
     */
    update(dt:number):void{
        super.update(dt);
        //自动合成Buffer剩余时间
        let buffers:IBuffer[]=BufferManager.GetBufferGroup("AutoSynthesis");
        if(buffers!=null&&buffers.length>0){
            let buffer:IBuffer=buffers[0];
            let endTime:number=buffer.GetTimeRemaining();
            this.autoSynthesisLabel.string=StringUtils.TimeFormatting(endTime,":",":",":",":",":","");
        }else{
            this.autoSynthesisLabel.string="自动合成";
        }
        //加速Buffer
        buffers=BufferManager.GetBufferGroup("Accelerate");
        if(buffers!=null&&buffers.length>0){
            this.bufferNode.active=true;
        }else{
            this.bufferNode.active=false;
        }
    }
}