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';
import Loginpop from '@/panels/loginpop/loginpop';
import InvalidPop from '@/panels/invalidPop/invalidPop';
import FirstPop from '@/panels/firstPop/firstPop';
import Tipspop from '@/panels/tipspop/tipspop';

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

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

  indexData: {
    actStartTime?: number,
    actEndTime?: number,
    currentTime?: number, // 前端自定义
    // 我的终点时间
    myEndTime?: number,
    ruleText?: string,
    uid?: string,
    // 大明星配置
    bigStartConfig?: Array<{
      prizeImg?: string,
      titleImg?: string,
    }>,
    // 首次体验金弹窗
    firstMoneyPop?: {
      agreementText?: string,
      experienceNum?: number,
    },
    // 模拟资产
    virtualAssets?: {
      preDayIncome?: string,
      availableFunds?: string,
      totalMoney?: string,
      realBuyJumpUrl?: string,
      totalIncome?: string,
    },
    // 签到模块
    checkIn?: {
      totalCheckIn?: number,
      todayCheckIn?: boolean, // 今日是否签到(true签到)	
      totalExperienceNum?: number, // 累计可获得最高体验金数量
      checkInConfig?: Array<{
        id?: number,
        days?: number,
        experienceNum?: number,
        status?: boolean, // true已领奖
      }>,
    },
    // 推荐产品配置
    recommendProductConfig?: Array<{
      name?: string,
      shenShuGuiZei?: string,
      touZiQiXianText?: string,
      qigouText?: string,
      baiFenBiText?: string,
      fengXian?: string,
      code?: string,
      status?: string,
      realBuyJumpUrl?: string,
    }>,
    // 待存储产品code
    codeList?: Array<{
      code?: string,
      type?: number, // 产品类型(0-非现金，1-现金)
    }>,
    endPop?: boolean,
  } = {};

  async judgeIsWhiteUser() {
    const { success, data, code, message } = await API.isWhiteUser();
    if (success) {
      if (data) {
        location.replace(data);
      } else {
        await this.updateIndex();
      }
    } else if (code == 60001) {
      // 非白名单用户
      ModalCtrl.showModal(InvalidPop);
    } else if (code == 60002) {
      // 请绑定手机号
      ModalCtrl.showModal(Loginpop)
    } else {
      Toast.show(message || '网络异常，请稍后再试')
    }
  }

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

    const { firstMoneyPop, endPop } = resData

    if (firstMoneyPop) {
      ModalCtrl.showModal(FirstPop, firstMoneyPop);
    }
    if (endPop) {
      ModalCtrl.showModal(Tipspop);
    }
  }

  async doSign() {
    const { success, data } = await API.doCheckIn();
    this.updateIndex();
    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;
  }


  /** 普通分享 */
  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
    };

    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.getInviteCode({ 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.doAssist({ inviteCode: inviteCode });
    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  }

}

export default (new Store());
