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";

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,
        });

        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(title: string, desc: string, pic: string) {
        // @ts-ignore
        wx.miniProgram.postMessage({
            data: {
                title, // 标题
                desc, // 描述
                imgUrl: pic, // 图片
                url: this.inviteInfo.shareUrl // 链接
            }
        });
    }

}

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

export default shareStore;