<style src="../../styles/main.css"></style>
<template>
    <div>
        <div v-if="!isLoaded" ref="loading_a1" id="loading_a1"></div>
        <div v-if="!isLoaded" ref="loading" id="loading">正在进入系统中...</div>
        <div v-if="reconnect" class="reconnect">网络连接中断，正在进行重连...</div>
        <div v-if="loadProgressValue>0 && loadProgressValue<100" class="reconnect">
            <div class="loadText">模型加载中...</div>
            <div class="loadProgress" :style="{width:loadProgressValue+'%'}"></div>
        </div>
        <video ref="EngineContent" autoplay muted style="width: 1920px;height:1080px;">浏览器不支持</video>
        <Fac v-if="currentTargetType=='FAC'" user-role="index" :fac-model-load-state="facModelLoadState"  @markerLClick="facMarkerLClick" @OpenIframeWin="OpenIframeWin"></Fac>
        <In02 ref="In02Ele" v-if="currentTargetType=='IN02'" user-role="index" :click-event="In02ClickEvent" :in02-model-load-state="in02modelloadstate" :user-timeout="AutoPlayer"  @OpenIframeWin="OpenIframeWin"></In02>
        <In03 ref="In03Ele" v-if="currentTargetType=='IN03'" user-role="index" :click-event="In03ClickEvent" :in03-model-load-state="in03modelloadstate" :user-timeout="AutoPlayer"  @OpenIframeWin="OpenIframeWin"></In03>
        <!--
        <In04 v-if="currentTargetType=='IN04'" :click-event="In04ClickEvent" :in04-model-load-state="in04modelloadstate" :user-timeout="AutoPlayer"></In04>
        <In05 v-if="currentTargetType=='IN05'" :click-event="In05ClickEvent" :in05-model-load-state="in05modelloadstate" :user-timeout="AutoPlayer"></In05>
        -->
        <Bottom @loadNavModel="loadNavModel" user-role="index" :fac-model-load-state="isLoaded"/>
    </div>
    <div id="iframeWin" v-if="isShowIframeWin" :class="iframeWinData.class">
        <div class="title"><span class="text" v-html="iframeWinData.title"></span><img src="../../assets/image/Close.png" style="margin: 7px 17px;float: right;cursor: pointer;" @click="CloseIframeWin"></div>
        <div class="content"><iframe id="ifrm" :src="iframeWinData.src" class=""></iframe></div>
    </div>
