import { _decorator, Color, instantiate, Label, Layout, Node, Prefab, ScrollView, Sprite } from 'cc';
import { ResKeeper } from '../../../framework/res/ResKeeper';
import { StringUtil } from '../../../framework/util/StringUtil';
import List from '../../../framework/list/List';
import { FateattridConf } from '../../config/FateattridConf';
import { AttrAddTypeEnum, AttrConf, ItemEnum } from '../../common/InterfaceAddEnum';
import { RoleManager } from '../../manager/RoleManager';
import { CommonItem } from '../common/CommonItem';
import { Framework } from '../../../framework/Framework';
import { GameEvent } from '../../data/GameEvent';
import { GoodsData } from '../../data/GoodsData';
import { GoodsManager } from '../../manager/GoodsManager';
import { GlobalConf } from '../../config/GlobalConf';
const { ccclass, property } = _decorator;

@ccclass('HeroFateItem')
export class HeroFateItem extends ResKeeper {
	@property({ type: Sprite, tooltip: "名称背景" })
	titleBg: Sprite = null;

	@property({ type: Label, tooltip: "名称文字" })
	titleTx: Label = null;

	@property({ type: Node, tooltip: "英雄节点" })
	itemNode: Node = null;

	@property({ type: Node, tooltip: "升级按钮" })
	updateBtn: Node = null;

	@property({ type: Label, tooltip: "升级按钮文字" })
	updateBtnTx: Label = null;

	@property({ type: Node, tooltip: "激活按钮" })
	activeBtn: Node = null;

	@property({ type: Label, tooltip: "激活按钮文字" })
	activeBtnTx: Label = null;

	@property({ type: List, tooltip: "描述列表" })
	svDesc: List = null;

	private _data = {};
	private canActive = false;
	private _descData = [];
	private _costNum = 0;

	protected onLoad() {
		this.updateBtnTx.string = StringUtil.getLanguageData('升级');
		this.activeBtnTx.string = StringUtil.getLanguageData('激活');
	}

	protected onDestroy() {
		//如果该组件有事件自行取消注释
		//Framework.event.removeEvent(this);
		super.onDestroy();
	}

	//如果使用了池中的节点,在该函数内归还,该函数会在onDestroy前调用
	onClose() {

	}

	//UI事件处理
	private onTouchButton(event: Event) {
		//Framework.audio.playEffect(AudioID.Click);
		let target: any = event.target;
		if (target.name == 'update_btn') {
			let cost = GoodsManager.getGoodsById(String(GlobalConf.data.FateMatId.Value));
			if (cost.count < this._costNum) {
				Framework.tips.setTips(StringUtil.getLanguageData('升级所需材料不足'));
				return;
			}
			let args = {
				id: this._data['conf']['Id']
			}
			RoleManager.sendFateLevelUp(args, () => {
				Framework.event.fireEvent(GameEvent.FateChange);
			})
		} else if (target.name == 'active_btn') {
			let cost = GoodsManager.getGoodsById(String(GlobalConf.data.FateMatId.Value));
			if (cost.count < this._costNum) {
				Framework.tips.setTips(StringUtil.getLanguageData('激活所需材料不足'));
				return;
			}
			if (!this.canActive) {
				Framework.tips.setTips(StringUtil.getLanguageData('至少需要获得两个英雄!'));
				return;
			}
			let args = {
				id: this._data['conf']['Id']
			}
			RoleManager.sendFateLevelUp(args, () => {
				Framework.event.fireEvent(GameEvent.FateChange);
			})
		}
	}

	refreshItem(data) {
		this._data = data;
		let color = '#ffffff'
		if (data.conf.Grade == 1) {
			color = '#7CE680'
		} else if (data.conf.Grade == 2) {
			color = '#306AFF'
		} else if (data.conf.Grade == 3) {
			color = '#A46DEB'
		} else if (data.conf.Grade == 4) {
			color = '#EB9A6D'
		} else if (data.conf.Grade == 5) {
			color = '#EB6D6D'
		}
		this.titleBg.color = new Color(color);

		this.canActive = false;
		let activeRole = 0
		for (const element of data.conf.FateRidArray) {
			let role = RoleManager.getRoleById(element);
			if (role) {
				if (role['id']) {
					activeRole = activeRole + 1
				}
				this.load('common', `prefab/CommonItem`, Prefab, (pre: Prefab) => {
					let item = instantiate(pre);
					this.itemNode.addChild(item);
					item.getComponent(CommonItem).setClickEnable(false);
					item.getComponent(CommonItem).setNumShow(false);
					item.getComponent(CommonItem).setGray(role['id'] ? false : true);
					item.getComponent(CommonItem).refreshItem(role);
				})
			}
		}
		
		this.canActive = (activeRole >= 2);

		this._descData = [];
		this.itemNode.removeAllChildren();
		let atteConf = FateattridConf.data;
		for (let lv = 1; lv <= 4; lv++) {
			let arr = ['', '', ''];
			for (let index = 0; index < data.conf.AttrIdArray.length; index++) {
				const element = atteConf[data.conf.AttrIdArray[index]];
				let attr = element['AttrLevel' + lv].split(':');
				let attrConf = AttrConf[attr[0]]
				let value = attrConf.type == AttrAddTypeEnum.reality ? attr[1] + '' :
					parseFloat((100 * Number(attr[1])).toFixed(2)) + '%'
				arr[1] = StringUtil.getLanguageData(attrConf.name);
				if (arr[0] == '') {
					arr[0] = arr[0] + element.Num
				} else {
					arr[0] = arr[0] + '/' + element.Num
				}
				if (arr[2] == '') {
					arr[2] = arr[2] + value
				} else {
					arr[2] = arr[2] + '/' + value
				}
			}
			if (this._costNum <= 0) {
				if (lv > data.level) {
					this._costNum = data.conf['LevelCost' + lv]
				}
			}

			let t = {
				str: 'Lv.' + lv + ' ' + StringUtil.getLanguageData(`{0}人同时上阵,羁绊中英雄{1}提升{2}`, arr),
				state: lv <= data.level
			}
			this._descData.push(t);
		}


		this.svDesc.numItems = this._descData.length;

		let name = StringUtil.getLanguageData(data.conf.Name);
		if (data.level > 0) {
			this.titleTx.string = name + ' Lv.' + data.level;
			this.updateBtn.active = true;
			this.activeBtn.active = false;
		} else {
			this.titleTx.string = name + ` (${StringUtil.getLanguageData('未激活')})`;
			this.updateBtn.active = false;
			this.activeBtn.active = true;
		}
	}

	onEventList(item, idx) {
		item.getComponent(Label).string = this._descData[idx].str;
		if (this._descData[idx].state) {
			item.getComponent(Label).color = new Color('#8A6230');
		} else {
			item.getComponent(Label).color = new Color('#C5B29A');
		}
		if (idx == this._descData.length - 1) {
			this.scheduleOnce(() => {
				this.svDesc.getComponent(ScrollView).content.getComponent(Layout).updateLayout(true);
			}, 0.1);
		}
	}
}