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

        const type = getUrlParams("type") || "1";

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

        let path = null;

        // if (type == "1") {
        //     path = "package/pages/snake-fun-play/index";
        // } else {
        //     path = "package/pages/common-activity/index";
        // }

        // /package/pages/snake-fun-play/index

        path = `pages/snake-fun-play/index?inviteCode=${genCodeData.inviteCode}`;
        // package/pages/common-activity/index
        // const path = "package/pages/snake-fun-play/index" +
        //     "?webUrl=" + encodeURIComponent(this.inviteInfo.shareUrl);

        const { success: genQrSuc, data: genQrData } = await sendWebNet(WebNetName.genQrCode, {
            path: path,
            type: type,
            envVersion: "release"
        });

        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 || {};

        const param = {
            data: {
                title, // 标题
                desc: content, // 描述
                imgUrl: thumbnail, // 图片
                link: this.inviteInfo.shareUrl // 链接
            }
        }
        console.log("postMessage参数", param);

        // @ts-ignore
        wx.miniProgram.postMessage(param);
    }

}

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

export default shareStore;