import { makeAutoObservable } from "mobx";
import API from "../api/index";
import store from ".";
import { Toast } from "@spark/ui";
import modalStore from "./modal";
import { md5 } from "@spark/utils";
import { saveCookies, setCookies } from "./fetcher";
import { showShareGuide } from "@spark/share";
import shareStore from "./share";
import { handleLogClick, handleLogExposure } from "../../MD";
import { isWeChat } from "../utils/share";
import { appJump, getUrlParam, windowJumpUrl } from "../utils/utils";
import { CHANNEL_PARAMS, TASK_CODE } from "../utils/constants";

const taskStore = makeAutoObservable({
  /** 当前任务 */
  curTask: {},
  setCurTask(data) {
    this.curTask = data;
  },

  /** 任务列表 */
  taskList: [],
  /** 获取任务 */
  async getTaskList() {
    const { success, data } = await API.getTaskInfo({
      // 展示对应任务数据逻辑: 优先取分享人code 其次取url参数code 最终取绑定的业务员code（这个后端会自己取）
      code: getUrlParam("ykCode") || getUrlParam("code") || "",
      from: CFG.channel,
    });
    if ((success, data)) {
      this.taskList = data?.item || [];


    }
  },

  /** 去完成 */
  async doTask(item) {
    // jumpUrl 后端已经根据渠道返回对应的链接
    const { code, jumpUrl } = item || {};

    switch (true) {
      //签到
      case code == TASK_CODE.THIRD_SIGN:
        console.info("签到任务");
        await taskStore.complete(item);
        break;
      //邀请
      case code == TASK_CODE.INVITE:
        console.info("邀请任务");
        // const res =
        await shareStore.doInvite();
        // modalStore.pushPop("Shareposter", { qrCode: res }, true);
        break;
      //增员介绍 海报or视频
      case code?.indexOf(TASK_CODE.ZY) > -1:
        modalStore.closePop("Taskpop");
        modalStore.pushPop("LongImgPop", {
          imgUrl: jumpUrl,
          taskSucCb: async () => {
            await this.complete(item);
          },
          noCount: false,
          type: code == "zy_video" ? 2 : 1, //1海报 2视频
        });

        break;
      case code?.indexOf(TASK_CODE.SY) > -1:
        await taskStore.complete(item);
        break;
      // 七秒浏览 or 税优关爱百万任务
      default:
        console.info("七秒浏览任务", CFG.spcCode, CFG.workerCode);
        if (isWeChat()) {
          // 微信端
          await taskStore.complete(item);
          setTimeout(() => {
            if (CFG.channel == CHANNEL_PARAMS.YK_PUBLIC || CFG.channel == CHANNEL_PARAMS.YK_MINI) {
              // 友客渠道 需要单独拼参数 参数key直接配置在链接上 value取code
              // btt2_开头的任务 不需要前端拼code
              // let _url =
              //   code.indexOf(TASK_CODE.BROWSE_AREA) >= 0 ? jumpUrl : `${jumpUrl}${CFG.spcCode || CFG.workerCode || ""}`;
              // alert(CFG.spcCode || CFG.workerCode || "")
              let _url = `${jumpUrl}${CFG.spcCode || CFG.workerCode || ""}`;
              console.info("_url", _url);
              // alert(_url)
              windowJumpUrl(_url);
            } else {
              windowJumpUrl(jumpUrl);
            }
          }, 500);
        } else {
          // app
          taskStore.setCurTask(item);
          saveCookies();
          const thirdBrowseParams = {
            hyper_link: jumpUrl,
            is_back: "true",
            functionType: "1",
          };
          setTimeout(() => {
            appJump("queryUserBindCustomerManger", "", thirdBrowseParams, "infoCallBack");
          }, 300);
        }
        break;
    }
  },

  /** app获取绑定信息回调 */
  getInfoCallback(res) {
    console.info("info", res, res?.agentCode);
    const resObj = res ? JSON.parse(res) : {};
    const { curTask } = taskStore;
    console.info("curTask", curTask);
    if (JSON.stringify(curTask) == "{}") return;
    const agentCode = curTask.jumpUrl?.match(/agent_code=(\d+)/)?.[1];
    const _jumpUrl = !!agentCode
      ? curTask.jumpUrl?.replace(agentCode, resObj?.agentCode)
      : `${curTask.jumpUrl}&agent_code=${resObj?.agentCode}`;
    const thirdBrowseParams = {
      hyper_link: _jumpUrl,
      is_back: "true",
      function_type: "5",
    };
    console.info(`%c jumpUrl: ${_jumpUrl}`, "font-size: 20px; color: pink");
    appJump("Router", "duibaMethod", thirdBrowseParams, "browseCallBack");
  },

  /** app7s浏览跳转回调 */
  async getBrowseCallback(res) {
    const { curTask } = taskStore;
    console.info("curTask", curTask);
    if (JSON.stringify(curTask) == "{}") return;
    await setCookies();
    console.info("回调数据", res);
    let resObj = res ? JSON.parse(res) : {};
    if (curTask?.code?.indexOf(TASK_CODE.SY) > -1) {
      //税悦不管时间
      const res = await taskStore.complete(curTask);
      if (res?.success) {
        await taskStore.getTaskList();
      }
      return;
    }
    if (resObj.isSuccess == 1 && Number(resObj.time) >= 7) {
      const res = await taskStore.complete(curTask, resObj.time);
      if (res?.success) {
        await taskStore.getTaskList();
      }
    }
  },

  /** 完成任务 */
  async complete(item, time) {
    const { id, code } = item || {};
    const { userId } = store.homeInfo || {};
    // const systemTime = Date.now();
    // const sign = md5(`${userId}_${code}_${systemTime}_9f733a0ccf92439d`);
    let params = {
      // taskId: id,
      taskCode: code,
      // timestamp: systemTime,
      // sign: sign,
    };
    // if (time) {
    //   params.time = time;
    // }
    const res = await API.doCompleted(params);


    if(item?.jumpUrl && item?.jumpUrl !== '/' && code.indexOf(TASK_CODE.SY) > -1) {
      location.href = item?.jumpUrl;
    }

    if (code.indexOf(TASK_CODE.BROWSE_COMMON) > -1 && isWeChat()) {
      setTimeout(async () => {
        await this.getTaskList();
        // await store.getSalesManIndex();
      }, 1500);
    } else {
      await this.getTaskList();
      // await store.getSalesManIndex();
    }

    return res;
  },

  /** 领奖 */
  async getTaskPrize(item) {
    const { id, code, prizePendingCode } = item || {};

    // if (isWeChat()) {
    //   // 出二维码提示弹窗
    //   modalStore.closePop("Taskpop");
    //   modalStore.pushPop("TaskQrcode");
    //   return;
    // }

    const { success, data } = await API.sendPrize({
      taskId: id,
      taskCode: code,
      prizePendingCode: prizePendingCode,
    });
    // await store.getSalesManIndex();
    if (success && data) {
      Toast(`抽奖次数+${data?.options?.[0]?.sendCount || 0}`);
      await taskStore.getTaskList();
      // await store.getHomeInfo();
    }
  },
});
export default taskStore;
