import { showToast } from "../Module/UIFast";
import { getUrlParam } from "./Utils/Utils";
import { getWebData, sendWebNetWithToken, WebNetName } from "./Utils/WebNet/WebNet";
import { SHARE_TYPE } from "./const";
import { appShare } from "../AppTool";
import store from "../store/store";

export default class ShareCenter {

    private static _ins: ShareCenter = null;

    public static get ins() {
        !ShareCenter._ins && (ShareCenter._ins = new ShareCenter());
        return ShareCenter._ins;
    }

    shareUrl = `/projectx/${location.pathname.split('/')[2]}/share.html?appID=${getUrlParam("appID")}`
    inviteCode = ''

    async getInviteCode() {
        if (this.inviteCode) return this.inviteCode
        const {success, data} = await sendWebNetWithToken(WebNetName.getInviteCode, null, null, null, false);
        if (success) {
            this.inviteCode = data?.inviteCode || ''
        }

        return '';
    }

    /**
     * 分享
     * @param type 分享类型
     */
    async doShare() {
        const inviteCode = await this.getInviteCode();
        if (inviteCode) return false
        const {shareInfo, appKey, shareOrigin} = getWebData(WebNetName.getFrontVariable).data
        let shareData = shareInfo ? JSON.parse(shareInfo) : {}
        let shareParams = {
            title: shareData.title,
            content: shareData.content,
            thumbnail: shareData.thumbnail,
            url: `${shareOrigin || location.origin}${this.shareUrl}&appKey=${appKey}&openBs=openbs&inviteCode=${this.inviteCode}&channel=${getUrlParam("channel")}`
        }

        // app分享

        await appShare(shareParams);
    }

    // 助力
    async doAssist() {
        const inviteCode = getUrlParam("inviteCode")
        if (!inviteCode) return false;
        const {success} = await sendWebNetWithToken(WebNetName.doAssist, {inviteCode}, null, null, false);
        if (success) {
            showToast(`已成功为您的好友助力\n您也得到1次挑战次数哦～`)
        }
        history.replaceState({}, '', location.href.replace(new RegExp(`[?&]inviteCode=[^&]*`), ''));
    }
}

