import {
    _decorator,
    assetManager,
    Component,
    game,
    lerp,
    Node,
    Prefab,
    profiler,
    ProgressBar,
    resources,
    Sprite,
    macro,
} 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 store from "../store/store";
import { appRequest, disableGestureReturn, resetBackCookie } from "../AppTool";
import { sendWebNet } from "../Scripts/Utils/WebNet/WebNet";

const {ccclass, property} = _decorator;

const _FPS = 61;

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

    @property(Prefab)
    uiPrefab: Prefab;

    @property(Node)
    progEffect: Node;

    @property(ProgressBar)
    progressBar: ProgressBar;

    interval = null;

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

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

        UIMgr.ins.setup(this.uiPrefab);

        store.updateFrontVariable();

        // disableGestureReturn();

        this.interval = setInterval(() => {
            this.keepLive();
        }, 1000 * 60 * 5);

        // this.tempSaveCookie();
        // setInterval(() => {
        //     this.tempSaveCookie();
        // }, 5 * 1000);

    }

    tempCookie = null;

    tempSaveCookie() {
        sendWebNet("/autoLogin/tempSaveCookie", null, null, true)
            .then((res) => {
                if (!res?.data) {
                    resetBackCookie(this.tempCookie);
                    return;
                }
                this.tempCookie = res.data;
            });
    }

    onDestroy() {
        clearInterval(this.interval);
    }

    keepLive = () => {
        appRequest('/activityCommonService/duiBaKeepAlive', {
            method: 'POST',
        }).then(res => {
            console.log('keepLive', res);
        });
    };

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

        await changeScene(HomeScene);

    }

    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);
                    const x = lerp(-300, 300, pro);
                    this.progEffect.setPosition(x, 12);
                    // this.progressTxt.string = `正在加载中   ${(pro * 100).toFixed(0)}%`;
                },
                async (error) => {
                    if (error) {
                        console.error(error);
                        showToast("活动太火爆啦，请稍后再试~");
                    }
                    // onComplete();
                    resolve();
                }
            );
        });

    }

}


