<template>
  <div class="dashboard">
    <header>
      <h1 class="title">光子科技大数据中心</h1>
      <div>
        <h2 class="title_right">时间: {{ updateTime }}</h2>
      </div>
    </header>
    <div class="model">
      <div id="loadingScreen">
        <el-progress type="circle" :percentage="loadedPercent" :width=220 status="warning">
          <template #default="{ percentage }">
            <div style="font-size: 30px; color: white; font-weight: bold">{{ percentage }}%</div>
            <div style="font-size: 18px; color: white; margin-top: 10px">工厂模型加载中</div>
          </template>
        </el-progress>
      </div>
      <canvas id="renderCanvas"></canvas>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import * as BABYLON from "babylonjs"
import * as BABYLON_GUI from "babylonjs-gui"
import * as BABYLON_GRID from "@/utils/gridMaterial"
import * as BABYLON_MATERIAL from "@/utils/babylonMaterial"
import 'babylonjs-loaders';
import 'animate.css';
export default {
  data() {
    return {
      query:{
        year_s:2023,
        month_s:8,
        type:'month_s',
        page:0
      },
      factoryData: {},
      sectionData: {},
      initialAlpha: -Math.PI / 1.2,
      initialBeta: Math.PI / 2.5,
      initialRadius: 15,
      initialTarget: null,
      scene: null,
      myui: null,
      is_mainviewpoint: false,
      resizeTimeout: null,
      engine: null,
      loadedPercent: 0,
     
      showKgcet: true,
      currentLightMesh: null,
      activeSection: 2,
      activeSectionName: '回转窑',
      updateTime: '2023-08-17 16:00:00',
      basicOption: {
        backgroundColor: '',
        xAxis: {
          data: ['一月', '二月', '三月', '四月', '五月', '六月'],
        },
        yAxis: { type: 'value'},
        series: [
          {
            name: '销量',
            type: 'bar',
            barwidth:10,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            data: []
          }
        ],
        grid: { // 让图表占满容器
          top: "10%",
          left: "12%",
          right: "0px",
          bottom: "15%"
        }
      },
      nowDay:1,
      nowMonth:1,
      nowYear:2023,
      year_start:0,
      end_time:'',
      start_time:'',
      xAxisData:[],
      arrMonth:[],
      chart1Option: {},
      chart2Option: {},
      chart3Option: {},
      chart4Option: {},
      chart5Option: {},
      chart6Option: {},
      seriesData1:[0,0,0,0,0,0],
      seriesData2:[0,0,0,0,0,0],
      seriesData3:[0,0,0,0,0,0],
      seriesData3_2:[0,0,0,0,0,0],
      seriesData4:[0,0,0,0,0,0],
      seriesData5:[0,0,0,0,0,0],
      seriesData6:[0,0,0,0,0,0],
      path:"ws://49.232.14.174:2226/ws/my/?token=",
		  ws:null,
      
    }
  },
  mounted() {
    var that = this;
    this.addListener();
    let myDate = new Date();
    let year = myDate.getFullYear();
    let month = myDate.getMonth()+1;
    let day = myDate.getDate();
    that.nowDay = day;
    that.nowMonth = that.query.month_s = month;
    that.nowYear = that.query.year_s = year;
    this.initDomStyle();
    setTimeout(function () {
        that.initFactory();
    }, 1000);
    let month1= month>9?month:'0'+month;
    let end_time  = year+'-'+month1+'-01 10:00:00';
    let year_s=year;
    if(month<6){
      year_s = year-1;
    }
    let arr = [],xAxisData = [];
    let monthItem = month;
    for (let i = 0; i < 6; i++) {
        arr.push(monthItem);
        if(monthItem === 1) {
          monthItem = 12; 
        } else {
          monthItem--; 
        }
    } 
    arr.reverse();
    for(let i=0;i<6;i++){
      let item = arr[i]+'日'
      xAxisData.push(item);
    }
    let month0= arr[0]>9?arr[0]:'0'+arr[0];
    let start_time = year_s+'-'+month0+'-01 10:00:00';
    that.arrMonth = arr;
    that.year_start = year_s;
    that.xAxisData = xAxisData;
    that.start_time = start_time;
    that.end_time = end_time;
  },
  beforeUnmount() {
    // 性能优化
    const canvas = document.getElementById('renderCanvas');
    if (canvas) {
      canvas.parentNode.removeChild(canvas);
    }
  },
  methods: {
    // 动态绑定Class
    bindClass(type){
      let classInfo = { socketDom: true, redColor: false, 
        orangeColor:false, yellowColor:false, blueColor:true }
      if(type==''){
              classInfo.redColor = true
      }
      return classInfo
    },
    compare(property) {
        return function (a, b) {
            return a[property] - b[property];
        }
    },
    addListener() {
      var that = this;
      window.addEventListener('resize', function () {
        // 如果已经有 resizeTimeout，清除它
        if (this.resizeTimeout) {
          clearTimeout(this.resizeTimeout);
        }
        // 设置一个新的 resizeTimeout，延迟调整样式
        this.resizeTimeout = setTimeout(function () {
          that.initDomStyle()
        }, 300); // 延迟 300 毫秒，可以根据需要调整
      });
    },
    initDomStyle() {
      // 获取窗口的总高度
      var windowHeight = window.innerHeight;
      var windowWidth = window.innerWidth;
      var dashboard = document.getElementsByClassName('dashboard')[0];
      var model = document.getElementsByClassName('model')[0];
      if (windowWidth > 960) {
        dashboard.style.overflow = 'hidden';
        model.style.position = 'absolute';
        model.style.height = (windowHeight - 3) + 'px';
        model.style.top = 0
      }else {
        dashboard.style.overflow = 'auto';
        var chartHeight = windowWidth * 0.6;
        model.style.position = 'relative';
        model.style.height = chartHeight;
      }
      if (this.engine != null) {
        this.engine.resize();
      }
     
    },
    resizeChart(name) {
      // 根据name resize chart
      var myChart = echarts.getInstanceByDom(document.getElementById(name));
      if (myChart != undefined) {
        // console.log(name + ' :resize')
        myChart.resize();
      }
    },
    setChart(name, option = null) {
      // 根据name 渲染数据, option需填写，否则option为模拟数据
      var myChart = echarts.getInstanceByDom(document.getElementById(name));
      if (myChart == undefined) {
        myChart = echarts.init(document.getElementById(name), 'dark', { renderer: 'svg' });
      }
      if (option == null) {
        option = Object.assign({}, this.basicOption)
      }

      setTimeout(() => {
            try {
              myChart.setOption(option);
            } catch (error) {}
        }, 500)    
    },
    initFactory() {
      var that = this;
      const canvas = document.getElementById("renderCanvas"); // Get the canvas element
      const engine = new BABYLON.Engine(canvas, true); // Generate the BABYLON 3D engine
      BABYLON.DefaultLoadingScreen.prototype.displayLoadingUI = function () {
      }
      BABYLON.DefaultLoadingScreen.prototype.hideLoadingUI = function () {
        document.getElementById("loadingScreen").style.display = "none";
      }

      engine.displayLoadingUI();
      const createScene = function () {
        const scene = new BABYLON.Scene(engine);
        scene.clearColor = BABYLON.Color3.Black(); //BABYLON.Color3(1, 0, 1); 
        const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 50, height: 50 });
        const groundMaterial = new BABYLON_GRID.GridMaterial("groundMaterial", scene);
        groundMaterial.majorUnitFrequency = 5;
        groundMaterial.minorUnitVisibility = 0.5;
        groundMaterial.gridRatio = 2;
        ground.material = groundMaterial;
        ground.position.y = -0.1;
        ground.rotation.z = 2*Math.PI;

        //large ground
        const largeGroundMat = new BABYLON.StandardMaterial("largeGroundMat");
        largeGroundMat.diffuseTexture = new BABYLON.Texture("url to large ground texture");

        const largeGround = BABYLON.MeshBuilder.CreateGroundFromHeightMap("largeGround", "https://assets.babylonjs.com/environments/villageheightmap.png", {width:50, height:50, subdivisions: 200, minHeight:0, maxHeight: 2});
        largeGround.material = groundMaterial;
        largeGround.position.y = -0.1;


        // 加载背景图片
        // const backgroundImage = new BABYLON.Layer('', 'img/bj.png', scene, true);
        const camera = new BABYLON.ArcRotateCamera("camera", that.initialAlpha, that.initialBeta, that.initialRadius, new BABYLON.Vector3(0, 0, 0));
        that.initialTarget = camera.getTarget();
        camera.lowerBetaLimit = Math.PI / 2.6; //无法移动到地面以下
        camera.upperBetaLimit = Math.PI / 2.1; //无法移动到地面以下
        camera.attachControl(canvas, true);
        camera.maxZ = 200; // 调整适当的值
        // 相机限制
        camera.lowerRadiusLimit = 2;
        camera.upperRadiusLimit = 4;

        // 灯光
        const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0));
        light.intensity = 1.6;
       
        // 全屏GUI
        const advancedTexture = BABYLON_GUI.AdvancedDynamicTexture.CreateFullscreenUI("myUI");
        that.myui = advancedTexture;
        // 创建一个高亮层
        const highlightLayer = new BABYLON.HighlightLayer('highlightLayer', scene);
        // 主视角
        var control_main = new BABYLON_GUI.StackPanel();
        control_main.isVertical = false
        control_main.top = '-40%';
        control_main.left = '-20%';
        advancedTexture.addControl(control_main);
      
        var button_main = BABYLON_GUI.Button.CreateSimpleButton("button_main", "主视角");
        button_main.width = "80px"
        button_main.height = "30px";
        button_main.color = "white";
        button_main.cornerRadius = 20;
        button_main.background = "green";
        // control_main.addControl(button_main)
        button_main.onPointerClickObservable.add(() => {
          if (camera.alpha != that.initialAlpha || camera.beta != that.initialBeta || camera.radius != that.initialRadius) {
            var cameraPosition = new BABYLON.Vector3(
              0 + that.initialRadius * Math.sin(that.initialBeta) * Math.cos(that.initialAlpha),
              0 + that.initialRadius * Math.cos(that.initialBeta),
              0 + that.initialRadius * Math.sin(that.initialBeta) * Math.sin(that.initialAlpha)
            );
            var ease = new BABYLON.CubicEase();
            ease.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
            BABYLON.Animation.CreateAndStartAnimation('at6', camera, 'position', 45, 200, camera.position, cameraPosition, 0, ease);
            BABYLON.Animation.CreateAndStartAnimation('at61', camera, 'target', 45, 200, camera.target, that.initialTarget, 0, ease);
          }
        })
        
        // 高亮显示mesh名
        const mesh_rect = new BABYLON_GUI.Rectangle('mesh_rect');
        mesh_rect.width = "100px";
        mesh_rect.height = "25px";
        mesh_rect.background = 'orange';
        mesh_rect.alpha = 0.6;
        mesh_rect.isVisible = false;
        advancedTexture.addControl(mesh_rect);

        var mesh_name = new BABYLON_GUI.TextBlock('mesh_name');
        mesh_name.text = "";
        mesh_name.color = 'white';
        mesh_name.fontSize = '14px';
        mesh_rect.addControl(mesh_name);
        var remoteGlbUrl = process.env.VUE_APP_BASEURL + "/media/model/photon.glb";
        BABYLON.SceneLoader.Append(remoteGlbUrl, "", scene, function (scene) {
          engine.hideLoadingUI()
        }, 
        function (evt) {
          var loadedPercent = 0;
          if (evt.lengthComputable) {
            loadedPercent = parseInt(evt.loaded * 100 / evt.total);
          } else {
            var dlCount = evt.loaded / (1024 * 1024);
            loadedPercent = Math.floor(dlCount * 100.0) / 100.0;
          }
          that.loadedPercent = loadedPercent;
        })
        return scene;
      };

      const scene = createScene(); //Call the createScene function
      // scene.debugLayer.show()

      // Register a render loop to repeatedly render the scene
      engine.runRenderLoop(function () {
        scene.render();
      });
      this.engine = engine;
      this.scene = scene;
      // Watch for browser/canvas resize events
      window.addEventListener("resize", function () {
        engine.resize();
      });
    },
    handleSectionClick(val, index) {
      let that = this;
      

    },
    getMgroupChartData(name){
    
    },
  },
 
}
</script>
<style scoped>
.dashboard {
  background-color: black;
  font-family: Inter, "-apple-system", BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "noto sans", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

header {
  position: absolute;
  z-index: 10;
  height: 50px;
  width: 100%;
  /* 调整头部高度 */
  /* background-image: url('/public/img/header.png'); */
  /* 替换为实际的背景图片路径 */
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  flex: 1;
  color: white;
  font-size: 24px;
}

.title_right {
  flex: 1;
  font-size: 20px;
  color: white;
  text-align: right;
}

.model {
  top: 0;
  width: 100%;
}

#renderCanvas {
  width: 100%;
  height: 100%
}

#loadingScreen {
  position: absolute;
  width: 100%;
  top: 260px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
}

</style>