import { makeAutoObservable } from 'mobx';
import API from '../api/index';
import store from './store';
import { CHANNEL } from '@/AppTools';
import { Toast } from '@grace/ui';
import { hxbankShare } from './bank';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';


const shareStore = makeAutoObservable({
  /** 邀请码 */
  inviteCode: "",
  /** 邀请链接 */
  inviteUrl: "",

  /** 获取邀请码 */
  async getInviteCode() {
    // const { success, data } = await API.queryInviteCode({
    //   channel: CFG.channel
    // })
    const { success, data } = await API.getInviteCode()
    if (success && data) {
      const { inviteCode } = data || {}
      this.inviteCode = inviteCode
      return inviteCode
    }
    return ''
  },

  /** 获取分享链接 */
  async getShareLink(isInvite = false) {
    let url = `${CFG.domain}${CFG.shareUrl}`;
    if (isInvite) {
      if (!this.inviteCode) {
        await this.getInviteCode();
      }
      url += `&inviteCode=${this.inviteCode}`;
    }
    this.inviteUrl = url;
    return url;
  },

  /** 分享 TODO 看看有没有普通分享这个场景 */
  async doShare(isInvite = false) {
    console.log("🚀 ~ CFG:", CFG,CFG.channel, CHANNEL.HXBANK)
    const { shareInfo } = store.frontVariable;
    const _url = await this.getShareLink(isInvite);
    // 分享方法
    hxbankShare({
      ...shareInfo,
      url: _url
    })
    // if (CFG.channel == CHANNEL.HXBANK) { // 华夏银行APP分享
    //   const _url = await this.getShareLink(isInvite);
    //     // 分享方法
    //     hxbankShare({
    //       ...shareInfo,
    //       url: _url
    //     })
    // } else {

    // }
  },

  /** 助力 */
  async doAssist(sucCb) {
    if (!CFG.inviteCode) return false;
    console.info("进入助力！！！")
    if (sessionStorage.getItem("inviteCode")) return false;
    const { success } = await API.doAssist({ inviteCode: CFG.inviteCode });
    if (success) {
      Toast.show("助力成功");
      sucCb?.()
    }
    sessionStorage.setItem("inviteCode", CFG.inviteCode);
    history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
  },
})
export default shareStore;

