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?: string,
      checkInConfig?: Array<{
        id?: number,
        days?: string,
        experienceNum?: string,
        status?: string,
      }>,
    },
    // 推荐产品配置
    recommendProductConfig?: Array<{
      name?: string,
      shenShuGuiZei?: string,
      touZiQiXianText?: string,
      qigouText?: string,
      baiFenBiText?: string,
      fengXian?: string,
      code?: string,
      status?: string,
      realBuyJumpUrl?: string,
    }>,
    // 待存储产品code
    codeList?: Array<string>,
  } = {};

  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, { agreementTitle: '《模拟理财服务协议》', agreementText: '您即将进入第三方服务页面，该服务由华夏理财有限责任公司提供。为了便于您使用本页面服务，需要您主动提供手机号信息，个人信息仅用于本活动登录及参与，无其他用途。相关信息保护责任由华夏理财承担。' }) // TODO 字段？
    } 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, TODO } = resData

    if (firstMoneyPop) {
      ModalCtrl.showModal(FirstPop, firstMoneyPop);
    }
    if (TODO) {
      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());
