import { Start, PathUrl, SpaceLevelManager, Object3d, Space3d, Object3dManager, Color3} from "./box3.js";
import { createDivTag, createNewButton } from "./divHelper.js";

/**应用入口 */
export class App {
    /**@type {App} */
    static Instance = null;
    constructor() {
        App.Instance = this;
        this.core = null;
        /**所有空间模型 Array
         * @type {Space3d[]}
         */
        this.spaces = Object3dManager.Space3dArray;
        /**所有普通模型 Array
         * @type {Object3d[]}
        */
        this.models = Object3dManager.Object3dArray;
        /**主摄像机 */
        this.camera = null;

        /*可在加载场景前设置资源根路径   */
        PathUrl.SetModelRootPath('../model/');
        PathUrl.SetImgRootPath('../img/');
        PathUrl.SetIconRootPath('../icon/');
        PathUrl.SetSkyboxRootPath('../skybox/');
        PathUrl.SetGifRootPath('../gif');

        this.ct = document.getElementById('app');
        this.core = new Start(this.ct);
        // 默认纹理
        this.core.fbTexture = PathUrl.imgPath + 'logo.png';

        // binding.init();
        this.camera = this.core.mainCamera;

        /**全局右键点击任务集合 */
        this.rightClickTasks = [];
        this.core.sceneInputer.mouseRightClickEvent = () => { this.rightClickTasks.forEach(f => { if (f) f(); }) }

        /**全局左键点击任务集合 */
        this.leftClickTasks = [];
        this.core.sceneInputer.mouseLeftClickEvent = () => { this.leftClickTasks.forEach(f => { if (f) f(); }) }

        //加载场景文件
        this.core.loader.loadScene('../scene/scene.json');
        //注册加载开始事件
        this.core.loader.onStart = () => { this.onStartLoad() };
        //注册加载事件
        this.core.loader.onLoad = () => { this.onLoading() };
        //注册加载结束事件
        this.core.loader.onEnd = () => { this.onEndLoad() };
        // this.core.loader.importScene(JSON.parse(scene));

        this.core.highlighter.color = Color3.FromHexString('#00ff33');

        window.camera = this.camera;
    }

    onStartLoad() {
        console.log('开始加载场景');
        console.log(window.location.href);
    }

    onLoading() {
        let cd = this.core.loader.progress;
        let progress = cd.toFixed(2) + "%";
        let text = document.getElementById("progress-text");
        text.innerText = "资源加载中... " + progress;
        if (cd >= 100) document.getElementById("progress-div").style.display = 'none';
    }

    async onEndLoad() {
        //限制仰角最大值
        this.camera.maxBetaAngle = 90;
        this.camera.camera.wheelDeltaPercentage = 0.05;
        this.camera.panningDistanceLimit = 3000;
        this.camera.maxRadius = 5000;
        this.initSpaces(this.spaces);
        this.initModels(this.models);

        //空间选择
        this.testSpaceMenu(this.spaces);

        console.log('已完成场景初始化');
    }

    /**空间初始化
     * 
     * @param {Space3d[]} spaces 
     */
    initSpaces(spaces) {
        setInterval(() => {
            this.core.defaultLights.updateShadowOnce();
        }, 100);

        spaces.forEach(s3d => {
            //添加描边功能
            s3d.enableMouseEnterOutline = true;
            //解锁鼠标点击事件
            s3d.disablePickable = false;
            //s3d.useMeshPicking = true;
            //添加单击事件
            s3d.addMouseLeftClickAction(() => {
                //定位
                s3d.flyToCustomView();
            })
            //添加转场事件
            s3d.onEnterEvent = () => {
                s3d.disablePickable = true;
            }
            s3d.onOutEvent = () => {
                s3d.disablePickable = false;
            }

            //注册双击事件，使镜头可定位到设备
            s3d.addMouseDoubleClickAction(() => {
                s3d.enterSpace();
                s3d.flyToCustomView();
            })

            //注册鼠标移入事件 移入后生成标签
            s3d.addMouseEnterAction(() => {
                let name = (!s3d.alias || s3d.alias === '') ? s3d.modelName : s3d.alias;
                s3d.addHtml(createDivTag('双击进入-'+name))
            });
            //注册鼠标移出事件 移出后删除标签
            s3d.addMouseExitAction(() => {
                s3d.removeHtml();
            });
        })

    }

    /**模型初始化
     * 
     * @param {模型数组} models 
     */
    initModels(models) {
        let tags = [];
        //获取 所有可交互的模型对象实例 注册事件
        for (let i = 0; i < models.length; i++) {
            /**@type {Object3d} */
            const o3d = models[i];
            if (!o3d.uid || o3d.uid === "none" || o3d.uid === "null" || o3d.uid === "") continue;
            //注册鼠标移入事件
            o3d.addMouseEnterAction(() => {
                let name = (!o3d.alias || o3d.alias === '') ? o3d.modelName : o3d.alias;
                o3d.addHtml(createDivTag(name));
            });

            //注册鼠标移出事件
            o3d.addMouseExitAction(() => {
                o3d.removeHtml();
            });

            //注册单击事件
            o3d.addMouseLeftClickAction(() => {
            })

            if(o3d.object3dType === 6){
                tags.push(o3d);
            }
        }

        window.mapTags = tags;
    }

    /**空间菜单 */
    testSpaceMenu(spaces) {
        let btn = createNewButton('地图复位', '10px', null, null, '50px');
        btn.onclick = () => {
            const current = SpaceLevelManager.CurrentSpace3d;
            if (current) {
                current.enterSpace();
                current.flyToCustomView();
            }
        }

    }
}
new App();