import { showPanel, showToast } from "../Module/UIFast";
import { getUrlParam } from "./Utils/Utils";
import { getWebData, sendWebNet, sendWebNetWithToken, WebNetName } from "./Utils/WebNet/WebNet";
import { SHARE_TYPE } from "./const";
import ShareCenter from "./ShareCenter";
import { appJump } from "./Utils/appFn";
import { Node } from "cc";
import { HomeScene } from "./Scenes/HomeScene";
import { TaskPanel } from "./Panels/TaskPanel/TaskPanel";
import PosterPanel from "./Panels/PosterPanel";
import BrowseImgPanel from "./Panels/BrowseImgPanel";
import store from "../store/store";

const levelToast = {
    3: "恭喜您今日运势极佳，可领取3次挑战次数",
    2: "恭喜您今日运势上佳，可领取2次挑战次数",
    1: "恭喜您今日运势上等，可领取1次挑战次数",
};

const beforeDoComplete = (item: any, func: Function) => {
    console.log("点了去完成");
    const hasBtnText = !!item?.buttonText;
    const time = hasBtnText? 1000: 0;
    if (hasBtnText) {
        showToast(item?.buttonText);
    }
    setTimeout(() => {
        !!func && func();
    }, time);
}

export default class TaskCenter {

	private static _ins: TaskCenter = null;
    /** 任务信息 */
    private _taskInfo: Object = {};
    /** 所有任务数据（未过滤装备任务） */
    private _taskInfoOrigin = [];
    /** 当前的tab */
    private _tab: string = null;

	public static get ins() {
		!TaskCenter._ins && (TaskCenter._ins = new TaskCenter());
		return TaskCenter._ins;
	}

    get taskInfo() {
        return this._taskInfo;
    }

    get taskInfoOrigin() {
        return this._taskInfoOrigin;
    }

    get taskTabInfo() {
        return this._taskInfo[this._tab];
    }

    set taskInfo(data) {
        this._taskInfo = data;
    }

    set taskInfoOrigin(data) {
        this._taskInfoOrigin = data;
    }

    get tab() {
        return this._tab;
    }

    set tab(tabName: string) {
        this._tab = tabName;
    }





    /** 查询任务 */
    async getTaskInfo() {
        const res = await sendWebNet(WebNetName.queryTasks);
        if (res?.success) {
            // 所有任务数据（未过滤装备任务）
            TaskCenter.ins.taskInfoOrigin = res?.data?.item || [];

            const temp = {};

            for (let item of (res?.data?.item || [])) {
                const desc = JSON.parse(item?.desc);
                // 20240220迭代 desc字段增加返回 taskType 1:装备任务 2:活动任务(前端需要做过滤显示)
                if (desc?.taskType == 1) continue
                // if (!!temp[desc.tabType]) {
                //     temp[desc.tabType].push(item);
                // } else {
                //     temp[desc.tabType] = [item];
                // }
                // 20240227 去掉tab 减少改动点 保持原来有tab的数据格式
                if (!!temp['all']) {
                    temp['all'].push(item);
                } else {
                    temp['all'] = [item];
                }
            }
            TaskCenter.ins.taskInfo = temp;
            if (!!!TaskCenter.ins.tab) {
                TaskCenter.ins.tab = Object.keys(temp)?.[0];
            }
        }
    }

    /** 完成任务 */
    async doCompleted(taskCode: string) {
        const res = await sendWebNetWithToken(WebNetName.doCompleted, {taskCode: taskCode});
        if (res?.success) {
            this.getTaskInfo();
        }
    }

    /** 设置tab */
    setTab(tabName: string) {
        if (!!!Object.keys(this.taskInfo).includes(tabName)) {
            console.log("不存在该tab");
            return;
        }
        TaskCenter.ins.tab = tabName;
    }

    /** 任务处理中心 */
    async handleClickTask(taskCode: string, item: any = {}, taskNode?: Node) {
        let jumpUrl = "";
        if (item?.jumpUrl) {
          jumpUrl = item?.jumpUrl?.split("$$$")?.[1];
        }
        /** 邀请任务 */
        if (taskCode?.startsWith("it")) {
            beforeDoComplete(item, () => {
                ShareCenter.ins.doShare(SHARE_TYPE.INVITE);
            })
        } 
        /** 浏览任务 */
        else if (taskCode?.startsWith("bt")) {
            if (taskCode == "bt_real") {
                // 真浏览-浏览长图任务
                showPanel(BrowseImgPanel, {
                    panelType: "topNoScale",
                    doneFun: async () => {
                        const res = await sendWebNetWithToken(WebNetName.finishBrowseTask, {taskCode: item?.code, taskId: item?.id})
                        if (res?.success) {
                            await this.getTaskInfo();
                            !!taskNode && taskNode.getComponent(TaskPanel).taskRender();
                        }
                    }
                })
            } else if (taskCode == "bt_mrys") {
                // 浏览每日运势任务
                showPanel(PosterPanel, {
                    sharedFun: async (level) => {
                        const res = await sendWebNetWithToken(WebNetName.finishBrowseTask, {taskCode: item?.code, taskId: item?.id, ysLevel: level})
                        if (res?.success) {
                            showToast(levelToast[level]);
                            await this.getTaskInfo();
                            !!taskNode && taskNode.getComponent(TaskPanel).taskRender();
                        }
                    }
                })
            } else {
                beforeDoComplete(item, async () => {
                    await sendWebNetWithToken(WebNetName.finishBrowseTask, {taskCode: item?.code, taskId: item?.id});
                    appJump(jumpUrl);
                })
            }
        } 
        /** 行方任务 */
        else if (taskCode?.startsWith("tt")) {
            beforeDoComplete(item, async () => {
                if (!item?.extra || item?.extra == 0) { // 未领取任务 调领取行方任务接口
                    await sendWebNetWithToken(WebNetName.claimThirdTask, {taskCode: item?.code, taskId: item?.id});
                }
                const type = item?.code.split("_")[1];
                if (type == "t") { // 行方交易任务
                    appJump(jumpUrl)
                } else if (type == "s") { // 行方签约任务
                    appJump(jumpUrl)
                }
            })
        }
        /** 会员等级达标任务 */
        else if (taskCode == 'hydjdb') {
            // 能给链接跳转 就配置正常配置jumpUrl
            // 不能跳转 jumpUrl配置$$$ 需要toast提示就配置buttonText
            beforeDoComplete(item, async () => {
                appJump(jumpUrl)
            })
        }
    }

    /** 领取奖励 */
    async receivePrize(item, taskNode: Node) {
        const res = await sendWebNetWithToken(WebNetName.sendPrize, {taskCode: item?.code, prizePendingCode: item?.prizePendingCode});
        if (res?.success) {
            await this.getTaskInfo();
            !!taskNode && taskNode.getComponent(TaskPanel).taskRender();
            store.updateIndex();
            showToast("任务完成，奖励已发放");
        }
    }

}

