import Panel from "../../MVC/views/Panel";
import { DataManager } from "../../../libs/tw/manager/DataManager";
import { NetName } from "../../../libs/tw/enum/NetName";
import SceneCtrl from "../../MVC/ctrls/sceneCtrl";
import { ModuleTypes } from "../../types/sceneTypes";
import { NetManager } from "../../../libs/tw/manager/NetManager";

export default class MyPrizeScene extends Panel {

	public backBtn: eui.Button;
	public scroller: eui.Scroller;
	public list: eui.List;

	public get skinKey() { return 'MyPrizeScene' }
	// public get groupName() { return 'prize_panel' }

	constructor(data?) {
		super(data);

	}
	initEvents() {
		this.backBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.touch_tap_back_btn, this);
	}

	touch_tap_back_btn() {
		SceneCtrl.instance.change(ModuleTypes.START_SCENE);
	}

	removeEvents() {
		this.backBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.touch_tap_back_btn, this);
	}

	protected onSkinComplete(): void {
		super.onSkinComplete();

		this.preLoadRes();
		this.onLoad();

	}

	protected onLoad(): void {
		this.initUI();
		let listData = [];
		NetManager.ins.queryRecords((success) => {
			if (!success) {
				return;
			}
			let data = DataManager.ins.getData(NetName.QUERY_RECORDS).data;
			for (let i = 0; i < data.length; i++) {
				let newData = {
					icon: data[i].extra.icon,
					title: data[i].extra.name,
				};

				if (data[i].refType == "coupon") {
					NetManager.ins.getCouponInfo((success) => {
						if (!success) { return; }
						newData['link'] = DataManager.ins.getData(NetName.GET_COUPON_INFO).data.link;
					}, data[i].id, () => {
						let data = DataManager.ins.getData(NetName.GET_COUPON_INFO);
						return !(data.success && data.code == '0000000000');
					}, 10);
				} else {
					newData['link'] = `/aaw/projectx/takePrize?projectOrderNo=${data[i].id}`;
				}
				listData.push(newData);
			}

			this.list.itemRenderer = MyPrizeItem;
			const ac = new eui.ArrayCollection(listData);
			this.list.dataProvider = ac;
		})
	}

	private initUI(): void {
		this.scroller.height = 750 / window.outerWidth * window.outerHeight - 120;
	}

	protected async preLoadRes() {

		return new Promise(function (resolve, reject) {
			resolve();
		});
	}
}


class MyPrizeItem extends eui.ItemRenderer {
	public icon: eui.Image;
	public title: eui.Label;

	constructor() {
		super();
		this.skinName = "resource/skins/MyPrizeItemSkin.exml";
	}

	dataChanged() {
		this.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
			window.location.href = this.data.link;
		}, this);

		this.title.text = this.data.title;
		this.icon.source = this.data.icon;
		// this.validateNow();
	}
}