import mobx from "mobx";
import { assetManager, ImageAsset, SpriteFrame, Texture2D } from "cc";
import { getUrlParams } from "../Utils/WebNet/web/webTools";
import { sendWebNet, WebNetName } from "../Utils/WebNet/WebNet";
import store from "./store";
import { showShareGuide } from "../../Module/UIFast";

const { makeAutoObservable } = mobx;

class ShareStore {

    inviteInfo: {
        shareUrl: string,
        inviteCode: string,
        qrCode: string | SpriteFrame,
    } = {
        shareUrl: "",
        inviteCode: "",
        qrCode: "",
    };

    async genInviteInfo() {

        this.inviteInfo.shareUrl = `${location.origin}${location.pathname}`
            + `?appID=${getUrlParams("appID")}`;

        const { success: genCodeSuc, data: genCodeData } = await sendWebNet(WebNetName.getInviteCode);
        if (!genCodeSuc) {
            this.inviteInfo.inviteCode = genCodeData.inviteCode;
        }

        this.inviteInfo.shareUrl = store.frontVariable.loginUrl
            + `&inviteCode=${genCodeData.inviteCode}`;

        const path = "package/pages/common-activity/index" +
            "?webUrl=" + encodeURIComponent(this.inviteInfo.shareUrl);

        const { success: genQrSuc, data: genQrData } = await sendWebNet(WebNetName.genQrCode, {
            path: path,
            type: store.frontVariable.type || "1",
        });

        if (genQrSuc) {
            this.inviteInfo.qrCode = genQrData.result;
            assetManager.loadRemote<Texture2D>(genQrData.result, (err, imageAsset: ImageAsset) => {
                if (err) {
                    return;
                }
                const texture = new Texture2D();
                texture.image = imageAsset;
                const sp = new SpriteFrame();
                sp.texture = texture;
                this.inviteInfo.qrCode = sp;
            });
        }
    }

    doShare(showGuide = true) {

        if(showGuide){
            showShareGuide();
        }

        const { title, content, thumbnail } = store.frontVariable?.shareInfo || {};
        // @ts-ignore
        wx.miniProgram.postMessage({
            data: {
                title, // 标题
                desc: content, // 描述
                imgUrl: thumbnail, // 图片
                url: this.inviteInfo.shareUrl // 链接
            }
        });
    }

}

const shareStore: ShareStore = makeAutoObservable(new ShareStore());

export default shareStore;