import { makeAutoObservable, } from 'mobx';
import API from '../api/index';
import { Toast } from "@grace/ui";
import { initWx } from "@/built-in/share/weixin/weixin.ts";
import { _asyncThrottle, _debounce, getUrlParam } from '@/utils/utils';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { getDomain } from '@spark/dbdomain';
import { showShareGuide } from '@spark/share';
import BlackPop from '@/panels/blackPop';
import SetupPop from '@/panels/setupPop';
import SetupSuccessPop from '@/panels/setupSuccessPop';
import EndPop from '@/panels/endPop';
import { PrizePanel } from '@/panels/PrizePanel/PrizePanel';

class Store {

  constructor() {
    makeAutoObservable(this);
  }
  homeRoot= null;

  /** 前端开发配置 */
  frontVariable: {
    // 虚拟盘项目id
    otherProjectId: string,
    homeTip: any;
    shareInfo: any,
    ruleImg?: string,
  } = {
      otherProjectId: '',
      shareInfo: {
        title: "",
        desc: "",
        imgUrl: "",
      },
      homeTip: ''
    };

  ruleInfo = '';

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

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

  indexData: {
    actStartTime: number,
    actEndTime: number,
    // 模拟资产
    virtualAssets: {
      preDayIncome: number,
      availableFunds: number,
      totalMoney: number,
      totalIncome: number,
      profit: string
    },
    // 产品配置
    recommendProductConfig?: Array<{
      name?: string,
      shenShuGuiZei?: string,
      qigouText?: string,
      fengXian?: string,
      code?: string,
      realBuyJumpUrl?: string,
      mineProduct?: boolean, // 我的产品(true是)
      rate?: number, // 利率（需要除100展示）
      type?: string, // 产品类型(0-非现金，1-现金)
      totalProfit?: number, // 累计收益，mineProduct为true时有值，单位：分	
      positionMoney?: number, // 持仓金额，mineProduct为true时有值，单位：分	
    }>,
    productEnd: boolean,
    endPoint: number,
    giftPop: {
      actPrizeVO?: Array<{
        prizeName?: string,
        prizeImg?: string,
        prizeId?: string,
      }>
      pop: boolean,
      show: boolean
    },
    lcGradeIcon: boolean,
    lastMonthRankPop: boolean,
    overallRankPop: {
      prizeId: string,
      prizeImg: string,
      prizeName: string,
    },
    bannerInfo: {
      bannerImg: string,
      bannerLink: string,
    }[],
    currentTime: number,
    black: boolean,
    signInStatus: boolean,
  } = {} as any;

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

    const { black, giftPop, lastMonthRankPop, overallRankPop, signInStatus } = resData

    // 非白名单名单拦截弹窗
    if (black) {
      ModalCtrl.showModal(BlackPop);
    }

    // 立即报名弹窗
    if (!signInStatus) {
      ModalCtrl.showModal(SetupPop);
    }

    // 报名成功的弹窗
    if (giftPop?.pop) {
      ModalCtrl.showModal(SetupSuccessPop);
    }

    // 上月理财成绩弹窗
    if (lastMonthRankPop) {
      ModalCtrl.showModal(EndPop);
    }

    if (overallRankPop) {
      ModalCtrl.showModal(PrizePanel, {
        optionImg: overallRankPop.prizeImg,
        optionName: overallRankPop.prizeName,
      });
    }
  }

  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);
    const url = `${domain || location.origin}${CFG.index}`;

    const shareInfo = this.frontVariable?.shareInfo?.[0]
    const option = {
      title: shareInfo?.title,
      // 标题
      desc: shareInfo?.desc || '',
      // 描述
      imgUrl: shareInfo?.imgUrl,
      link: 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]
    const option = {
      title: shareInfo?.title,
      // 标题
      desc: shareInfo?.desc || '',
      // 描述
      imgUrl: shareInfo?.imgUrl,
      link: url
    };

    showShareGuide();

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

    initWx(option);
  }

  async doAssist() {
    const inviteCode = getUrlParam('inviteCode')
    if (!inviteCode || inviteCode == 'null' || inviteCode == 'undefined') return false;
    const { success, message, code } = await API.doAssist({ inviteCode: inviteCode });
    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  }

}

export default (new Store());
