import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { 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 Choice_challenge from '../../src/components/choice_challenge/choice_challenge';
import SkyFullGoldPanel from "@/panels/SkyFullGoldPanel/SkyFullGoldPanel.tsx";
import Renewmodule from '../../src/components/renewmodule/renewmodule';
import Finish_challenge from '../../src/components/finish_challenge/finish_challenge';
import { IBubbleInfo } from "@/pages/HomePage/Top/Components/Bubble.ts";
import { IOverflowBubbleInfo } from "@/pages/HomePage/Top/Components/OverflowBubble.ts";
import ReturnAwardPanel from "@/panels/ReturnAwardPanel/ReturnAwardPanel.tsx";
import NewcomerPanel from "@/panels/NewcomerPanel/NewcomerPanel.tsx";
import WedExpPanel from "@/panels/WedExpPanel/WedExpPanel.tsx";
import SignSucPanel from "@/panels/SignSucPanel/SignSucPanel.tsx";

class Store {

  constructor() {
    makeAutoObservable(this);
  }

  baseInfo: any = {};

  /** 前端开发配置 */
  frontVariable: {
    shareInfo: IWxShareInfo,
    ruleImg?: string,
  } = {
      shareInfo: {
        title: "",
        desc: "",
        link: "",
        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;

    if (data.downGoldVo) {
      ModalCtrl.showModal(SkyFullGoldPanel, data.downGoldVo);
    }

    if (data.returnAwardCreditsNum) {
      ModalCtrl.showModal(ReturnAwardPanel, {
        creditNum: data.returnAwardCreditsNum,
      });
    }

  }

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


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

    const { boolLimit, newLuckCreditsNum } = data;

    if (newLuckCreditsNum) {
      ModalCtrl.showModal(NewcomerPanel, { creditNum: newLuckCreditsNum, });
    }

    if (boolLimit) {
      // 周三限时奖励
      ModalCtrl.showModal(WedExpPanel, data);
    } else {
      ModalCtrl.showModal(SignSucPanel, 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<{
      code: string;
      icon: string;
      subTitle: string;
      title: string;
      completedSize: number;
      intervalLimitSize: number;
      intervalType: number;
    }>;
    boolNeedChallengeCompletePop?: boolean;
    latestChallengeSuccessTime?: number;
    boolNeedResignPop?: boolean;
  } = {
      challengeStartTime: 0,
      challengeEndTime: 0
    };

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

  async getTaskInfo() {
    const { success, data } = await API.getChallengeIndex();
    if (success && data) {
      this.taskInfo = data
      const { boolOpenChallenge = 0,
        choosedChallengeId = 0,
        hasChallengeDay = 0,
        boolNeedResign,
        challengeConfigList = [],
        taskInfoList = [],
      } = this?.taskInfo || {};

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

      // 当前挑战信息
      const {
        challengeTotalDay = 0,
        prizeName = '',
        prizeImg = '',
        resignJf = 0,
        resignQg = 0,
      } = currentChallenge || {};

      if (!data.choosedChallengeId) {
        ModalCtrl.showModal(Choice_challenge)
      }
      if (data.boolNeedResignPop) {
        ModalCtrl.showModal(Renewmodule, { hasChallengeDay, resignJf, resignQg });
      }
      if (data.boolNeedChallengeCompletePop) {
        ModalCtrl.showModal(Finish_challenge, { prizeName, prizeImg })
      }
    }
  };

  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=[^&]*`), ''));
  }

}

export default (new Store());
