<template>
  <div class="wcontainer">
    <img class="logo" :src="require(`@/assets/images/logo.png`)" alt="" />
    <Loading :barWidth="loadprogress" v-if="!hadLoaded" />
    <transition appear name="dm">
      <vmenu @clickItem="handleItem" />
    </transition>

    <transition appear name="dm">
      <vintroduce v-if="currentItem == 'info'" />
    </transition>


    <div id="webgl" ref="webgl"></div>
  </div>
</template>

<script>
import * as THREE from "three";
import { CSS2DRenderer, CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.js";

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
import { TWEEN } from "three/examples/jsm/libs/tween.module.min";

import vmenu from "@/components/menu";
import Loading from "@/components/loading";


import RoomLabel from "@/kit/RoomLabel";


import vintroduce from "@/components/introduce";


export default {
  components: { vmenu, Loading, vintroduce },
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      controls: null,
      textrueLoader: null,
      rafId: null,
      container: null,
      containerW: 0,
      containerH: 0,
      loadprogress: 0,
      hadLoaded: false,
      modelLoaded: null,
      timer: null,
      obj: null,
      labelRenderer: null,
      label: null,
      meshGroup: null,
      currentItem: ''
    };
  },
  methods: {

    handleItem(data) {
      this.currentItem = data.id

      switch (data.id) {
        case "info":
          this.info()
          break;
        default:
          break;
      }
    },

    info() {

    },

    init() {
      //画布
      this.container = this.$refs.webgl;
      this.containerW = this.$refs.webgl.getBoundingClientRect().width;
      this.containerH = this.$refs.webgl.getBoundingClientRect().height;


      //渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true});
      this.renderer.setSize(this.containerW, this.containerH);
      this.renderer.setClearAlpha(0);
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.renderer.outputEncoding = THREE.sRGBEncoding;
      this.container.appendChild(this.renderer.domElement);

      const pmremGenerator = new THREE.PMREMGenerator(this.renderer);

      this.scene = new THREE.Scene();

      this.scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.4).texture;

      // 相机
      this.camera = new THREE.PerspectiveCamera(45, this.containerW / this.containerH, 0.1, 1000);
      this.camera.position.set(0, 0, 0.78);
      this.camera.lookAt(this.scene.position);


      // 控制器
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.dampingFactor = 0.1;
      // this.controls.minDistance = 100;
      // this.controls.maxDistance = 800;
      // this.controls.maxPolarAngle = Math.PI;
      // this.controls.minPolarAngle = 0;
      this.controls.enablePan = false;
      this.controls.enableZoom = true;
      this.textrueLoader = new THREE.TextureLoader();
      this.controls.addEventListener("change", () => {
        this.label && this.label.update()
      });

      // this.loadGlb();
      this.loadObj()

      window.addEventListener("resize", this.onresize, false);

    },

    // 窗口改变
    onresize() {
      this.containerW = this.$refs.webgl.getBoundingClientRect().width;
      this.containerH = this.$refs.webgl.getBoundingClientRect().height;
      this.camera.aspect = this.containerW / this.containerH;
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(this.containerW, this.containerH);
      // this.labelRenderer.setSize(this.containerW, this.containerH);
    },

    loadGlb() {
      const loader = new GLTFLoader();
      loader.load(
        `model/wl48-he.glb`,
        (gltf) => {
          this.obj = gltf.scene;
          this.obj.traverse((child) => {
            if (child instanceof THREE.Mesh) {
              console.log(child);
              if (child.name == "WL48_ping") {
                var emissiveTexture = this.textrueLoader.load("model/shadow.jpg");
                // emissiveTexture.encoding = THREE.LinearEncoding;
                child.material.emissiveMap = emissiveTexture;
                child.material.emissiveIntensity = 0;
                child.material.emissive = new THREE.Color(0xffffff);
              }
            }
          })

          this.label = new RoomLabel({
            "position": [
              0.1,
              0.3,
              0
            ],
            "title": "new2",
            "floorIndex": 0,
            camera: this.camera,
            domElement: this.renderer.domElement,
            modelobj: this.obj.children
          })


          this.modelLoaded = true;
          this.scene.add(this.obj);

          this.animate();
        },
        (progress) => {
          // console.log(progress.loaded/progress.total);
        },
        function (error) {
          console.error(error);
        }
      );
    },

    loadObj() {
      new MTLLoader().setPath("model/").load("wl48-he.mtl", (materials) => {
        materials.preload();

        new OBJLoader()
          .setMaterials(materials)
          .setPath("model/")
          .load(
            "wl48-he.obj",
            (object) => {
              object.traverse((child) => {
                if (child instanceof THREE.Mesh) {
                  console.log();
                }
              });

              this.modelLoaded = true;
              let s = 0.005
              object.scale.set(s, s, s)
              this.scene.add(object);
              this.label = new RoomLabel({
                  "position": [-5.0576,11.1395,-10.387],
                  "title": "new2",
                  camera: this.camera,
                  domElement: this.renderer.domElement,
                  modelobj: object.children
                })
              this.animate();
            },
            (pro) => { }
          );
      });


      var light1 = new THREE.AmbientLight(16777215);
      light1.intensity = 2.8;
      this.scene.add(light1)

      var light2 = new THREE.DirectionalLight(0xffffff, 1);
      light2.position.set(0, 1, 0.4).normalize();
      light2.intensity = 3;
      this.scene.add(light2)
      //
    },

    animate() {
      this.rafId = requestAnimationFrame(this.animate);
      this.controls.update();
      TWEEN.update();
      this.renderer.render(this.scene, this.camera);
    },

  },
  mounted() {
    this.timer = setInterval(() => {
      if (!this.hadLoaded) {
        if (this.loadprogress < 80) {
          this.loadprogress += 0.8;
        } else {
          if (this.modelLoaded) {
            if (this.loadprogress <= 100) {
              this.loadprogress += 2;
            } else {
              this.hadLoaded = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }
        }
      }
    }, 10);
    this.init();
  },
  watch: {
    hadLoaded(newVal) {

    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    cancelAnimationFrame(this.rafId);
    window.removeEventListener("resize", this.onresize, false);

    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.scene = null;
    this.camera = null;
    this.renderer.domElement = null;
    this.renderer = null;
    this.controls = null;
    this.textrueLoader = null;
    this.rafId = null;
  },
};
</script>

<style lang="less" scoped>
.wcontainer {
  width: 100%;
  height: 100%;
  position: relative;
  background-repeat: no-repeat;
  color: #ac5b5b;

  .logo {
    position: absolute;
    top: 50px;
    left: 66px;
    width: 100px;
    z-index: 9999;
  }


  #webgl {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}

.dm-enter {
  opacity: 0;
}

.dm-leave-to {
  opacity: 0;
}

.dm-enter-active,
.dm-leave-active {
  transition: all 3.8s ease;
}
</style>

<style lang="less">
.label {
  color: #000;
  text-align: center;

  >img {
    width: 20px;
    position: absolute;
    left: 50%;
    transform: translate(-50%, 10%);
  }
}

@full: 18500px;
@single: 500px;
@scale: 0.6;

.bowen {
  z-index: 9;
  width: @single * @scale;
  height: @single* @scale;
  overflow: hidden;
  pointer-events: none;

  >img {
    width: @full * @scale;
    left: 0;
    height: 100%;
    position: absolute;
    animation: jieshuo 2.4s steps(37) forwards;
  }
}

@keyframes jieshuo {
  100% {
    left: -@full* @scale;
  }
}
</style>
