import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { IWxShareInfo } from "@/built-in/share/weixin/weixin.ts";
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import Ranknoprizepop from '@/components/ranknoprizepop/ranknoprizepop';
import Rankprizepop from '@/components/rankprizepop/rankprizepop';
import { getUrlParam } from '@/utils/utils';
import { isWechatMiniProgram, isWeiXin } from '@/AppTools';
import { handleLogExposure } from '@/MD';

class Store {

  constructor() {
    makeAutoObservable(this);
  }

  /** 前端开发配置 */
  frontVariable: {
    privacyTxt: string,
    prizeInfoAuthTxt: string,
    shareInfo: IWxShareInfo,
    shopUrl?: string,
    scanUrl?: string,
  } = {
      privacyTxt: "",
      prizeInfoAuthTxt: "",
      shareInfo: {
        title: "",
        desc: "",
        link: "",
        imgUrl: "",
      },
    };

  ruleInfo = '';

  /** 获取活动规则 */
  async initRule() {
    // 模拟获取远程的数据
    const { data } = await API.getRule();
    this.ruleInfo = data;
  }

  /** 获取前端配置项 */
  async getFrontVariable() {
    // 获取前端开发配置
    const { data } = await API.getFrontVariable();
    this.frontVariable = data || {};
    console.log('前端开发配置', data)
  }

  indexData: {
    remainTimes?: number,
    uid?: string,
    actEndTimestamp?: number,
    timeStamp?: number,
    actStartTimestamp?: number,
    remainDrawTimes?: number,
    newAssist?: number,
    rankPopInfo?: {
      sendPrize: boolean,
      prizeName: string,
      prizeImg: string,
      rank: number
    },
    rank?: {
      rank: number,
      prizeName: string,
      prizeImg: string,
    }
  } = {};

  async updateIndex() {
    const { success, data, timeStamp } = await API.index();
    if (!success) {
      return;
    }
    this.indexData = data;
    this.indexData.timeStamp = timeStamp;

    if (data.rankPopInfo) {
      if (data.rankPopInfo.sendPrize) {
        ModalCtrl.showModal(Rankprizepop, { ...data.rankPopInfo })
      }
      // else {
      //   ModalCtrl.showModal(Ranknoprizepop, { ...data.rankPopInfo })
      // }
    }

    if (data?.newAssist > 0) {
      this.showToast(`成功邀请${data.newAssist}位好友助力`)
    }
  }

  judgeActTime(brakeStart = true, brakeEnd = true) {
    if (brakeStart && this.indexData.timeStamp < this.indexData.actStartTimestamp) {
      Toast.show("活动未开始");
      return false
    } else if (brakeEnd && this.indexData.timeStamp > this.indexData.actEndTimestamp) {
      Toast.show("活动已结束，感谢您的关注～");
      return false
    }
    return true;
  }
  taskList = [];
  async queryTask() {
    const { success, data } = await API.queryTasks();
    if (success) {
      this.taskList = data.item;
      for (let i = 0; i < data.item.length; i++) {
        if (data.item[i].code === 'login') {
          if (data.item[i].taskStatus == 1) {
            handleLogExposure(9)
          }
        } else if (data.item[i].code === 'invite') {
          if (data.item[i].taskStatus == 0) {
            handleLogExposure(10, 1)
          } else if (data.item[i].taskStatus == 1) {
            handleLogExposure(10, 2)
          }
        } else if (data.item[i].code === 'scan') {
          if (data.item[i].taskStatus == 0) {
            handleLogExposure(11, 1)
          } else if (data.item[i].taskStatus == 1) {
            handleLogExposure(11, 2)
          }
        }
      }
    }
  }
  async doAssist() {
    let code = getUrlParam('inviteCode')
    const { success, data } = await API.doAssist({ inviteCode: code });
    if (success) {
      Toast.show("成功为好友助力，一起来参与活动吧～");
    }
    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  }
  prizeList = [];
  async getPrizeList() {
    const resp = await API.getPrizeList();
    if (resp.success) {
      this.prizeList = resp.data;
    }
  }
  province: string = '';
  city: string = '';
  area: string = '';
  name: string = '';
  phone: string = '';
  detail: string = '';
  goMiniApp() {
    if (isWechatMiniProgram()) {
      // 小程序内跳转

    } else if (isWeiXin()) {
      // 微信内跳转

    }
  }
  toastList = []
  toastCon = false;
  showToast(lab?: string) {
    if (lab) {
      this.toastList.push(lab)
    }
    if (this.toastCon) {
      return;
    }
    this.toastCon = true
    Toast.show(this.toastList.shift())
    setTimeout(() => {
      this.toastCon = false;
      if (this.toastList.length > 0) {
        this.showToast()
      }
    }, 2000)

  }

}

export default (new Store());
