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

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(type: string) {
		await this.getInviteCode()
		if (!this.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")}`
		}
		// 游戏去炫耀 不同的分享信息
		if (type === SHARE_TYPE.FLAUNT) {
			shareParams.title = shareData.game_title
			shareParams.content = shareData.game_content
			shareParams.thumbnail = shareData.game_thumbnail
		}
		console.info('shareParams', shareParams);


		// app分享
		const { url, title, content, thumbnail } = shareParams;
		const ThirdApp = window['ThirdApp'];
		ThirdApp.wxShare(title, content, url, thumbnail, 'WX,PYQ', 'WebPage');
	}

	// 助力
	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=[^&]*`), ''));
	}
}

