import { _decorator, Node,Label, EventTouch} from 'cc';
import List from '../third/List';
import { Utils } from '../utils/Utils';
import { userIns } from '../data/UserData';
import { GunItem } from '../items/item/GunItem';
import { autoBind } from '../extend/AutoBind';
import { BaseExp } from '../core/base/BaseExp';
import { GunAttrItem } from '../items/item/GunAttrItem';
import { GunTypeItem } from '../items/item/GunTypeItem';
import { uiMgr } from '../core/manager/UIManager';
import { Constants } from '../data/Constants';
import MsgHints from '../utils/MsgHints';
const { ccclass, property } = _decorator;

@ccclass('ArsenalUI')
export class ArsenalUI extends BaseExp {
    @autoBind({ type: List, tooltip: "枪的属性列表" })
    public gun_atts_scrollView: List;
    @autoBind({ type: List, tooltip: "枪的类型列表" })
    public gun_type_scrollView: List;
    @autoBind({ type: List, tooltip: "枪的列表" })
    public gun_scrollView: List;
    @autoBind({ type: Label, tooltip: "枪的名字" })
    public gun_name_label: Label;
    @autoBind({ type: Label, tooltip: "枪的类型的名字" })
    public type_name_label: Label;
    @autoBind({ type: Node, tooltip: "模型摄像机" })
    public model_camera: Node;

    //枪的属性数据
    private gunAttrList:Array<any> = [];
    //枪的类型数据
    private gunTypeList:Array<any> = [];
    //每个类型下的枪的数据
    private gunList:Array<any> = [];
    //玩家选择的类型 默认用户使用的枪的所在的类型
    private curTypeData:any = null;
    //用户当前选择的枪 默认用户当前使用的枪
    private curGunData:any = null;

    start() {
        this.hasAnim = false;
        this.closeOnBlank = false;
    }
    
    public show(...args: any[]){
        this.model_camera.active = true;
        this.curGunData = userIns.getCurUseGun();
        this.loadArsenalData();
    }

    public hide(){
        this.model_camera.active = false;
    }

    /**
     * 加载武器库数据 选中的类型数据
     * @param typeData 选择的类型 默认用户选中的第一把枪的类型
     */
    public loadArsenalData(typeData:any = null){
        //列表2、枪的类型列表、查询玩家拥有的枪的类型 按type分组 从每个分组中取出第一个元素
        const groupedByType = userIns.playerGunsTable.reduce((acc: Record<number, any[]>, gun) => {
            if (!acc[gun.type]) {
                acc[gun.type] = [];
            }
            acc[gun.type].push(gun);
            return acc;
        }, {});
        if(this.gunTypeList.length <= 0){
            this.gunTypeList = Object.values(groupedByType).map(group => {
                const typeData = group[0];
                //判断该类型是否解锁（用户是否拥有该类型的枪）
                const unlocked = userIns.data.guns.some(gun => gun.type === typeData.type);
                //判断是否选中类型（与当前使用枪械类型一致）
                const selected = typeData.type === this.curGunData?.type;
                return { 
                    ...typeData,
                    unlocked: unlocked,
                    selected: selected 
                };
            });
        }
        this.gun_type_scrollView.numItems = this.gunTypeList.length;
        this.curTypeData = typeData ?? this.gunTypeList.find(gun => gun.type === this.curGunData.type);
        //枪的名字
        this.gun_name_label.string = this.curGunData.name_lang;
        //枪的类型的名字
        this.type_name_label.string = this.curTypeData.type_name;

        //列表3、类型的下的枪的类表、查询该类型下玩家拥有的枪
        const hasGunList = Utils.clone(userIns.data.guns)
                .filter(gun => gun.type === this.curTypeData.type)
                .map(gun => ({ 
                    ...gun, 
                    unlocked: true,
                    selected: gun.id == this.curGunData.id
                })); //添加解锁状态;
        //添加未解锁的枪
        const unlockGuns = Utils.clone(userIns.playerGunsTable)
                .filter(gun => 
                    gun.type === this.curTypeData.type && 
                    !hasGunList.some(g => g.id === gun.id)
                )
                .map(gun => ({ 
                    ...gun, 
                    unlocked: false,
                    selected: false
                }));
        //合并已解锁和未解锁的枪械列表
        this.gunList = [...hasGunList, ...unlockGuns];
        this.gun_scrollView.numItems = this.gunList.length;

        //模型摄像机下的枪
        this.model_camera.children.forEach(child => {
            child.active = `${this.curGunData.prb_name}_gun` === child.name;
        });

        //列表1、选择枪的属性列表
        this.gunAttrList = [];
        const values = userIns.gunAttrKeys.map(key => this.curGunData[key]);
        values.forEach((value,i) => {
            let attr_name: string = userIns.gunAttrKeys[i];
            //里面包括属性总的值和最大等级值 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
            })
        });
        this.gun_atts_scrollView.numItems = this.gunAttrList.length;
    }

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

    /**
     * 选择枪列表的数据
     * @param item item节点
     * @param idx 数据信息
     */
    public setGunListItemData(item: Node, idx: number) {
        let com:GunItem = item.getComponent(GunItem);
        com.init(this.gunList[idx],(gunData:any)=>{
            this.curGunData = gunData;
            this.loadArsenalData(this.curTypeData);
        }); 
    }

    /**
     * 选择枪的类型的数据
     * @param item item节点
     * @param idx 数据信息
     */
    public setGunTypeItemData(item: Node, idx: number) {
        let com:GunTypeItem = item.getComponent(GunTypeItem);
        com.init(this.gunTypeList[idx],(typeData:any)=>{
            this.gunTypeList.forEach(e=>e.selected = e.id == typeData.id);
            this.loadArsenalData(typeData);
        }); 
    }

    /**
     * 按钮点击事件
     * @param event 事件
     * @param param 参数
     */
    override onBtnClicked(event:EventTouch, param:any) {
        super.onBtnClicked(event,param);
        let btnName = event.target.name;
        if(btnName === 'upgrade_btn'){//升级枪的按钮
            if(!this.curGunData){
                MsgHints.show('Gun data not found');
                return;
            }
            this.model_camera.active = false;
            uiMgr.show(Constants.popUIs.upgradeGunUI,[this.curGunData]);
        }
    }
}

