import { makeAutoObservable, toJS, } 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 { PageCtrl } from '@/core/ctrls/PageCtrl';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';

class Store {

  constructor() {
    makeAutoObservable(this);
  }

  baseInfo: any = {};

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

  ruleInfo = '';

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

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

  homeTipIndex = 0;
  homeTipsCon = null
  changeHomeTip = () => {
    console.log("changeHomeTip",toJS(this.homeTipIndex))
    clearTimeout(this.homeTipsCon)
    this.homeTipsCon = setTimeout(() => {
      if (this.homeTipIndex < this.frontVariable.homeTip.length - 1) {
        this.homeTipIndex++;
      } else {
        this.homeTipIndex = 0;
      }
      this.changeHomeTip()
    }, 5000)
  }
  /** 获取前端配置项 */
  async getFrontVariable() {
    // 获取前端开发配置
    const { data } = await API.getFrontVariable();
    this.frontVariable = data || {};
    console.log('前端开发配置', data)
    if (data.homeTip?.length > 0) {
      this.changeHomeTip()
    }
  }

  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,
    }[],

    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);


  async doSign() {
    const { success, data } = await API.sign();
    this.updateIndex();
    this.getTaskInfo();
    if (!success) return;

    const { boolLimit, newLuckCreditsNum } = data;

  }


  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;
  }

  // 首页挑战信息
  taskInfo: {
    boolOpenChallenge?: boolean;
    choosedChallengeId?: string;
    challengeStartTime: number;
    challengeEndTime: number;
    hasChallengeDay?: number;
    boolNeedResign?: boolean;
    challengeConfigList?: Array<{
      challengeId: string;
      challengeTotalDay: number;
      prizeName: string;
      prizeImg: string;
      resignJf: number;
      resignQg: number;
    }>;
    taskInfoList?: Array<{
      id: string | number;
      code: string;
      icon: string;
      subTitle: string;
      title: string;
      completedSize: number;
      intervalLimitSize: number;
      intervalType: number;
      jumpUrl?: string;
      boolShowCompletePop?: boolean;
    }>;
    boolNeedChallengeCompletePop?: boolean;
    latestChallengeSuccessTime?: number;
    boolNeedResignPop?: boolean;
    boolShowFailPop?: boolean;
    challengeSuccessPopInfo?: {
      prizeName: string;
      prizeImg: string;
    };
  } = {
      challengeStartTime: 0,
      challengeEndTime: 0
    };

  async getBaseIndex() {
    const { success, data } = await API.getChallengeBaseIndex()
    if (!success) return;
    this.baseInfo = data;
    this.indexData.creditsNum = data.jfNum;
  }

  async getTaskInfo() {
    const { success, data } = await API.getChallengeIndex();
    if (success && data) {
      this.taskInfo = data

      const { boolOpenChallenge,
        boolNeedResignPop,
        challengeSuccessPopInfo,
        boolShowFailPop,
        choosedChallengeId = 0,
        hasChallengeDay = 0,
        // boolNeedResign,
        challengeConfigList = [],
        taskInfoList = [],
      } = this?.taskInfo || {};

      // 找到当前挑战信息项
      const currentChallenge = challengeConfigList.find(
        item => item.challengeId === choosedChallengeId
      );

    }
  };

  /** 普通分享 */
  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 });
    await this.getTaskInfo();
    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  }

}

export default (new Store());
