import { makeAutoObservable } from "mobx";
import API from "../api/index";
import store from "./store";
// import modalStore from "./modal";
import { saveCookies, setCookies } from "./fetcher";
import shareStore from "./share";
import { isWeChat } from "../utils/share";
import { getUrlParam, windowJumpUrl } from "../utils/utils";
import { appJump } from "../utils/sensors.js";
import { CHANNEL_PARAMS, TASK_CODE } from "../utils/constants";
import { Toast } from "@grace/ui";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl";
import LongImgPop from "@/panels/longImgPop/longImgPop.jsx";
import { handleLogClick, handleLogExposure } from "../MD";

interface TaskItem {
  jumpUrl?: string;
  code?: string;
  id?: string;
  prizePendingCode?: string;
}

const taskStore = makeAutoObservable({
  /** 当前任务 */
  curTask: {} as TaskItem,
  setCurTask(data: TaskItem) {
    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 || [];
      (data?.item || []).map((item,index)=>{
        console.log('item?.taskStatus',item?.taskStatus)
        if(item?.taskStatus == 0){
          if(item?.code == 'invite'){
            handleLogExposure(35,3)
          }else{
            handleLogExposure(35,1)
          }
        }else if(item?.taskStatus == 1){
          handleLogExposure(35,2)
        }
      })
    }
  },

  /** 去完成 */
  async doTask(item) {
    // jumpUrl 后端已经根据渠道返回对应的链接
    const { code, jumpUrl } = item || {};
    handleLogClick(35,1)
    switch (true) {
      //签到
      case code == "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("bt_3_") > -1:
        ModalCtrl.closeModal();
        ModalCtrl.showModal(LongImgPop,{
          imgUrl: jumpUrl,
          taskSucCb: async () => {
            await this.complete(item);
          },
          noCount: false,
          type: code == "bt_3_poster" ? 1 : 2, //1海报 2视频
        })

        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("browse_shui_yue") > -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=0) {
    const { id, code } = item || {};
    let params = {
      taskCode: code,
    };
    const res = await API.doCompleted(params);
    // await store.getHomeInfo();

    if (code.indexOf("browse_") > -1 && isWeChat()) {
      setTimeout(() => {
        this.getTaskList();
      }, 1500);
    } else {
      this.getTaskList();
    }

    return res;
  },

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

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