import Gamecfg from "../../../common/gameCfg";
import { gameMethod } from "../../../common/gameMethod";
import { xlsItemInfo } from "../../../common/xlsConfig";
import { KindItem } from "../../../common/Xys";
import UIHelp from "../../../logic/ui/UIHelp";
import EventMng from "../../../manager/EventMng";
import { ResItemInfo } from "../../../shared/item/PtlItemInfo";
import { MsgItemChange_s } from "../../../shared/item/server/MsgItemChange_s";
import { I18n } from "../../../utils/I18nUtil";
import { ItemEvent } from "../../const/EventConst";
import { IconUrl } from "../../const/ResConst";
import { ConstItem, ItemBaseCfg, ItemKind } from "../../const/TypeConst";
import GameDataCenter from "../../GameDataCenter";
import { ItemModelData } from "./ItemModelData";

export default class ItemModel extends ItemModelData {
	// 本次登录不再提示是否购买,直接买的列表
	buyNowList: { [key: string]: boolean } = {};

	// private _showEfect: number[] = null;

	// get showEffectList() {
	// 	if (this._showEfect == null) {
	// 		this._showEfect = Gamecfg.mathInfo.getItem("item_show_effect")?.pram?.item;
	// 	}
	// 	return this._showEfect;
	// }

	constructor() {
		super("item");
		this.buyNowList = {};
	}

	onRegister(): void {
        GameDataCenter.gameServer.ListenMsg("item/server/ItemChange_s", this.onItemChange, this);
    }

	onItemChange(msg: MsgItemChange_s) {
        for (let key in msg) {
            if (Object.prototype.hasOwnProperty.call(msg, key)) {
                this.ItemInfo[key] = msg[key];
            }
        }
        EventMng.emit(ItemEvent.UP_ITEM);
    }
	
	setItemInfo(res: ResItemInfo) {
		this.ItemInfo = res;
	}

	getKindItem(kindItem: KindItem): KindItem {
		let item: KindItem = [];
		item[0] = kindItem?.[0] ?? 1;
		item[1] = kindItem?.[1];
		item[2] = this.getItemCount(kindItem);
		return item;
	}

	getItemCount(kindItem: KindItem | ConstItem): number {
		if (kindItem?.[0] == ItemKind.money) {
			switch (kindItem?.[1]) {
				case ConstItem.sp[1]:
					return  GameDataCenter.gridMap.hcInfo?.tili ?? 0;
				default:
					return this.ItemInfo?.[kindItem?.[1]] ?? 0;
			}
		}
	}

	getItemCfgBase(kindItem: KindItem | ConstItem): ItemBaseCfg {
		// console.log("kindItem:", kindItem)
		let baseInfo: ItemBaseCfg = {
			id: "",
			name: "",
			icon: "",
			pinzhi: 0,
			desc: "",
			type: "",
			detailType: "",
			from: [],
			param: {},
			iconUrl: "",
			iconshowtype: 0,
		};
		let kind = kindItem?.[0];
		let conf: any = null;
		let id = kindItem?.[1];
		let temp: { name: string; desc: string; url: string; pinzhi: number } = { name: null, desc: null, url: null, pinzhi: null };
		switch (kind) {
			case ItemKind.money:
				conf = Gamecfg.itemInfo.getItem(id?.toString());
				temp.name = I18n.getItemMoneyName(id);
				temp.desc = I18n.getItemMoneyDesc(id);
				temp.url = IconUrl.item + conf?.icon;
				break;
		}
		if (conf == null) {
			console.error("道具配置找不到:", JSON.stringify(kindItem));
			return baseInfo;
		}
		baseInfo.id = conf.id;
		baseInfo.name = temp.name; // temp.name
		baseInfo.icon = conf?.icon || "";
		baseInfo.pinzhi = conf?.pinzhi || temp?.pinzhi || 1;
		baseInfo.desc = temp?.desc || "";
		baseInfo.type = conf?.type || "";
		baseInfo.detailType = conf?.detailType || "";
		baseInfo.from = conf?.from || [];
		baseInfo.param = conf?.param || {};
		baseInfo.iconUrl = temp.url || "";
		baseInfo.iconshowtype = conf?.iconshowtype || 0;
		baseInfo.kind = kind;
		return baseInfo;
	}

