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 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 Finish_task from '../../src/components/finish_task/finish_task';
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";
import { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';
import Assist_succeed from "../../src/components/assist_succeed/assist_succeed"
import Assist_fail from "../../src/components/assist_fail/assist_fail"
import Fail_challenge from "../../src/components/fail_challenge/fail_challenge"
import GuidePanel from "@/panels/GuidePanel/GuidePanel.tsx";

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;

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

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

    if (!data.guideFlag) {
      ModalCtrl.closeModal(GuidePanel);
      ModalCtrl.showModal(GuidePanel, {}, false);
    }

  }

  /**
   * 更新首页信息，给倒计时用的
   */
  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;

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

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

      // 当前挑战的挑战礼物信息
      const {
        prizeName = '',
        prizeImg = ''
      } = challengeSuccessPopInfo || {};

      if (boolOpenChallenge) {
        if (!choosedChallengeId) {
          ModalCtrl.showModal(Choice_challenge)
        }
        if (boolNeedResignPop) {
          ModalCtrl.showModal(Renewmodule, { hasChallengeDay, resignJf, resignQg });
        }
        taskInfoList.forEach(task => {
          if (task.boolShowCompletePop) {
            const { title } = task
            ModalCtrl.showModal(Finish_task, { title });
          }
        });
      }
      if (challengeSuccessPopInfo) {
        ModalCtrl.showModal(Finish_challenge, { prizeName, prizeImg })
      }
      if (boolShowFailPop) {
        ModalCtrl.showModal(Fail_challenge)
      }
    }
  };

  /** 普通分享 */
  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 });
    if (success) {
      ModalCtrl.showModal(Assist_succeed);
    } else { ModalCtrl.showModal(Assist_fail, { code, message }); }

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

}

export default (new Store());