</template>
<script>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import lottie from 'lottie-web';
import api from "@/api/system";
import Bottom from '../components/Bottom.vue';
import Fac from '../components/Fac.vue';
import In02 from '../components/In02.vue';
import In03 from '../components/In03.vue';
//import In04 from '../components/In04.vue';
//import In05 from '../components/In05.vue';
export default {
    components:{
        Bottom,
        Fac,
        In02,
        In03,
        //In04,
        //In05,
    },
    setup() {
        const loading_a1=ref(null);
        const loadProgressValue=ref(0);//模型加载初始进度
        const EngineContent=ref(null);
        const reconnect=ref(false);
        const isShowIframeWin = ref(false);
        const iframeWinData = ref({});
        const autoplayer_btn =ref(null);
        let In02ClickEvent = ref(null);
        let In04ClickEvent = ref(null);
        let In03ClickEvent = ref(null);
        let In05ClickEvent = ref(null);
        const In03Ele = ref(null);
        let isLoaded = ref(false);
        let isClearEle = ref(false);
        window.player = null;
        let playerNative = ref(null);
        let playerConnState=false;
        window.modelLoadState = {};
        const facModelLoadState=ref(false);
        const in02modelloadstate=ref(false);
        const in03modelloadstate=ref(false);
        const in04modelloadstate=ref(false);
        const in05modelloadstate=ref(false);
        let currentTargetType = ref('');
        let reconntimer=null;
        let MarkerMapFac={};
        let AutoPlayer=ref(false);
        let markerLClickObj=null;

        let  inPoints={
            "IN02":{"Text001_002":1,"x1":-28.07801,"y1":37.95126,"x2":-23.32394,"y2":31.16921},
            "IN03":{"Text001_006":1,"x1":46.86921,"y1":24.87041,"x2":51.91054,"y2":17.87417},
            //"IN04":{"Text001_004":1,"x1":-38.46275,"y1":35.65208,"x2":-44.94122,"y2":28.22142},
            //"IN05":{"Text001_005":1,"x1":102.43050,"y1":38.96248,"x2":108.99212,"y2":30.86295}
        };
        function CloseIframeWin(){
            isShowIframeWin.value=false;
            iframeWinData.value={};
        }
        function OpenIframeWin(info){
            iframeWinData.value = {
                class:info.class==null? 'newwin bpbWin':info.class,
                src:info.src,
                title:info.title
            };
            isShowIframeWin.value=true;
        }
        function ShowLoading(){
            lottie.loadAnimation({
                // 选取一个容器，用于渲染动画
                container: loading_a1.value,
                // 定义JSON文件路径
                animationData: lottiedata,
                // 是否循环播放
                loop: true,
                // 渲染的格式svg/canvas/html，svg性能更优，兼容性更好
                renderer: "svg",
            });
        }
        function loadNavModel(item){
            //console.log(item)
            switch(item.code){
                case "FAC":
                    loadFacModel(playerNative.value);
                    break;
                case "IN02":
                    loadIn02Model(playerNative.value);
                    break;
                case "IN03":
                    loadIn03Model(playerNative.value);
                    break;
            }
        }
        function facMarkerLClick(obj){
            //接收Fac组件中点击标记时的数据
            markerLClickObj = obj;
        }
        function handleBodyClick(){
            isClearEle.value=true;
        }
        async function moveFacAnything(name,event){
            console.log(name, event)
            if(event.object==null) return;
            var se = event.object;
            player.Native.ModelTree.setSelectItem(event.object.item);
            var calcInfo = await PlayerUtils.call(player.Native.ModelTree.calcItemAabb, se.item);
            console.log(calcInfo)
            player.Native.Camera.moveToAabbWithDistance([calcInfo.localAabb.min, calcInfo.localAabb.max], 0.5, 0, 0.9);
        }
        function senceInit(){
            player = new RemotePlayer({
                video: EngineContent.value, //绑定视频标签或图片标签
                signalServer: process.env.VUE_APP_3D, //云渲染服务器，发布时需要改为实际地址
                engineId: "" + Date.now(), // 引擎会话id，如果已存在则连接，没有则创建，会话在断开连接后超时自动关闭
                rtcIni: 'rtc.ini', // 可指定webrtc配置文件，默认为rtc.ini，相对目录为集群节点的enginePath目录
                autoResize: true, // 引擎是否跟跟随标签尺寸
                limtMoveCPS: 10, // 限制每秒鼠标移动的消息个数
                userTimeout: 1000 * 60 * 5, // 用户操作超时设置，毫秒
                exitTimeout: 1000 * 60 * 60 * 999999, // 用户超时后多久断开会话
                maxTimeout: 10000, // 会话超时时间，允许掉线后引擎保存多久，在该时间内可重新连接到会话，否则会创建新的会话
                debug: false // 是否启用调试，开启后调用Native接口时会使用console.log进行记录
            });
            //2.[可选]监听连接成功消息
            player.on("Connected", () => {
                console.log("Has connected to engine")
                playerConnState = true
                reconnect.value = false;
                isLoaded.value = true;
                if (reconntimer != null) clearTimeout(reconntimer);
            });

            //3.[可选]监听连接失败消息
            player.on("Disconnected", (e) => {
                console.log("Disconnected from engine", e);
                reconnect.value = true;
                isClearEle.value=true;
                playerConnState = false
                facModelLoadState.value=false;
                in02modelloadstate.value=false;
                in03modelloadstate.value=false;
                window.IN03Markers=null;
                AutoPlayer.value=false;
                EngineContent.value.pause();
                if(e=='signal websocket error'){
                    //服务器网络不通
                }
                modelLoadState={};
                //currentTargetType.value='';
                //4.[推荐]尝试重新连接
                reconntimer = setTimeout(function () {
                    console.log('尝试自动重连：', playerConnState)
                    if (playerConnState) return
                    if(player==null ){
                        window.location.reload();
                        return;
                    }
                    player.reconnect();
                }, 4000);
                //启动自动连接状态检测
                setTimeout(() => {
                    //5秒还未连接成功时直接刷新页面
                    if(!playerConnState){
                        console.log('自动连接超时，自动页面刷新')
                        window.location.reload();
                    }
                }, 9000);
            });

            //5. [推荐] 响应UserTimeOut消息，引擎接收用户鼠标触屏事件超时发出通知
            player.on("UserTimeOut", () => {
                console.info('用户长时间没有操作三维视图，可调用player.resetTimer()取消退出');
                //AutoPlayer.value = true;  //暂时取消自动漫游功能
            });
            player.on('TimeOutExit',()=>{
                console.info('长时间没有操作，已断开连接');
            });
            player.on('ConnectedFailed',(evt)=>{
                console.info('服务器连接失败');
            })
            //6.监听远程过程调用加载完成消息
            player.on("NativeLoad", async (Native) => {
                modelLoadState={};
                EngineContent.value.play();
                playerNative.value =Native;                
                //模型加载完成监听处理
                Native.Model.EventProgressEnd.connect(function(step,id,name){
                    modelLoadState[name]=true; 
                    if(window.CurrentTargetType!=name){
                        return
                    }
                    //当前模型加载完成，添加进度动画效果，否则会是一闪而过的效果
                    loadProgressValue.value=99;
                    setTimeout(() => {
                        //动画效果为固定的0.5s，多0.5s才让进度消失
                        loadProgressValue.value=100;
                    }, 1000);
                    if("FAC"==name){
                        facModelLoadState.value=true;//全厂模型加载完成
                        player.Native.Model.setModelVisible('IN02',false);
                        player.Native.Model.setModelVisible('IN03',false);
                        player.Native.Model.setModelVisible(name,window.CurrentTargetType==name?true:false);                                               
                        player.Native.CameraAnimation.clearKeyFrame();
                    }else if("IN02"==name){
                        in02modelloadstate.value=true;
                        player.Native.Model.setModelVisible('FAC',false);
                        player.Native.Model.setModelVisible('IN03',false);
                        player.Native.Model.setModelVisible(name,window.CurrentTargetType==name?true:false);                        
                    }else if("IN03"==name){
                        in03modelloadstate.value=true;
                        player.Native.Model.setModelVisible('FAC',false);
                        player.Native.Model.setModelVisible('IN02',false);
                        player.Native.Model.setModelVisible(name,window.CurrentTargetType==name?true:false);
                    }              
                });
                //模型加载中监听处理
                Native.Model.EventProgress.connect(function(v,hander,name){   
                    //当进度大于0.99时，交由EventProgressEnd监听处理            
                    if(window.CurrentTargetType!=name || v>0.99 ||v<1) return;
                    loadProgressValue.value = (v*100).toFixed(0);
                });
                // // 选择Pickup工具
                player.Native.Tools.setCurrentTool("system.Pickup");
                player.Native.Settings.set('skybox',"string","null");
                player.Native.Settings.set('bg.image.file',"string",'data/sky/bg.png');
                //不显示提示框
                player.Native.Settings.set("tips.enabled", "bool", false);
                // //点选高亮显示
                player.Native.Settings.set("pickUp.highlight", "bool", false);
                //点选包围盒
                player.Native.Settings.set("show.select.box", "bool", false);
                player.Native.Settings.set("skybox.select", "string", "blue");
                //点选背景虚化
                player.Native.Settings.set("color.pickup.bkAlpha", "float", 0.8);
                // 选中展示节点
                // sam0023 = await player.Native.ModelTree.findItemByName("CYLINDER 3 of EQUIPMENT /C1101", 0, true, 3);
                player.Native.Settings.set('ambientIndenty', 'float', 0.39);//初始化环境光补偿
                player.Native.Settings.set('diffuseIntensity', 'float', 0.8);//初始化光线强度
                player.Native.Settings.set('specularIntensity', 'float', 0.64);//初始化高光强度
                player.Native.Settings.set('searchLightIntensity', 'float', 0.5);//初始化探照灯强度
                // 点击事件一般仅用于浏览工具，在点选工具下无效
                Native.Tools.setCurrentTool("system.Browse");
                console.log('window.CurrentTargetType:',window.CurrentTargetType)
                switch(window.CurrentTargetType){
                    case "IN02":
                        loadIn02Model(Native);
                        break;
                    case "IN03":
                        loadIn03Model(Native);
                        break;
                    default:
                        loadFacModel(Native);
                        break;
                }
                Native.ModelTree.EventBrowseLClick.connect((event) => {
                    if(event.object==null) return;

                    if(currentTargetType.value=="FAC"){
                        //必须延迟处理模型的点击事件，以判断是否是点击的标记，暂时没有找到更好的方法处理标记点击
                        setTimeout(function(event){
                            if(markerLClickObj!=null){
                                //标记被点击时，不执行模型点击逻辑
                                markerLClickObj = null;
                                return;
                            }
                            markerLClickObj = null;
                            var inTxt = "";
                            if(inPoints[event.object.name]!=null){
                                //进入楼层内部
                                inTxt = txt;
                            }else {
                                for (var txt in inPoints) {
                                    var item = inPoints[txt];
                                    if(event.pos[1]>= item["x1"] && event.pos[2]<= item["y1"] &&event.pos[1]<= item["x2"] && event.pos[2]>= item["y2"]){
                                        inTxt = txt;
                                        break;
                                    }
                                }
                            }
                            if(inTxt!=""){
                                switch(inTxt){
                                    case "IN02":
                                        loadIn02Model(Native);
                                        break;
                                    case "IN03":
                                        loadIn03Model(Native);
                                        break;
                                    default:
                                        break;
                                }
                                currentTargetType.value=inTxt;
                            }else{
                               // moveFacAnything("LClick", event);
                            }
                        },200,event);
                        return;
                    }
                    if(currentTargetType.value=="IN02"){
                        In02ClickEvent.value = event;
                        //In02Ele.updateInfo("LClick", event);
                    }
                    if(currentTargetType.value=="IN03") {
                        //move03Anything("LClick", event);
                        In03ClickEvent.value = event;
                    }
                });
                Native.ModelTree.EventBrowseRClick.connect((event) => {
                    if(markerLClickObj!=null) return;
                    //updateInfo("RClick", event)
                });
            })
        }
        function getBottomBtnImg(imgname, type){
            if(currentTargetType.value==type) return require('@/assets/image/'+imgname+'_active.png');
            else return require('@/assets/image/'+imgname+'.png');
        }
        async function loadFacModel(Native){
            if(currentTargetType.value=="FAC") return;
            currentTargetType.value="FAC";
            await player.Native.Settings.set('ambientIndenty', 'float', 0.39);//初始化环境光补偿
            await player.Native.Settings.set('diffuseIntensity', 'float', 1.2);//初始化光线强度
            await player.Native.Settings.set('specularIntensity', 'float', 0.64);//初始化高光强度
            if(modelLoadState[currentTargetType.value]==null){   
                loadProgressValue.value = 1;   
                modelLoadState['FAC']=false;          
                var cf = "data://models/T_ALL.pr";
                //var errStr = await PlayerUtils.call(Native.Model.loadModel, currentTargetType.value, cf);
                //异步加载模型，加载进度通过EventProgress及EventProgressEnd进行监听
                PlayerUtils.call(Native.Model.loadModelWithParam, currentTargetType.value, cf, {
                  "loadThreshold": 10000,
                  "unloadThreshold": 100000,
                  "dynamicLoadEnabled ": true
                });
                if(modelLoadState['IN02']==null){
                    modelLoadState['IN02']=false; 
                    var cf = "data://models/T_02.pr";
                    PlayerUtils.call(Native.Model.loadModelWithParam, 'IN02', cf, {
                      "loadThreshold": 10000,
                      "unloadThreshold": 100000,
                      "dynamicLoadEnabled ": true
                    });
                }
                if(modelLoadState['IN03']==null){
                    modelLoadState['IN03']=false;
                    var cf = "data://models/T_03.pr";
                    PlayerUtils.call(Native.Model.loadModelWithParam, 'IN03', cf, {
                      "loadThreshold": 10000,
                      "unloadThreshold": 100000,
                      "dynamicLoadEnabled ": true
                    });
                }
                return;
            }  
            await player.Native.Model.setModelVisible("IN02",false);
            await player.Native.Model.setModelVisible("IN03",false);
            await player.Native.Model.setModelVisible(currentTargetType.value,true); 
            if(modelLoadState[currentTargetType.value]==true) facModelLoadState.value=true;
        }
        //印花
        async function loadIn03Model(Native){
            player.Native.Settings.set('ambientIndenty', 'float', 1);//初始化环境光补偿
            player.Native.Settings.set('diffuseIntensity', 'float', 2.5);//初始化光线强度
            player.Native.Settings.set('specularIntensity', 'float', 0.6);//初始化高光强度
            if(currentTargetType.value=="IN03") return;
            currentTargetType.value="IN03";
            if(modelLoadState[currentTargetType.value]==null){
                loadProgressValue.value = 1;
                modelLoadState[currentTargetType.value]=false;
                var cf = "data://models/T_03.pr";
                //异步加载模型，加载进度通过EventProgress及EventProgressEnd进行监听
                PlayerUtils.call(Native.Model.loadModelWithParam, currentTargetType.value, cf, {
                  "loadThreshold": 10000,
                  "unloadThreshold": 100000,
                  "dynamicLoadEnabled ": true
                });
                return;
            }
            await player.Native.Model.setModelVisible("FAC",false);
            await player.Native.Model.setModelVisible("IN02",false);
            await player.Native.Model.setModelVisible(currentTargetType.value,true);
            if(modelLoadState[currentTargetType.value]==true) in03modelloadstate.value=true;
        }
        //经编
        async function loadIn02Model(Native){
            player.Native.Settings.set('ambientIndenty', 'float', 0.39);//初始化环境光补偿
            player.Native.Settings.set('diffuseIntensity', 'float', 0.8);//初始化光线强度
            player.Native.Settings.set('specularIntensity', 'float', 0.64);//初始化高光强度
            if(currentTargetType.value=="IN02") return;
            currentTargetType.value="IN02";
            if(modelLoadState[currentTargetType.value]==null){
                loadProgressValue.value = 1;
                modelLoadState[currentTargetType.value]=false;
                var cf = "data://models/T_02.pr";
                //异步加载模型，加载进度通过EventProgress及EventProgressEnd进行监听
                PlayerUtils.call(Native.Model.loadModelWithParam, 'IN02', cf, {
                  "loadThreshold": 10000,
                  "unloadThreshold": 100000,
                  "dynamicLoadEnabled ": true
                }); 
                return;
            }
            await player.Native.Model.setModelVisible("FAC",false);
            await player.Native.Model.setModelVisible("IN03",false);
            await player.Native.Model.setModelVisible(currentTargetType.value,true);
            if(modelLoadState[currentTargetType.value]==true) in02modelloadstate.value=true;
        }
        onMounted(()=>{
            window.addEventListener("click", handleBodyClick);
            ShowLoading();
            senceInit();
        });
        onBeforeUnmount(()=>{
            EngineContent.value.pause();
            player.Native.Model.unloadModel('FAC');
            player.Native.Model.unloadModel('IN02');
            player.Native.Model.unloadModel('IN03');

        })
        return {
            player,
            isShowIframeWin,
            iframeWinData,
            facMarkerLClick,
            CloseIframeWin,
            OpenIframeWin,
            isLoaded,
            currentTargetType,
            loading_a1,
            loadProgressValue,
            reconnect,
            EngineContent,
            AutoPlayer,
            In02ClickEvent,
            In03ClickEvent,
            In04ClickEvent,
            In05ClickEvent,
            facModelLoadState,
            in02modelloadstate,
            in03modelloadstate,
            in04modelloadstate,
            in05modelloadstate,
            ShowLoading,
            handleBodyClick,
            senceInit,
            getBottomBtnImg,
            markerLClickObj,
            loadNavModel,
        }
    },
}
</script>
<style scoped>
</style>
