import { _decorator, Node, Label} from 'cc';
import { BaseExp } from '../core/base/BaseExp';
import List from '../third/List';
import { autoBind } from '../extend/AutoBind';
import { userIns } from '../data/UserData';
import MsgHints from '../utils/MsgHints';
import { Constants } from '../data/Constants';
import { stateMgr } from '../core/manager/StateManager';
import { UpgradeItem } from '../items/item/UpgradeItem';
import { uiMgr } from '../core/manager/UIManager';
import { ArsenalUI } from './ArsenalUI';
import { audioMgr } from '../core/manager/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('UpgradeGunUI')
export class UpgradeGunUI extends BaseExp {
    @autoBind({ type: List, tooltip: "枪的属性数据" })
    public gun_attr_scrollView: List;
    @autoBind({ type: Label, tooltip: "金币文本" })
    public gold_lable: Label;
    @autoBind({ type: Label, tooltip: "钻石文本" })
    public diamond_lable: Label;
    @autoBind({ type: Node, tooltip: "模型摄像机" })
    public model_camera: Node;

    //升级数据
    private gunAttrList:any[] = [];
    //枪数据
    private curGunData:any = null;

    start() {
        this.hasAnim = false;
        this.closeOnBlank = false;
        //注册动态变化值
        stateMgr.registerUI(Constants.gold, this.gold_lable);
        stateMgr.registerUI(Constants.diamond, this.diamond_lable);
    }
    
    public show(...args: any[]){
        this.model_camera.active = true;
        const gunData:any = args[0];
        //加载选中的枪
        this.loadUpgradeData(gunData.id);
    }

    public hide(){
        this.model_camera.active = false;
        const arsenalUI:ArsenalUI = uiMgr.getPageComponent(Constants.popUIs.arsenalUI);
        arsenalUI.model_camera.active = true
    }

    /**
     * 加载枪的数据
     */
    public loadUpgradeData(id:string){
        this.curGunData = userIns.data.guns.find(gun => gun.id === id);
        //模型摄像机下的枪
        this.model_camera.children.forEach(child => {
            child.active = `${this.curGunData.prb_name}_gun` === child.name;
        });
        //选择枪的属性列表
        this.gunAttrList = [];
        const values = userIns.gunAttrKeys.map(key => this.curGunData[key]);
        values.forEach((value,i) => {
            let attr_name: string = userIns.gunAttrKeys[i];
            // 生成消耗字段的key（使用驼峰命名转换）
            const attr = attr_name.replace(/^\w/, (c) => c.toUpperCase());
            const expendKey:string = `next${attr}Expenditure`;
            const uniqueIdKey:string = `${attr_name}UniqueId`;
            const attrLevelKey:string = `${attr_name}Level`;
            //里面包括属性总的值和最大等级值 totalValue maxLevel
            let mData = userIns.getGunMaxValue(this.curGunData,attr_name);
            this.gunAttrList.push({
                attr_name: attr_name,
                attr_value: value,
                attr_icon: this.curGunData[`${attr_name}_icon`],
                ...mData,
                attribute_lang: userIns.playerGunAttsTable.find(e=>e.attribute_name == attr_name)?.attribute_lang,
                nextExpenditure: this.curGunData[expendKey] || '',
                unique_id: this.curGunData[uniqueIdKey] || '',
                level: this.curGunData[attrLevelKey] || 1
            })
        });
        this.gun_attr_scrollView.numItems = this.gunAttrList.length;
    }

    /**
     * 选择枪的属性升级列表的数据
     * @param item item节点
     * @param idx 数据信息
     */
    public setGunAttsItemData(item: Node, idx: number) {
        let com:UpgradeItem = item.getComponent(UpgradeItem);
        com.init(this.gunAttrList[idx],this.clicked.bind(this)); 
    }

    /**
     * item上的按钮点击事件
     * @param data 数据
     * @param idx 点击按钮的下标 1、免费看广告 2、金币 3、钻石
     * @param clikTarget 点击对象
     */
    public clicked(data:any,idx:number,clikTarget: Node){
        if(data.isMaxLevel){
            MsgHints.show(`This gun ${data.attr_name} is at the maximum level!`);
        }else{
            const [id,num] = data.nextExpenditure.split("_");
            const sData:any = userIns.itemTable.find(e=>e.id == id);
            //是否升级
            let isSucced: boolean = false;
            if(idx == 1){//免费看广告
            }else if(idx == 3){//金币钻石
                if(sData.id == 1001){
                    if(userIns.data.gold < num){
                        MsgHints.show("Insufficient gold!");
                    }else{
                        userIns.data.gold -= num;
                        isSucced = true;
                    }
                }else if(sData.id == 1002){//钻石
                    if(userIns.data.diamond < num){
                        MsgHints.show("Insufficient diamonds!");
                    }else{
                        userIns.data.diamond -= num;
                        isSucced = true;
                    }
                }
            }
            if(isSucced){//升级
                userIns.upgradeGun(this.curGunData,data.attr_name);
                //刷新数据
                this.loadUpgradeData(this.curGunData.id);
                audioMgr.playOneShot(Constants.audios.upgrade);
            }
        }
    }
}

