import { Panel } from "../../module/views/Panel";
import { RES } from "../../module/RES";
import { showWaiting, getCurrentScene, showToast, hideWaiting } from "../../module/ctrls";
import { sendTbNet, TbNetName } from "../TaoBaoNet";
import { Tools } from "../Tools";
import { GDispatcher } from "../Main";
import { G_EVENT } from "../common/G_EVENT";
import { layers } from "../../module/views/layers";


//任务类型,可能变
export enum TaskType {
	follow = "follow",
	login = "login",
	invites = "invites",
	browserPage = "browserPage",
	orderGoods = "orderGoods",
}

interface TaskData {
	/**
	 * 任务类型
	 */
	taskType: string
	/**
	 * 任务文案
	 */
	title: string
	/**
	 * 任务奖励
	 */
	rewards: number
	/**
	 * 任务每日限制次数
	 */
	times: number
	/**
	 * 任务频率	
	 */
	taskRateType: number
	/**
	 * 待领取次数
	 */
	waitReceive: number
	/**
	 * 总共完成次数
	 */
	completeTimes: number
	/**
	 * 今日完成次数
	 */
	todayCompleteTimes: number
	/**
	 * 任务状态 1未完成 2 待领取 3 已完成
	 */
	status: number
	/**
	 * 链接地址
	 */
	url: string
	/**
	 * 商品配置ids 商品相关任务返回
	 */
	itemIds: string
}



export class TaskPanel extends Panel {
	get groupNames() { return ["TaskPanel"] }
	get skinName() { return "TaskPanel" }
	scrollView: FYGE.Container;
	txt5: FYGE.TextField;
	txt4: FYGE.TextField;
	txt2: FYGE.TextField;
	txt1: FYGE.TextField;
	btn5: FYGE.Button;
	btn4: FYGE.Button;
	btn3: FYGE.Button;
	btn2: FYGE.Button;
	btn1: FYGE.Button;
	closeBtn: FYGE.Button;

	[TaskType.follow]: CusButton;
	[TaskType.login]: CusButton;
	[TaskType.invites]: CusButton;
	[TaskType.browserPage]: CusButton;
	[TaskType.orderGoods]: CusButton;

