import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { initWx, IWxShareInfo } from "@/built-in/share/weixin/weixin.ts";
import { _asyncThrottle, _debounce, getUrlParam } from '@/utils/utils';
import { IBubbleInfo } from "@/pages/HomePage/Top/Components/Bubble.ts";
import { IOverflowBubbleInfo } from "@/pages/HomePage/Top/Components/OverflowBubble.ts";
import { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';

class Store {

  constructor() {
    makeAutoObservable(this);
  }

  baseInfo: any = {};

  /** 前端开发配置 */
  frontVariable: {
    shareInfo: any,
    ruleImg?: string,
  } = {
    shareInfo: {
      title: "",
      desc: "",
      imgUrl: "",
    },
  };

  ruleInfo = '';

  /** 积分门票 */
  ticketNum = null;

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

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

  indexData: {
    actStartTime?: number,
    actEndTime?: number,
    currentTime?: number,

    guideFlag?: boolean,
    creditsNum?: number,
    expireDays?: number,
    currentStoreNum?: number,
    storeLimitNum?: number,
    continueSignDays?: number,
    todaySignFlag?: boolean,
    signRecords?: {
      id: string,
      day: number,
      creditsNum: number,
      boolSign: boolean,
    }[],

    overflowBubble?: IOverflowBubbleInfo,

    bubbleRecords?: IBubbleInfo[],

    returnAwardCreditsNum?: number,

    downGoldVo?: {
      creditsNum: number,
      multipleValue: number,
      taskId: string,
      url: string,
    }

  } = {};

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

  /**
   * 更新首页信息，给倒计时用的
   */
  updateIndexThrottle = _debounce(async () => {
    return await this.updateIndex();
  }, 500);

  judgeActTime(brakeStart = true, brakeEnd = true) {
    if (brakeStart && this.indexData.currentTime < this.indexData.actStartTime) {
      Toast.show("活动未开始");
      return false
    } else if (brakeEnd && this.indexData.currentTime > this.indexData.actEndTime) {
      Toast.show("活动已结束");
      return false
    }
    return true;
  }

  /** 普通分享 */
  async initShare() {
    const domain = await getDomain();
    console.error('看下域名', domain);
    let url = `${domain || location.origin}${CFG.index}`;

    const shareInfo = this.frontVariable?.shareInfo?.[0]
    let option = {
      title: shareInfo?.title,
      // 标题
      desc: shareInfo?.desc || '',
      // 描述
      imgUrl: shareInfo?.imgUrl,
      link: url
    };

    option.link = (domain || location.origin) + CFG.loginMidUrl + encodeURIComponent(url);
    initWx(option);
  }

  /** 邀请好友 */
  async doInvite(taskCode) {
    const domain = await getDomain();
    console.error('看下域名', domain);
    let url = `${domain || location.origin}${CFG.index}`;

    const shareInfo = this.frontVariable?.shareInfo?.[1]
    let option = {
      title: shareInfo?.title,
      // 标题
      desc: shareInfo?.desc || '',
      // 描述
      imgUrl: shareInfo?.imgUrl,
      link: url
    };

    showShareGuide();

    const res = await API.getChallengeInviteCode({ taskCode: taskCode })
    url += `&inviteCode=${res.data.inviteCode}`;

    option.link = (domain || location.origin) + CFG.loginMidUrl + encodeURIComponent(url);
    initWx(option);
  }

  async doAssist() {
    let inviteCode = getUrlParam('inviteCode')
    if (!inviteCode || inviteCode == 'null' || inviteCode == 'undefined') return false;
    const { success, message, code } = await API.getChallengeAssist({ inviteCode: inviteCode });

    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  }

}

export default (new Store());
