import { makeAutoObservable, toJS} 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/index';
import { CHANNEL, queryAppFundDetail } from '@/AppTools';
import EndPop from '@/panels/endPop';
import { PrizePanel } from '@/panels/PrizePanel/PrizePanel';
import FirstPop from '@/panels/firstPop/firstPop';
import SetupSuccessPop from '@/panels/setupSuccessPop'

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,
    firstMoneyPop: {
      agreementText: string,
      experienceNum: number,
    },
    // 模拟资产
    virtualAssets: {
      preDayIncome: number,
      availableFunds: number,
      totalMoney: number,
      totalIncome: number,
      profit: number
    },
    // 产品配置
    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,
    canJoinCurrentRank: boolean,
  } = {} as any;

  /**
   * 更新某些基金信息
   * @param fundcodeList 需要查询的基金code列表
   */
  async updateFundInfo(fundcodeList) {
    console.info('需要查询的基金code列表, ', fundcodeList.map(item => item.code))
    // 调客户端方法 查询产品的收益率等信息
    const adInfos = []
    for (let len = fundcodeList.length, i = 0; i < len; i++) {
      const res = await queryAppFundDetail(fundcodeList[i])
      if (res) adInfos.push(res)
    }
    // 本地自测代码
    // adInfos[0] = {
    //   fundcode: '23112008P',
    //   incomeRate: '1.78%',
    //   pernetValue: '1.0690',
    // }

    // 将客户端查到的收益率 更新到产品列表中
    const _temp = JSON.parse(JSON.stringify(this.indexData))
    _temp.recommendProductConfig = _temp.recommendProductConfig?.map(item => {
      const _adInfo = adInfos.find(adInfo => adInfo.fundcode == item.code)
      if (_adInfo) {
        item.rate = (_adInfo.incomeRate.replace('%', '') || 0) * 10000 / 100
        return item
      }
      return item
    })
    this.indexData = _temp;
    console.info('基金产品收益率信息(客户端更新后的), ', toJS(this.indexData))

    if (!adInfos?.length) return
    // 将客户端查到的收益率 更新我们后端
    const _codeList = adInfos.map(item => {
      return {
        code: item.fundcode, // 产品code
        incomeRate: (item.incomeRate.replace('%', '') || 0) * 10000 / 100, // 年化率(单位：分),例如：1.78%传递178
        netValue: (item.pernetValue || 0) * 1000000 / 100, // 净值(单位：分),例如:1.66传递16600
      }
    })
    const params = {
      codeList: _codeList,
    }
    console.info('coop_codeUpdate入参，', params)
    API.coop_codeUpdate(params)
  }

  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, firstMoneyPop, codeList } = resData

    // 更新产品信息
    if (codeList?.length) {
      this.updateFundInfo(codeList)
    }

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

    // 发放初始理财体验金弹窗
    if (firstMoneyPop) {
      ModalCtrl.showModal(FirstPop, {
        notifyText: firstMoneyPop.agreementText,
        experienceNum: firstMoneyPop.experienceNum,
      })
    }

    // 新手礼包获得弹窗
    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());
