import {
    _decorator,
    assetManager,
    game,
    Component,
    Label,
    Node,
    Prefab,
    profiler,
    ProgressBar,
    resources,
    input, Input,
} from 'cc';
import { PREVIEW } from 'cc/env';
import { UIMgr } from "../Module/UIMgr";
import { changeScene, showToast } from "db://assets/Module/UIFast";
import { HomeScene } from "db://assets/Scripts/Scenes/HomeScene";
import { sendWebNet, WebNetName } from "../Scripts/Utils/WebNet/WebNet";
import { getUrlParams } from "../Scripts/Utils/WebNet/web/webTools";
import store from "../Scripts/store/store";
import { AudioMgr } from "../core_tgx/base/AudioMgr";
import { MusicBtn } from "../Component/MusicBtn/MusicBtn";
import { gameId } from "../Scripts/AppTool";

const {ccclass, property} = _decorator;

const _FPS = 61;

@ccclass('Start')
export class Start extends Component {

    @property(Prefab)
    uiPrefab: Prefab;

    @property(Node)
    progressEffect: Node;

    @property(ProgressBar)
    progressBar: ProgressBar;

    @property(Label)
    progressTxt: Label = null;

    onLoad() {
        // game.frameRate = _FPS;

        // 预览调试时，显示性能统计面板
        if (PREVIEW) {
            // profiler.showStats();
        }
        // profiler.hideStats();

        UIMgr.ins.setup(this.uiPrefab);

        document.body.style.visibility = "visible";

        // MusicBtn.open = false;

    }

    onDestroy() {
    }

    async getAuthCode() {
        return new Promise((resolve) => {
            window["my"].onMessage = (e: any = {}) => {
                const {authCode, type} = e;
                if (type == "getAuthCode") {
                    resolve(authCode);
                }
            }

            try {
                window["my"].postMessage({type: "getAuthCode"});
            } catch (e) {
                console.error(e);
            }
        });
    }

    async start() {

        const dbTest = getUrlParams("dbTest") as string;

        if (dbTest) {

            const {appId, uid, fullName} = JSON.parse(dbTest);

            const {success, data} = await sendWebNet(WebNetName.dbTestLogin, {
                appId,
                uid,
                fullName,
            });

            if (!success) {
                showToast("Authorization failure");
                return;
            }

        } else {
            await store.getMiniQuery();

            const authCode = await this.getAuthCode();

            console.log("authCode", authCode);

            if (!authCode) {
                showToast("Authorization failure");
                return;
            }

            const {success, data} = await sendWebNet(WebNetName.autologin, {
                authCode: authCode,
                appId: gameId,
            });

            if (!success) {
                showToast("Authorization failure");
                return;
            }
        }

        await this.preload([
            {
                path: "common",
                type: "bundle",
            },
            {
                path: "HomeScene",
                type: "bundle",
            },
            {
                path: "MainGame",
                type: "bundle"
            },
        ]);

        await changeScene(HomeScene);

        AudioMgr.ins.play("audio/飞球背景音乐", {
            bundleName: "common",
        });

    }

    preload = (pkg) => {
        return new Promise<void>((resolve, reject) => {
            const pathArr = [];

            pkg.forEach((asset) => {
                if (typeof asset == "string") {
                    return pathArr.push(asset);
                }
                switch (asset.type) {
                    case "dir":
                        resources.getDirWithPath(asset.path).forEach((v) => pathArr.push(v.path));
                        break;
                    case "bundle":
                        assetManager.loadBundle(asset.path, (err, bundle) => {
                            if (err) {
                                console.error(err);
                            }
                        });
                        break;

                    default:
                        pathArr.push(asset.path);
                }
            });
            resources.load(
                pathArr,
                (finish: number, total: number, _) => {
                    const pro = finish / total;
                    if (pro < this.progressBar?.progress) {
                        return;
                    }
                    this.progressBar && (this.progressBar.progress = pro);
                    this.progressTxt.string = `${(pro * 100).toFixed(0)}%`;
                    const x = 640 * pro - 320;
                    this.progressEffect.setPosition(x, 0, 0);
                },
                async (error) => {
                    if (error) {
                        console.error(error);
                        showToast("活动太火爆啦，请稍后再试~");
                    }
                    // onComplete();
                    resolve();
                }
            );
        });

    }

}