	public showAni() {
		//底部适配,原先都是居中的，其他简单情况
		//  this.y = (layers.stageHeight - 1624) / 2
		//  var oriY = this.y;
		//  this.y += this.getLocalBounds().height;

		if (this.isShowing) return;
		this.isShowing = true;
		let oriY = 1624 - this.height - layers.stageOffsetY - this.getLocalBounds().y - this.parent.y;
		//正常的按上面这样算个就行，但是下面加了个滚动，不显示所有任务
		oriY += 330
		this.y = layers.stageHeight + this.height;
		console.log(oriY)
		FYGE.Tween.get(this)
			.to({ y: oriY }, 500, FYGE.Ease.quartOut)
			.call(() => {
				this.isShowing = false;
				//点击背景
				var g = this.addChildAt(new FYGE.Graphics(), 0)
					.beginFill(0xff0000)
					.drawRect(0, -this.y + layers.stageOffsetY - this.parent.y, 750, layers.stageHeight)
					.endFill()
					.addEventListener(FYGE.MouseEvent.CLICK, this.hidePanel, this)
				g.alpha = 0;
				g.renderable = false;//为了不被计算bound
			});
	}
	initUi() {
		//加滚动
		var scroll = this.addChild(new FYGE.ScrollPage(750, 600, this.scrollView.height + 25))
		scroll.position.set(0, 714)
		scroll.view.addChild(this.scrollView).position.set(24, 0)
		//修改原先按钮
		//移除了吧，只需要位置
		this.scrollView.removeChildren(this.btn1, this.btn2, this.btn3, this.btn4, this.btn5);
		var ps = [this.btn1, this.btn2, this.btn3, this.btn4, this.btn5];
		[TaskType.follow, TaskType.login, TaskType.invites, TaskType.browserPage, TaskType.orderGoods].forEach((e, i) => {
			this[e] = this.scrollView.addChild(new CusButton(e))
			this[e].position.copy(ps[i].position);
			this[e].visible = false;
			//文案弄个指向吧
			if (i != 2) {
				this[e]["txt"] = this["txt" + (i + 1)];
				this["txt" + (i + 1)].bold = true;
			}
		})

		this.txt1.text = "关注店铺\t(0/1)";
		this.txt2.text = "每日登录\t(0/1)";
		// this.txt3.text = "购买商品(0/1)";
		this.txt4.text = "浏览指定页面10s\t(0/1)";
		this.txt5.text = "预售商品付定金\t(0/2)";

		this.txt1["textOri"] = "关注店铺\t(%todayCompleteTimes%/%times%)";
		this.txt2["textOri"] = "每日登录\t(%todayCompleteTimes%/%times%)";
		// this.txt3["textOri"] = "购买商品(%todayCompleteTimes%/%times%)";
		this.txt4["textOri"] = "浏览指定页面10s\t(%todayCompleteTimes%/%times%)";
		this.txt5["textOri"] = "预售商品付定金\t(%todayCompleteTimes%/%times%)";

	}
	start(data) {
		super.start();
		this.updateTask();
	}
	public async updateTask() {
		showWaiting();
		var res = await sendTbNet(TbNetName.getTaskList)

		hideWaiting();
		if (!res.success) return;
		var data: TaskData[] = res.data;
		data.forEach((d) => {
			//关注店铺特殊处理  TODO可能还要改
			if (d.taskType == TaskType.follow) {
				// status任务状态 
				// 1未完成 2 待领取 3 已完成
				if (d.waitReceive || d.status == 3) {
					d.todayCompleteTimes = d.times = 1
				}
				else if (d.status == 1) {
					d.times = 1
					d.todayCompleteTimes = 0;
				}
			}
			//修改文案,邀请的没有文案
			if (d.taskType != TaskType.invites) {
				this[d.taskType]["txt"].text = this[d.taskType]["txt"].textOri.replace(/%todayCompleteTimes%/gi, d.todayCompleteTimes + "");
				this[d.taskType]["txt"].text = this[d.taskType]["txt"].text.replace(/%times%/gi, d.times + "")
			}

			this[d.taskType].visible = true;
			//如果有入会链接
			if (d.url) this[d.taskType].url = d.url;
			//如果又itemIds
			if (d.itemIds) this[d.taskType].itemIds = d.itemIds;
			//如果有待领取的
			if (d.waitReceive) {
				this[d.taskType].canGetStatus = true;
				this[d.taskType].enabled = true;
			}
			//如果是邀请的除了待领取就是去完成
			else if (d.taskType == TaskType.invites) {
				this[d.taskType].canGetStatus = false;
				this[d.taskType].enabled = true;
			}
			//如果已全部完成
			else if (d.todayCompleteTimes == d.times || d.status == 3) {
				this[d.taskType].canGetStatus = false;
				this[d.taskType].enabled = false;
			}
			//去完成状态
			else {
				this[d.taskType].canGetStatus = false;
				this[d.taskType].enabled = true;
			}
		})


	}

	/**
	 * 重写,加个消失动画
	 */
	hidePanel() {
		var endY = this.y + this.getLocalBounds().height;
		FYGE.Tween.get(this)
			.to({ y: endY }, 300)
			.call(() => {
				super.hidePanel()
			})
	}
	initEvents() {
		super.initEvents();
		GDispatcher.addEventListener(G_EVENT.UPDATE_TASK, this.updateTask, this);
	}
	removeEvents() {
		super.removeEvents();
		GDispatcher.removeEventListener(G_EVENT.UPDATE_TASK, this.updateTask, this);
	}
}