	//根据类型获取道具列表
	getItemListByType(type: string): KindItem[] {
		let list: KindItem[] = [];
		return list;
	}
	// 检测道具是否满足,弹出获取途径
	isEnough(needItem: KindItem | ConstItem, showTips: boolean = true, preCostCount: number = 0): boolean {
		if (gameMethod.isEmpty(needItem)) {
			console.error("item.isEnough 传入参数错误");
			return;
		}
		//不传数量默认为1
		if ((this.getItemCount(needItem) - preCostCount) >= (needItem[2] ?? 1)) {
			return true;
		}
		if (showTips) {
			// if (UIHelp.IsShowingUI(UIBattleFailView) == false) {
			let itemCfg = Gamecfg.itemInfo.getItem(needItem[1].toString());
			if (!itemCfg) return false;
			UIHelp.ShowI18nTips("common_unenough_1", I18n.getItemMoneyName(itemCfg.id));
			if (this.checkJumpList(itemCfg).length > 0) {
				// FguiMgr.Instance.openUI(ItemDetailViewView, ViewZorder.POP, null, needItem); //来源改成详情
			}
			// }
		}
		return false;
	}

	/** 对多个道具检测是否足够 */
	isEnoughItems(needItems: KindItem[], showTips: boolean = true) {
		let isEnough: boolean = true;
		needItems.some(element => {
			if (!this.isEnough(element, showTips)) {
				isEnough = false;
				return;
			}
		});
		return isEnough;
	}

	/**
	 * 检测道具预表现后是否满足,弹出获取途径
	 * @param needItem
	 * @param showTips
	 * @param preCost 已预扣除道具数量
	 * @returns
	 */
	isPreEnough(needItem: KindItem | ConstItem, showTips: boolean = true): boolean {
		if (gameMethod.isEmpty(needItem)) {
			console.error("item.isEnough 传入参数错误");
			return;
		}
		//不传数量默认为1
		if (this.getItemPreCostCount(needItem) >= (needItem[2] ?? 1)) {
			return true;
		}
		if (showTips) {
			// if (UIHelp.IsShowingUI(UIBattleFailView) == false) {
			let itemCfg = Gamecfg.itemInfo.getItem(needItem[1].toString());
			if (!itemCfg) return false;
			UIHelp.ShowI18nTips("common_unenough_1", I18n.getItemMoneyName(itemCfg.id));
			if (this.checkJumpList(itemCfg).length > 0) {
				// FguiMgr.Instance.openUI(ItemDetailViewView, ViewZorder.POP, null, needItem); //来源改成详情
			}
			// }
		}
		return false;
	}

	private cacheItemCost: {
		[id: number]: number;
	} = {};

	getItemPreCostCount(kindItem: KindItem | ConstItem) {
		if (kindItem?.[0] == ItemKind.money) {
			let count = this.getItemCount(kindItem);
			count -= this.getItemPreCost(kindItem);
			return count < 0 ? 0 : count;
		}
	}

	private getItemPreCost(item: ConstItem | KindItem) {
		return this.cacheItemCost[item[1]] ?? 0;
	}

	addPreCost(item: ConstItem | KindItem, num: number) {
		if (this.cacheItemCost[item[1]] == null) {
			this.cacheItemCost[item[1]] = 0;
		}
		this.cacheItemCost[item[1]] += num;
	}

	clearPreCostItem(): void {
		this.cacheItemCost = {};
	}

	checkJumpList(itemMoney: xlsItemInfo): xlsJumpInfo[] {
		let jumplist = [];
		// if (itemMoney?.from?.length > 0) {
		// 	for (let index = 0; index < itemMoney.from.length; index++) {
		// 		let id = itemMoney.from[index]?.toString();
		// 		let jumpCfg = Gamecfg.jumpInfo.getItem(id);
		// 		if (jumpCfg) {
		// 			//关闭支付,隐藏跳转
		// 			if (jumpCfg.isHideByPay && !GameDataCenter.order.isOpenPay) {
		// 				continue;
		// 			}
		// 			jumplist.push(jumpCfg);
		// 		}
		// 	}
		// }
		return jumplist;
	}

	//发送消息
	async sendItemInfo() {
        let ret = await GameDataCenter.gameServer.ReqApi("item/ItemInfo", {});
        if (ret?.res) {
            this.setItemInfo(ret.res);
            EventMng.emit(ItemEvent.UP_ITEM);
        }
    }
}
