import { _decorator, Component, Node, Prefab, LayoutComponent, instantiate, ScrollViewComponent, LabelComponent, ToggleComponent, JsonAsset } from 'cc';
import { GUIManager } from '../../../engines/gui/GUIManager';
import { GUIMediator } from '../../../engines/gui/GUIMediator';
import { DataModelEventType } from '../../../engines/models/DataModelEventType';
import StringUtils from '../../../engines/utils/StringUtils';
import GameConfigManager from '../../models/GameConfigManager';
import { GameModel } from '../../models/GameModel';
import { GamePropertys } from '../../models/GamePropertys';
import { UIConst } from '../UIConst';
import { FenceItemRenderScript } from './FenceItemRenderScript';
import { ShopItemRenderScript } from './ShopItemRenderScript';
const { ccclass, property } = _decorator;

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

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

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

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

    
    @property({
        type:Prefab
    })
    WeaponListItemRenderPrefab:Prefab=null;

    @property({
        type:LayoutComponent
    })
    WeaponListContext:LayoutComponent=null;

    @property({
        type:ScrollViewComponent
    })
    WeaponList:ScrollViewComponent=null;


    
    @property({
        type:Prefab
    })
    FenceListItemRenderPrefab:Prefab=null;

    @property({
        type:LayoutComponent
    })
    FenceListContext:LayoutComponent=null;

    @property({
        type:ScrollViewComponent
    })
    FenceList:ScrollViewComponent=null;

    /**
     * 需要包含在内的武器
     */
    private include:number[]=[];


    private showType:number=0;

    OnShow(data?:any):void{
        super.OnShow(data);
        this.SwitchToggle(null,this.showType,true);
        this.RefreshGlod();
        this.RefreshDiamond();
        this.AddEvent();
    }

    OnHide():void{
        this.RemoveEvent();
    }
    
    /**
     * 返回按钮点击
     */
    public BackButtonClick():void{
        GUIManager.single.Show(UIConst.PREPARE_UI);
        this.HideSelf();
    }

    private AddEvent():void{
        GameModel.single.AddEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged,0);
    }

    private RemoveEvent():void{
        GameModel.single.RemoveEvent(DataModelEventType.PROPERTY_CHANGED,this,this.GameModelPropertyChanged);
    }
    private GameModelPropertyChanged(key:string) {
        if(key==GamePropertys.WeaponCell){
            this.RefreshWeaponList(false);
        }else if(key==GamePropertys.gold){
            this.CallNextFrame(this.RefreshGlod.bind(this));
        }else if(key==GamePropertys.diamond){
            this.CallNextFrame(this.RefreshDiamond.bind(this));
        }else if(key==GamePropertys.currentFenceId){
            this.CallNextFrame(this.RefreshFenceList.bind(this));
        }
    }
    
    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 RefreshWeaponList(srollToZ:boolean):void{
        //根据当前枪生成包含列表
        this.buildInclude();

        let itemView:Node;
        let dataList:any[]=this.GetListData();
        if(dataList.length!=this.WeaponListContext.node.children.length){
            if(dataList.length<this.WeaponListContext.node.children.length){
                //删除多余的
                while(dataList.length<this.WeaponListContext.node.children.length){
                    this.WeaponListContext.node.removeChild(this.WeaponListContext.node.children[0]);
                }
            }else{
                //添加缺少的
                while(dataList.length>this.WeaponListContext.node.children.length){
                    itemView=instantiate(this.WeaponListItemRenderPrefab);
                    this.WeaponListContext.node.addChild(itemView);
                }
            }
        }
        let itemScript:ShopItemRenderScript;
        let count:number=dataList.length;
        for (let index = 0; index < count; index++) {
            itemView=this.WeaponListContext.node.children[index];
            itemScript=itemView.getComponent(ShopItemRenderScript);
            if(itemScript==null){
                throw new Error("商城列表项未挂载ShopItemRenderScript脚本!");
            }
            itemScript.UpdateItemRender(dataList[index]);
        }
        if(srollToZ){
            this.WeaponList.scrollToTop(0.1);
        }
    }
    private buildInclude():void{
        this.include.length=0;
        let currentWeaponConfig:any=GameConfigManager.GetWeaponConfig(GameModel.single.synthesisMaxWeaponId);
        let weaponConfig:any;
        //低级6个
        for (let index = 1; index <=6; index++) {
            weaponConfig=GameConfigManager.GetWeaponConfigByLevel(currentWeaponConfig.level-index);
            if(weaponConfig!=null){
                this.include.push(weaponConfig.id);
            }
        }
        //当前
        this.include.push(GameModel.single.synthesisMaxWeaponId);
        //高级3个
        for(let index=1;index<4;index++){
            weaponConfig=GameConfigManager.GetWeaponConfigByLevel(currentWeaponConfig.level+index);
            if(weaponConfig!=null){
                this.include.push(weaponConfig.id);
            }
        }
    }

    /**
     * 根据当前合成过的最大枪来计算列表数据
     */
    private GetListData():any[]{
        let result:any[]=[];
        let config:any=GameConfigManager.GetShopConfig(GameModel.single.synthesisMaxWeaponId);
        let weaponConfig:any;
        //解锁线
        let unlockLevel:number;
        if(config.unsealedGunId!=undefined){
            weaponConfig=GameConfigManager.GetWeaponConfig(config.unsealedGunId);
            unlockLevel=weaponConfig.level;
        }else{
            unlockLevel=-1;
        }
        let shopList:any[]=GameConfigManager.ShopList;
        shopList.sort((a,b)=> a.index-b.index);
        let itemData:any;

        for (let index = 0; index < shopList.length; index++) {
            const element = shopList[index];
            if(this.include.indexOf(element.id)<0){
                continue;
            }
            weaponConfig=GameConfigManager.GetWeaponConfig(element.id);
            itemData={
                id:element.id,
                index:element.index
            }
            //buyType 购买方式 0金币购买  1宝石购买 2 视频购买
            if(config.diamondPurchaseId==undefined){
                itemData.buyType=0;
            }else if(config.diamondPurchaseId.indexOf(element.id)>=0){
                itemData.buyType=1;
            }else if(config.videoId==undefined){
                itemData.buyType=0
            }else if(config.videoId==element.id){
                itemData.buyType=2;
            }else{
                itemData.buyType=0;
            }
            //state 0 未解锁  1 已解锁
            if(unlockLevel<0||weaponConfig.level>unlockLevel){
                itemData.state=0;
            }else{
                itemData.state=1;
            }
            result.push(itemData);
        }
        return result;
    }

    SwitchToggle(target:ToggleComponent,type:number,srollToZ:boolean):void{
        this.showType=type;
        //枪械
        if(type==0){
            this.WeaponList.node.active=true;
            this.FenceList.node.active=false;
            this.RefreshWeaponList(srollToZ);
        }else{//栏杆
            this.WeaponList.node.active=false;
            this.FenceList.node.active=true;
            this.RefreshFenceList(srollToZ);
        }
    }

    /**
     * 刷新栅栏列表
     */
    private RefreshFenceList(srollToZ:boolean=false):void{
        let itemView:Node;
        let jsonAsset:JsonAsset=GameConfigManager.GetConfig("Fence");
        let jsonConfig:any=jsonAsset.json;
        let dataList:any[]=jsonConfig;
        if(dataList.length!=this.FenceListContext.node.children.length){
            if(dataList.length<this.FenceListContext.node.children.length){
                //删除多余的
                while(dataList.length<this.FenceListContext.node.children.length){
                    this.FenceListContext.node.removeChild(this.FenceListContext.node.children[0]);
                }
            }else{
                //添加缺少的
                while(dataList.length>this.FenceListContext.node.children.length){
                    itemView=instantiate(this.FenceListItemRenderPrefab);
                    this.FenceListContext.node.addChild(itemView);
                }
            }
        }
        let itemScript:FenceItemRenderScript;
        let count:number=dataList.length;
        for (let index = 0; index < count; index++) {
            itemView=this.FenceListContext.node.children[index];
            itemScript=itemView.getComponent(FenceItemRenderScript);
            if(itemScript==null){
                throw new Error("商城列表项未挂载FenceItemRenderScript脚本!");
            }
            itemScript.UpdateItemRender(dataList[index]);
        }
        if(srollToZ){
            this.FenceList.scrollToTop(0.1);
        }
    }

    start () {
        // Your initialization goes here.
    }

    // update (deltaTime: number) {
    //     // Your update function goes here.
    // }
}
