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';
import { copyToClipboard } from '@spark/utils';


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;
    if (CFG.channel != CHANNEL.HXBANK) {
      copyToClipboard(this.inviteUrl);
      setTimeout(() => {
        copyToClipboard(this.inviteUrl);
      }, 200)
      Toast.show("邀请链接已复制，快去微信打开吧")
    }
    return url;
  },

  /** 分享 TODO 看看有没有普通分享这个场景 */
  async doShare(isInvite = false) {
    const { shareInfo } = store.frontVariable;
    if (CFG.channel == CHANNEL.HXBANK) { // 华夏银行APP分享

      try {
        // 分享方法
        hxbankShare({
          ...shareInfo,
          url: _url
        })
      } catch (err) {
        console.log('分享方法', err)
      }
    } else {
      const _url = await this.getShareLink(isInvite);
    }
  },

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

