var camCtrl;
var rayCtrl;
var uiCtrl;
var buildCtrl;

var _canvas;
var _engine;
var _scene;

var objCircle;

var mapCtrl;
var id;
var number = 0;
var allExhibits = null
var ignoreVisit

window.onload = function () {
    if (!ToolMgr.isMobel()) {
        let link = document.getElementById('linkcss');
        link.href = "http://exhibition.szwyg.org.cn/resources/exhibition_hall/res/css/style.css";
    }
    let params = ToolMgr.getParams(location.search);
    //params.id=1;
    if (params && params.id) {
        id = params.id;
        if (params.number) {
            number = Number(params.number)
        }
        ignoreVisit = params.ignore_visit
        initEnv(function () {
            _engine.runRenderLoop(function () {
                _scene.render();
                TWEEN.update();
                if (mapCtrl) {
                    mapCtrl.update(camCtrl.freeCamera);
                }
                // console.log(_engine.getFps());
            });
        });
    }
    else {
        alert("入参xx.html?id=1不存在");
    }
}
window.addEventListener("resize", function (ev) {
    if (_engine) {
        _engine.resize();
    }
});
function initEnv(callback) {
    _canvas = document.getElementById("renderCanvas");
    if (ToolMgr.isMobel()) {
        _engine = new BABYLON.Engine(_canvas, true);
    }
    else {
        _engine = new BABYLON.Engine(_canvas, true);
    }
    _scene = new BABYLON.Scene(_engine);
    _scene.environmentTexture = new BABYLON.HDRCubeTexture("http://exhibition.szwyg.org.cn/resources/exhibition_hall/res/hdr/1.hdr", _scene, 128, false, true, false, true);
    _scene.environmentIntensity = 1;

    _scene.gravity = new BABYLON.Vector3(0, -0.9, 0);
    _scene.collisionsEnabled = true;

    var light = new BABYLON.HemisphericLight("HemiLight", new BABYLON.Vector3(0, 1, 0), _scene);
    light.intensity = 1;
    // initCtrl();
    DataConfig.getAllData(id, (datas) => {
        if (datas.style == 1) {
            ModelConfig = ModernConfig
        } else if (datas.style == 2) {
            ModelConfig = AncientConfig
        }
        initCtrl();
        if (callback != null) {
            callback()
        }
        //加载模型
        buildCtrl.loadBuildModel("http://exhibition.szwyg.org.cn/resources/exhibition_hall/res/models/", ModelConfig.model, (value) => {
            uiCtrl.setProgress(value + "%")
        }, () => {
            //初始画
            for (let i = 0; i < datas.rooms.length; i++) {
                if (datas.rooms[i].number.toString() == "2") {
                    setHuaTex(datas.rooms[i].exhibits);
                    break;
                }
            }
            uiCtrl.loadFinish();
        });
        // _scene.executeWhenReady(function () {

        // });
        createCircle();
    });
}
function createCircle() {
    let mat = new BABYLON.StandardMaterial("circleMat", _scene);
    mat.emissiveTexture = new BABYLON.Texture("http://exhibition.szwyg.org.cn/resources/exhibition_hall/res/textures/circle.png", _scene);
    mat.opacityTexture = mat.emissiveTexture;
    mat.emissiveTexture.hasAlpha = true;
    mat.hasAlpha = true;
    mat.disableLighting = true;
    mat.environmentIntensity = 0;

    objCircle = BABYLON.Mesh.CreateGround("obj", 0.5, 0.5, 2, _scene);
    objCircle.position.y += 0.01;
    objCircle.material = mat;
}
function initCtrl() {
    //相机控制
    camCtrl = new CamCtrl(_canvas, _scene);
    camCtrl.awake();

    //射线检测
    rayCtrl = new RaycastCtrl(_canvas, _scene);
    rayCtrl.awake();
    //建筑
    buildCtrl = new BuildCtrl(_scene);

    uiCtrl = new UICtrl();

    mapCtrl = new MapCtrl();
    mapCtrl.awake();
    mapCtrl.addMapPos("11", ModelConfig.mapRange[0], ModelConfig.mapRange[1]);
    mapCtrl.attachMap("11", document.getElementById('map1'), document.getElementById('arrow1'), { bw: 0, bh: 0 }, { w: 0, h: 0 }, false);
}
function setHuaTex(exhibits) {
    allExhibits = exhibits
    for (let i = 0; i < allExhibits.length; i++) {
        let exhibit = allExhibits[i]
        let name = "PIC_";
        if (exhibit.number < 10) {
            name += "0" + exhibit.number;
        } else {
            name += exhibit.number;
        }
        let obj = _scene.getMeshByName(name);
        if (obj == null) {
            continue
        }
        // 驻足停留时间，默认值为3s
        obj.stayTime = exhibit.stay_time * 1000;
        
        // 设置展品宽度、高度
        obj.scaling.x = exhibit.width / 0.25
        obj.scaling.z = exhibit.height / 0.25

        // 设置展品左右偏移
        if (exhibit.offset_x >= 0) { // 向右移动
            obj.translate(new BABYLON.Vector3(1, 0, 0), exhibit.offset_x, BABYLON.Space.LOCAL);
        } else { // 向左移动
            obj.translate(new BABYLON.Vector3(-1, 0, 0), -exhibit.offset_x, BABYLON.Space.LOCAL);
        }
        // 设置展品上下偏移
        if (exhibit.offset_y >= 0) { // 向上移动
            obj.translate(new BABYLON.Vector3(0, 0, -1), exhibit.offset_y, BABYLON.Space.LOCAL);
        } else { // 向下移动
            obj.translate(new BABYLON.Vector3(0, 0, 1), -exhibit.offset_y, BABYLON.Space.LOCAL);
        }

        if (obj) {
            let tex = new BABYLON.Texture(exhibit.url + "?x-oss-process=image/resize,m_lfit,w_512,quality,q_80", _scene, false, true, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, () => {
                let mat = obj.material.clone();
                mat.albedoTexture = tex;
                mat.albedoColor.r = 1;
                mat.albedoColor.g = 1;
                mat.albedoColor.b = 1;
                tex.vScale = -1;
                obj.material = mat;
                // 一切就绪后，显示展品
                obj.setEnabled(true)
            });
        }
    }
    if (number > 0) {
        let name = "PIC_";
        if (number < 10) {
            name += "0" + number;
        } else {
            name += number;
        }
        let obj = _scene.getMeshByName(name);
        camCtrl.lookAt(obj)
    }
}
function showPicInfo(number) {
    console.log(number);
    if (allExhibits == null) {
        return
    }
    if (number.startsWith("0")) {
        number = number.substring(1)
    }
    let id = 0
    for (let i = 0; i < allExhibits.length; i++) {
        let exhibit = allExhibits[i]
        if (exhibit.number.toString() == number) {
            id = exhibit.id
        }
    }
    if (id == 0) {
        return
    }
    $("#detialWindow").attr("src", "/view/html/tourist/details.html?id=" + id);
    $("#showDetial").show();
}
