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

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

  /** 获取邀请码 */
  async getInviteCode() {
    const { success, data } = await API.queryInviteCode({
      channel: CFG.channel
    })
    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;
    console.log(url)
    return url;
  },

  /** 分享 TODO 看看有没有普通分享这个场景 */
  async doShare(isInvite = false) {
    console.log("ssss")
    const { shareInfo } = store.frontVariable;
    if (CFG.channel == CHANNEL.HXBANK) { // 华夏银行APP分享
      const _url = await this.getShareLink(isInvite);
      // 分享方法
      console.log("sss")
      hxbankShare({
        ...shareInfo,
        url: _url
      })
    } else if (CFG.channel == CHANNEL.HXLC) { // 华夏理财APP分享
      // 无分享方法
      // modalStore.closePop();
      // modalStore.pushPop('Sharepop');
    } else { // 其他三方APP
      // modalStore.closePop();
      // modalStore.pushPop('Sharepop');
    }
  },

  /** 助力 */
  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;

