"use strict";

import React from "react";
import { observer } from "mobx-react";
import "./taskpop.less";
import API from "@src/api";
import { _asyncThrottle, _throttle, windowJumpUrl } from "@src/utils/utils";
import { unwatchPageVisibility, watchPageVisibility } from "@spark/utils";
import { Toast } from "@spark/ui";
import { TASK_CODE } from "@src/utils/constants";
import modalStore from "@src/store/modal";
import { sensorMdClick, sensorMdExpouse } from "@src/utils/sensorMd";
import { Button } from "../Button";
import { miniGoUrl } from "@src/utils/share";
import { SvgaPlayer } from "@spark/svgaplayer";
import { RES_PATH } from "../../../sparkrc";
import store from "@src/store";
import { MD5 } from "crypto-js";
import { handleLogExposure, handleLogClick } from "../../../MD";

@observer
class Taskpop extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      taskInfo: [], // 任务列表
    };
  }
  async componentDidMount() {
    sensorMdExpouse("activityPage", { pageName: "任务页" });
    this.getTaskList();
  }

  componentWillUnmount() {
    unwatchPageVisibility(this.pageVChange);
  }

  /** 页面显示 */
  pageVChange = (visible) => {
    console.log("页面", visible ? "可见" : "不可见");
    if (visible) {
      this.getTaskList();
    }
  };

  /**
   * 获取任务列表数据
   */
  getTaskList = async () => {
    const { success, data } = await API.queryTasks();
    if (success && data) {
      this.setState({
        taskInfo: data || {},
      });
    }
  };

  // 按钮点击事件
  completeHandle = _throttle(async (item) => {
    handleLogClick(23);
    sensorMdClick("activityClick", { pageName: "任务页", buttonName: "去完成" });
    const { userId } = store.homeInfo || {};
    const { code, jumpUrl } = item || {};
    const systemTime = Date.now();
    const sign = MD5(`${userId}_${code}_${systemTime}_1c5f9cab3460e316`).toString();
    const params = {
      sign,
      taskCode: code,
      timestamp: systemTime,
    };
    if (code.indexOf(TASK_CODE.THIRD_RETAIN) > -1) {
      // sensorMdClick("PopupClick", { pageName: "任务页", buttonName: "留资咨询" });
      setTimeout(() => {
        windowJumpUrl(jumpUrl);
      }, 300);
    } else if (code.indexOf(TASK_CODE.BROWSE_PRODUCT) > -1) {
      // sensorMdClick("PopupClick", { pageName: "任务页", buttonName: "浏览产品" });
      modalStore.pushPop("LongImgPop", {
        imgUrl: jumpUrl,
        taskSucCb: async () => {
          await API.doCompleted(params);
        },
      });
    } else if (code.indexOf(TASK_CODE.SIGN) > -1) {
      // sensorMdClick("PopupClick", { pageName: "任务页", buttonName: "每日签到" });
    } else if (code.indexOf(TASK_CODE.BROWSE_MINI) > -1) {
      await API.doCompleted(params);
      watchPageVisibility(this.pageVChange);
      if (jumpUrl.indexOf("http") === 0) {
        setTimeout(() => {
          windowJumpUrl(jumpUrl);
        }, 300);
      } else {
        miniGoUrl(jumpUrl);
      }
    } else if (code.indexOf(TASK_CODE.BROWSE_VIDEO) > -1) {
      // sensorMdClick("PopupClick", { pageName: "任务页", buttonName: "浏览视频" });
      modalStore.pushPop("Videopop", {
        url: jumpUrl,
        taskSucCb: async () => {
          await API.doCompleted(params);
        },
      });
    }
  });

  /** 任务领奖 */
  receiveHandle = _asyncThrottle(async (task) => {
    handleLogClick(23);
    sensorMdClick("activityClick", { pageName: "任务页", buttonName: "去领取" });
    const { success, data } = await API.sendPrize({
      // taskId: task.id,
      taskCode: task.code,
      prizePendingCode: task?.prizePendingCode,
    });
    if (success) {
      data?.options?.[0]?.sendCount && Toast(`恭喜您领取${data.options[0].sendCount}次抽奖次数`);
      this.getTaskList();
    }
  });

  /* 关闭弹窗*/
  closeHandle = () => {
    this.props.popData?.refresh && this.props.popData?.refresh();
    modalStore.closePop();
  };

  render() {
    const { taskInfo } = this.state;
    return (
      <div className="taskpop">
        <SvgaPlayer className="task_svga" src={RES_PATH + "svga/pop.svga"} />
        <span className="bg"></span>
        <div className="task_list">
          {taskInfo?.item?.map((item, index) => {
            handleLogExposure(23);
            return (
              <div className="task_item" key={index}>
                <span className="task_item_bg"></span>
                <img className="task_icon" src={item.icon} />
                <div className="task_title">{item.title}</div>
                <span className="task_subtitle">{item.subTitle}</span>
                {/* taskStatus  任务状态      * 0 去完成，任务完成次数未达到上限      * 1 待领奖      * 2 已完成，任务完成次数达到上限 */}
                {item.taskStatus === 0 && (
                  <Button className="task_btn red_bg" onClick={() => this.completeHandle(item)}></Button>
                )}
                {item.taskStatus === 1 && (
                  <Button className="task_btn yellow_bg" onClick={() => this.receiveHandle(item)}></Button>
                )}
                {item.taskStatus === 2 && (
                  <Button
                    className="task_btn grey_bg"
                    onClick={() => {
                      handleLogClick(23);
                    }}>
                    已完成
                  </Button>
                )}
              </div>
            );
          })}
        </div>
        <Button className="close" onClick={this.closeHandle}></Button>
      </div>
    );
  }
}
export default Taskpop;