class CusButton extends FYGE.Button {
	private type: TaskType
	private _canGetStatus: boolean;
	get canGetStatus() {
		return this._canGetStatus
	}
	set canGetStatus(value) {
		this._canGetStatus = value;
		var t: [FYGE.Texture, FYGE.Texture]
		if (value) {//能领取时换图
			t = [
				RES.getRes("receiveBtn.png"),
				RES.getRes("receiveBtn.png"),
			]
		} else {
			t = [
				RES.getRes("goCompleteBtn.png"),
				RES.getRes("completeBtn.png"),
			]
		}
		this.changeTexture(t[0], t[0], t[1])
	}
	//外部自行赋值
	url: string
	constructor(type: TaskType) {
		var t = [
			RES.getRes("goCompleteBtn.png"),
			RES.getRes("completeBtn.png"),
		]
		super(t[0], t[0], t[1])
		this.type = type;
		//事件统一写吧
		this.addEventListener(FYGE.MouseEvent.CLICK, this.onClick, this)
	}

	onClick() {
		if (this.canGetStatus) {//能领取，发接口
			showWaiting();
			sendTbNet(
				TbNetName.receiveTaskRewards,
				{ taskType: this.type },
				(s, res) => {
					hideWaiting();
					if (s) {
						//领取成功,
						showToast("任务完成，次数+" + res.data.rewards);
						//刷新任务列表
						GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK);
						//次数更新,TODO ，字段待定
						Tools.gameInfo.gameCounts = res.data.gameTimes
						//首页刷新次数TODO，需要发接口，用接口数据刷新
						GDispatcher.dispatchEvent(G_EVENT.UPDATE_SCENE);
					}
				}
			)
		} else {//发对应任务方法
			//都弄个延时
			Tools.btnDelay(this)
			switch (this.type) {
				//分享
				case TaskType.invites:
					sendTbNet(
						TbNetName.showSharePanel,
						{ openId: Tools.globalData.openId },//注意小程序那边处理参数
						() => { },
						true
					);
					break;
				//关注
				case TaskType.follow:
					//由于点击空白区域关闭授权弹框拿不到任务回调，以防万一，移除事件
					GDispatcher.removeAllEventListenerByType(TbNetName.favorShop);
					sendTbNet(TbNetName.favorShop, {},
						(success, res) => {
							if (!success) return;
							//关注成功了，发完成接口，注意小程序那边就不用发接口了
							sendTbNet(
								TbNetName.doFollowTask,
								{ taskType: TaskType.follow },//其实不需要参数
								(success, res) => {
									if (!success) return;
									GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK);
								}
							);
						}, true
					);
					break;
				//购买商品
				case TaskType.orderGoods://商品集合页
					sendTbNet(
						TbNetName.navigateTo,
						{ url: '/pages/goodsPage/goodsPage?taskType=orderGoods&itemIds=' + this["itemIds"] },//TODO，路径待定
						() => { },
						true
					);
					//返回需要刷任务列表接口
					GDispatcher.once(G_EVENT.ON_SHOW, () => {
						GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK)
					}, this)
					break;
				//浏览商品，指定页面
				case TaskType.browserPage:
					sendTbNet(
						TbNetName.navigateToOutside,
						{ url: this.url },//指定页面
						() => { },
						true
					);
					//记录时间
					let last = Date.now();
					GDispatcher.once(G_EVENT.ON_SHOW, () => {
						if (Date.now() - last > 10 * 1000) {
							//达到了，刷新
							//完成任务
							showWaiting()
							sendTbNet(
								TbNetName.doJumpLinkTask,
								{ taskType: this.type }, //参数不需要了，完成任务接口都独立了
								(s) => {
									//刷新任务列表
									if (s) GDispatcher.dispatchEvent(G_EVENT.UPDATE_TASK)
								}, true)
						} else {
							showToast("未达到10秒")
						}
					}, this)
					break;
				//登录接口必完成不用

			}

		}
	}



}

