import mobx from "mobx";
import { getPxToken, getWebData, sendWebNet, sendWebNetWithToken, WebNetName } from "../Utils/WebNet/WebNet";
import { changeScene, showPanel, showToast } from "../../Module/UIFast";
import { MD5 } from "crypto-js";
import { md5 } from "../Utils/Md5";
import { runMainPage } from "../Scenes/runMainPage";
import { runGamePage } from "../Scenes/runGamePage";

const { makeAutoObservable } = mobx;


export interface IHomeInfo {
    extUserId: string, // 对外客户号
    timeStamp: number, // 当前时间 前端自定义
    actStartTime: number, // 活动开始时间(毫秒时间戳)
    actEndTime: number, // 活动结束时间(毫秒时间戳)
    lightEndTime: number, // 分会场点亮截止时间(毫秒时间戳)
    festivalStartTime: number, // 元宵抽奖开始时间，13位时间戳
    // 分会场-点亮记录，后端会排好序
    lightRecords: Array<{
        id: 1 | 2 | 3 | 4 | 5, //会场ID(1-开门大吉 2 - 金蛇送福 3 - 灵蛇献瑞 4 - 瑞蛇呈祥 5 - 祥蛇纳吉)
        lightStatus: number, //是否点亮，为true是
    }>,
    guideStatus: string, // 0-展示一级新手引导 1-展示新手引导红包雨icon 2-新手引导已完成
    remainDrawTimes: number, //剩余可抽大奖次数
    historyHasDraw: boolean, // 本次是否获得过抽奖次数，如果remainDrawTimes <0,且本字段为true则展示“已开奖”
    lightNum: number, // 点亮会场数量
    lightPop: boolean, // 是否弹出点亮弹窗，为true是
    // 剩余红包雨次数
    lessGameCount: number,
    // 红包雨提醒弹窗
    redRainPop: null | {
        type: number, //1-除夕弹窗 2-初五弹窗	
        awardTimes: number, //奖励抽奖次数
    },
    // 公告轮播弹窗
    noticeList: null | Array<{
        image: string, //图片	
        content: string, //内容
    }>,
    // 公告内容弹窗，不为空弹出
    noticePop: null | {
        image: string, //图片	
        content: string, //内容
    },
}


class Store {

    miniAppQuery: any = {};

    async getMiniQuery() {
        return new Promise<void>((resolve) => {
            window["my"].onMessage = (e: any = {}) => {
                const { query, type } = e;
                if (type == "getMiniAppQuery") {
                    this.miniAppQuery = query || {};
                    resolve();
                }
            }
            try {
                window["my"].postMessage({ type: "getMiniAppQuery" });
            } catch (e) {
                console.error(e);
            }
        });
    }


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

    async updateFrontVariable() {
        const { success, data } = await sendWebNet(WebNetName.getFrontVariable);
        if (!success) {
            return;
        }
        const resData = data || {};
        resData.shareInfo = resData.shareInfo ? JSON.parse(resData.shareInfo) : {};
        resData.shareInfoRunGame = resData.shareInfoRunGame ? JSON.parse(resData.shareInfoRunGame) : {};
        this.frontVariable = data;
    }

    homeInfo: IHomeInfo = {
        extUserId: '', // 对外客户号
        timeStamp: +new Date(), // 当前时间 前端自定义
        actStartTime: 0, // 活动开始时间(毫秒时间戳)
        actEndTime: 0, // 活动结束时间(毫秒时间戳)
        lightEndTime: 0, // 分会场点亮截止时间(毫秒时间戳)
        festivalStartTime: 0, // 元宵抽奖开始时间，13位时间戳
        lightRecords: [], // 分会场-点亮记录，后端会排好序
        guideStatus: "0", // 0-展示一级新手引导 1-展示新手引导红包雨icon 2-新手引导已完成
        remainDrawTimes: 0, //剩余可抽大奖次数
        historyHasDraw: false, // 本次是否获得过抽奖次数，如果remainDrawTimes <0,且本字段为true则展示“已开奖”
        lightNum: 0, // 点亮会场数量
        lightPop: false, // 是否弹出点亮弹窗，为true是
        lessGameCount: 0, // 剩余红包雨次数
        redRainPop: null, // 红包雨提醒弹窗
        noticeList: null, // 公告轮播弹窗
        noticePop: null, // 公告内容弹窗，不为空弹出
    }
    // 活动状态 1:未开始  2:已结束  3:进行中
    actStatus: 1 | 2 | 3 = 1;
    // 新点亮的建筑ID (1-开门大吉 2 - 金蛇送福 3 - 灵蛇献瑞 4 - 瑞蛇呈祥 5 - 祥蛇纳吉)
    newLighted: number = -1;

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

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

        if (timeStamp < actStartTime) {
            this.actStatus = 1
        } else if (timeStamp > actEndTime) {
            this.actStatus = 2
        } else {
            this.actStatus = 3
        }
    }

    // 校验时间状态
    checkTime(types = ["start", "end"]) {
        if (types.includes("start") && this.actStatus == 1) {
            showToast("活动未开始")
            return false
        }
        if (types.includes("end") && this.actStatus == 2) {
            showToast("活动已结束")
            return false
        }
        return true
    }

    ruleInfo: string = "";

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

    kmdjStartId: {};
    startsNet = true
    async startKMDJ() {
        console.log("this.startsNet", this.startsNet)
        if (!this.startsNet) {
            return
        }
        this.startsNet = false
        // getPxToken(async (msg, token) => {
        const { success, data } = await sendWebNetWithToken(WebNetName.kmdj_Start);
        if (!success) {
            this.startsNet = true
            changeScene(runMainPage)
        }
        this.kmdjStartId = data.startId;
        let kmdjIndex = getWebData(WebNetName.kmdj_Index).data
        if (kmdjIndex.boolGuideFinish) {
            changeScene(runGamePage)
            this.startsNet = true
        }
        this.startsNet = true
        // })
    }
    async submitKMDJ(score) {
        let sign;
        let time = new Date().getTime();
        sign = md5(`duiba2024${this.kmdjStartId}${score}${time}`)
        // await getPxToken(async (msg, token) => {
        const { success, data } = await sendWebNetWithToken(WebNetName.kmdj_Submit, { score, sign, startId: this.kmdjStartId, timeStamp: time }, { isGet: false, headers: { 'Content-Type': "application/x-www-form-urlencoded" } });
        if (success) {
            // 结算弹窗
            await sendWebNet(WebNetName.kmdj_Index);
            // showPanel(SnakeResultPanel, { ...data, score })
        } else {
            changeScene(runMainPage)
        }
        // })
    }
    lastPage = null;

}

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

export default store;