import mobx from "mobx";
import { getProjectId, sendWebNet, sendWebNetWithToken, WebNetName } from "../Utils/WebNet/WebNet";
import { showPanel, showToast } from "../../Module/UIFast";
import RankPrizePanel from "../Panels/RankPrizePanel";
import { getUrlParams } from "../Utils/WebNet/web/webTools";
import { assetManager, ImageAsset, SpriteFrame, Texture2D } from "cc";
import GetPrize from "db://assets/Scripts/Panels/GetPrize";
import gameStore from "./gameStore";
import html2canvas from "html2canvas";


const { makeAutoObservable } = mobx;


export interface IHomeInfo {
    actStartTime: number;
    actEndTime: number;
    currentTime: number;
    creditsNum: number;
    signPopFlag: boolean;
    continueSignDays: number;
    nickname: string;
    avatar: string;
    newGetSpId: string;
    newGetSpName: string;
    newGetSpImage: string;
    luckBenefitDesc: string;
    benefitDesc: string;
    firstEntryFlag: boolean;
    bagLightFlag: boolean;
    boolNotLogin: boolean;
    rankInfos: {
        index: number;
        nickname: string;
        avatar: string;
    }[];
    rankPopList: {
        rankType: 1 | 2;
        openDate: string;
        index: number;
        prizeId: string;
        prizeName: string;
        prizeImage: string;
        count: number;
    }[];
    bagPopVO: {
        bagNum: number;
        bagName: string;
        bagImg: number;
    };

    bagSwitch: boolean,
    avatarGuide: boolean,
}


class Store {

    frontVariable: { [key in string]: any } = {};

    async updateFrontVariable() {
        const { success, data } = await sendWebNet(WebNetName.getFrontVariable);
        if (!success) {
            return;
        }
        this.frontVariable = data;
    }

    homeInfo: IHomeInfo = {
        actStartTime: Date.now(),
        actEndTime: Date.now() - 1000,
        currentTime: Date.now(),
        creditsNum: 0,
        signPopFlag: false,
        continueSignDays: 0,
        nickname: "",
        avatar: "",
        newGetSpName: "",
        newGetSpImage: "",
        luckBenefitDesc: "",
        benefitDesc: "",
        firstEntryFlag: false,
        newGetSpId: null,
        rankInfos: [],
        rankPopList: [],
        bagPopVO: null,
        bagLightFlag: false,

        bagSwitch: false,
        avatarGuide: false,
        boolNotLogin: false,
    };

    async updateIndex() {
        const { success, data } = await sendWebNet(WebNetName.index);
        if (!success) {
            return;
        }

        this.homeInfo = data;
        if (data.bagPopVO) {
            showPanel(GetPrize, [{
                prizeName: data.bagPopVO.bagName,
                prizeImg: data.bagPopVO.bagImg,
                sendCount: data.bagPopVO.bagNum
            }]);
        }
    }

    ruleInfo: string = "";

    async updateRule() {
        const { success, data } = await sendWebNet(WebNetName.projectRule);
        if (!success) {
            return;
        }
        this.ruleInfo = data;
    }

    medalPop: any[] = [];

    setRankPop() {
        this.medalPop = this.homeInfo.rankPopList;
        this.judgeMedalPop();
    }

    judgeMedalPop() {
        if (this.medalPop.length > 0) {
            const item = this.medalPop.pop();

            console.log("准备跳转了", item);
            showPanel(RankPrizePanel, item);

        }
    }

    // 判断是否登录状态
    judgeLogin = () => {
        const { boolNotLogin } = store.homeInfo || {};
        if (boolNotLogin) {
            this.doLogin()
            return false
        }
        return true
    }
    doLogin() {
        // 赵一鸣：
        // path: package/pages/login/index
        // appid: wxf7010270499c9a16

        // 零食很忙：
        // path: package/pages/login/index
        // appid:wxb7d4a6d67d4ca5e1
        const type = getUrlParams("type") || "1";
        const loginId = getProjectId() == "p8ec64a64"
            ? "Did1NTg5NTE"
            : "Did1NTkzNDM";

        const centerUrl = `https://98112-activity.dexfu.cn/customShare/share?id=${loginId}&type=${type}`;

        const url = "/package/pages/login/index?callback=" + encodeURIComponent(centerUrl);
        // @ts-ignore
        wx.miniProgram.navigateTo({ url: url });
    }

    checkActTime = (isAllow = false) => {

        const { actStartTime, actEndTime, currentTime } = this.homeInfo || {};

        if (actStartTime > currentTime) {
            console.log("活动未开始");

            showToast("活动未开始");
            return false;
        }
        if (actEndTime < currentTime && !isAllow) {
            console.log("活动未开始");

            showToast("活动已结束");
            return false;
        }
        console.log("checkActTime");

        return true;
    };
    // // 道具页接口
    // propPageInfo: {}
    //
    // async getPropPageInfo(credits: string) {
    //     const param = {
    //         credits,
    //     };
    //     const {success, data} = await sendWebNet(WebNetName.propPag,param);
    //     if (!success) {
    //         return;
    //     }
    //     this.propPageInfo = data
    //
    // }

    enter: boolean = false;

    async doAssist() {
        const inviteCode = getUrlParams("inviteCode");
        if (!inviteCode) return;

        this.enter = true;

        const { success, data } = await sendWebNetWithToken(WebNetName.doAssist, { inviteCode });
        if (!success) return;

        console.log(this.enter);

        showToast(data.extra);
    }


    async getTaskInfo() {
        return await sendWebNet(WebNetName.taskList, {
            taskToken: getUrlParams("taskToken") || "123456",
        });
    }

    bagInfo: any = {};

    async getBagInfo() {
        const { success, data } = await sendWebNet(WebNetName.bagPag);

        if (!success) return false;

        this.bagInfo = data;

        return success;
    }

    exchangeInfo = {
        remainCredits: 0,
        exchangeShopList: [],
    };

    async getExchangeInfo() {
        const { success, data } = await sendWebNet(WebNetName.propPag);
        if (!success) {
            return;
        }

        this.exchangeInfo = data;
    }

    async upLoadImg(b64) {
        const {success, data} = await sendWebNet(
            WebNetName.uploadImg,
            {img64: b64},
            {
              isGet: false,
            //   headers: {"Content-Type": "application/json"},
              hideMsg: true
            }
          );
          if (success) {
            await sendWebNet(WebNetName.transfer, {detail: data, startId: gameStore.startInfo?.startId}, {hideMsg: true});
          }
          return
        let shortDoc = document.getElementById('Cocos3dGameContainer');
        await html2canvas(shortDoc, {
            useCORS: true,
            allowTaint: true,
            scale: 1,
            // backgroundColor: "rgba(0, 0, 0, 0)",
          }).then(async canvas => {
            const imgData = canvas.toDataURL('image/png');
            console.info("imgData",imgData)
            const {success,data} = await sendWebNet(WebNetName.uploadImg, {img64:imgData}, {
               headers:{ 'Content-Type': 'application/json'},
               hideMsg:true,
            }
);
            if(success){
                 await sendWebNet(WebNetName.transfer, {detail:data,startId:gameStore.startInfo?.startId},{hideMsg:true});
            }
          });

    }

}


const store: Store = makeAutoObservable(new Store());

export default store;
