<template>
    <div style="height: 100%">
      <div id="viewPort" style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;"></div>
      <div ref="modelProcess" style="position: absolute;top: 10px;left: 2px;color: white">正在加载模型0%</div>
      <div style="display: none">
        <audio controls loop id="alarm">
          <source src="./libs/alarm.mp3" type="audio/mpeg">
        </audio>
        <audio controls id="clash">
          <source src="./libs/alarm.mp3" type="audio/mpeg">
        </audio>
      </div>
      <div style="position: absolute;left: 10px;top:10px;height: 500px;overflow: auto;width: 300px;display: none">
        <el-color-picker v-model="color" color-format="rgb" @active-change="setModelColor"></el-color-picker>
      </div>
      <div style="position: absolute;left: 10px;top:10px;height: 500px;overflow: auto;width: 300px;display: none">
        <el-tree :data="treeData" :props="treeDefaultProps" @node-click="handleNodeClick"></el-tree>
      </div>
      <div style="position: absolute;left: 320px;top:10px;height: 340px;overflow: auto;width: 250px;padding-left: 30px;background-color: #ffffff;display: none">
        <el-row>{{ object.ModelName }}({{ object.ModelId }})</el-row>
        <el-row style="margin-top: 5px">
          <span>position</span>
          <el-input-number v-model="stepPosition" size="mini" style="width: 100px"></el-input-number>
          <br>
          <el-input-number v-model="object.position.x" :step="stepPosition" size="mini" style="width: 180px;margin-top: 5px" @change="ModelPositionChange"></el-input-number>
          <br>
          <el-input-number v-model="object.position.y" :step="stepPosition" size="mini" style="width: 180px;margin-top: 5px" @change="ModelPositionChange"></el-input-number>
          <br>
          <el-input-number v-model="object.position.z" :step="stepPosition" size="mini" style="width: 180px;margin-top: 5px" @change="ModelPositionChange"></el-input-number>
        </el-row>
        <el-row style="margin-top: 5px">
          <span>rotation</span>
          <el-input-number v-model="stepRotation" size="mini" style="width: 100px"></el-input-number>
          <br>
          <el-input-number v-model="object.rotation.x" :step="stepRotation" size="mini" style="width: 180px;margin-top: 5px" @change="ModelRotationChange"></el-input-number>
          <br>
          <el-input-number v-model="object.rotation.y" :step="stepRotation" size="mini" style="width: 180px;margin-top: 5px" @change="ModelRotationChange"></el-input-number>
          <br>
          <el-input-number v-model="object.rotation.z" :step="stepRotation" size="mini" style="width: 180px;margin-top: 5px" @change="ModelRotationChange"></el-input-number>
        </el-row>
        <el-row style="margin-top: 5px">
          <el-button type="warning" size="mini" @click="setViewCamera">重置</el-button>
          <el-button type="success" size="mini" @click="setModelSates">保存</el-button>
        </el-row>
      </div>
    </div>
</template>

<script>
import * as THREE from 'three'
import axios from 'axios'
import $ from 'jquery'
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import * as TWEEN from 'three/examples/jsm/libs/tween.module.js'

import { DmtControl } from './libs/DmtControl.js'
import { connect } from './js/websocketConnect.js'
import { connectMqtt } from './js/MqttConnect.js'
import { PlaySoundCommand } from './js/PlaySoundCommand.js'
import SpriteText from './js/three-spritetext.module.js'

// eslint-disable-next-line no-unused-vars
let container, clock, scene, camera, axesHelper, renderer, Plane
let modelCount = 0
const editor = {
  cameraStateZoom: 25,
  addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  showTagList: [{
    title: '工件：QY16KC',
    ModelId: 'A113AD62-9CE7-4ACF-8D0C-8E8A597A8768',
    object: null
  }],
  ip: '',
  WeldLight1: '',
  WeldLightVisible1: false,
  WeldLight2: '',
  WeldLightVisible2: false,
  scene: null,
  objectIdUUidMap: new Map(),
  opname: '',
  connectType: 1,
  BSport: '',
  IsAllowConnect: true,
  service: axios.create({
    baseURL: './submit/MESCommonBase.ashx',
    timeout: 1500000 // 请求超时时间
  }),
  selected: null,
  selectedLast: [],
  socket: null,
  mqttClient: {
    connected: false
  },
  ProjectCode: null,
  sceneConfig: null,
  resourcesTree: null,
  attachments: null,
  resources: null,
  cameraState: null,
  cameraStateAll: [],
  isOk: false,
  objectIdSet: new Map(),
  animOperations: null,
  CraftList: {},
  moveTrigger: null,
  camera: null,
  cameraPosition: 10,
  currentButton: 1,
  cameraControls: null,
  TagActList: {}, // 存放tag对应的类型
  worker: {}, // 播放工艺的线程
  RotationWorker: {}, // 自传工艺的线程
  ModelRotateWorker: {}, // 自传工艺的的状态数据
  rotateSpeed: 5 * Math.PI / 180,
  getObjectById: null, // 方法 根据ModelId获取模型
  solveAttachModel: null, // 方法 处理attach问题
  removeObject: null, // 方法 移除模型
  setModelWireFrame: null, // 方法 设置线框
  setTransparent: null, // 方法 设置透明
  showMessage: null, // 方法 显示消息
  drawPartTextInfo: null, // 方法 模型上显示文字
  ModelLabelList: new Map(), // 模型上显示列表
  playSoundCommand: new PlaySoundCommand(), //  方法 警告
  attachList: new Map(), // 记录attach列表
  objMaterial: new Map(),
  WareHouseList: [],
  WareHouse: new Map(), // 立库库存表
  WareHouseBasicModel: new Map(), // 立库库存基础 零件模型需要命名为warehousepart1-100 立库定位模型需要命名为warehouse1000-1009
  ProtocolIdentifiers: {
    Robot_7: 'Robot_7',
    Device_3: 'Device_3',
    Agv_3: 'Agv_3',
    Device_1: 'Device_1',
    FirstPosition: 'FirstPosition',
    WareHousePart: 'WareHousePart',
    Robot_6: 'Robot_6',
    RobotTcp: 'RobotTcp',
    DrawPath: 'DrawPath',
    ReLoadData: 'ReLoadData',
    PlayAct: 'PlayAct',
    CraftCurrOperation: 'CraftCurrOperation',
    Position: 'Position',
    Select: 'Select',
    DragMove: 'DragMove',
    ModelTransparent: 'ModelTransparent',
    Visible: 'Visible',
    Frames: 'Frames',
    ModelRotation: 'ModelRotation',
    GoHome: 'GoHome',
    GetJointAxisInfo: 'GetJointAxisInfo',
    GetDeviceBaseTool: 'GetDeviceBaseTool',
    GetJointValue: 'GetJointValue',
    C_B_ImportModel: 'C_B_ImportModel',
    SendURDF: 'SendURDF',
    SendDeviceJson: 'SendDeviceJson',
    GetDeviceJson: 'GetDeviceJson',
    SendMotionInfo: 'SendMotionInfo',
    C_B_ImportLayout: 'C_B_ImportLayout',
    GetPoseLocation: 'GetPoseLocation',
    C_B_SetProjectCode: 'C_B_SetProjectCode',
    C_B_TagIDTrigger: 'C_B_TagIDTrigger',
    C_B_ReLoad_TagIDHandler: 'C_B_ReLoad_TagIDHandler',
    C_B_SetCurrSignalList: 'C_B_SetCurrSignalList',
    SendClearModelInfo: 'SendClearModelInfo',
    C_B_SaveProjectSimulationData: 'C_B_SaveProjectSimulationData',
    C_B_GetProjectSimulationData: 'C_B_GetProjectSimulationData',
    C_B_KinematicsEditing: 'C_B_KinematicsEditing',
    C_B_SaveModel: 'C_B_SaveModel',
    C_B_ObjectAlarm: 'C_B_ObjectAlarm',
    C_B_JointMoveTo: 'C_B_JointMoveTo',
    JointMoveTo: 'JointMoveTo' // DT|JointMoveTo|modelCode|{"J1":"1","J2":"2","J3":"3","J4":"4","J5":"5","J6":"6","J7":"7","J8":"8","J9":"9"}
  },
  craftPlaySolveType: {
    visible: 'visible',
    rotation: 'rotation',
    craft: 'craft',
    signalwrite: 'signalwrite',
    wait: 'wait',
    FrameData: 'FrameData',
    attach: 'attach',
    warning: 'warning'
  },
  FrameOperation: {
    playCraft: true,
    visibleObject: true,
    rotationObject: true,
    writeSignal: true,
    waitSignal: true,
    attach: true,
    warning: true
  },
  signalSolveType: {
    visible: 'visible',
    rotation: 'rotation',
    craft: 'craft',
    targetLocation: 'targetlocation',
    attach: 'attach',
    warning: 'warning'
  }
}
// eslint-disable-next-line no-unused-vars
let ModelListTransParentList = []
const ModelList = []
const ModelListId = []
// eslint-disable-next-line no-unused-vars
const timer = null
// eslint-disable-next-line no-unused-vars
const lastIntersectModel = null
// eslint-disable-next-line no-unused-vars
const onUpPosition = new THREE.Vector2()

var raycaster = new THREE.Raycaster()
var mouse = new THREE.Vector2()

export default {
  components: {
  },
  name: 'DMT',
  props: {
    containerHeight: {
      type: String,
      default: '100vh'
    },
    containerWidth: {
      type: String,
      default: '100vw'
    }
  },
  data() {
    return {
      color: '',
      stepPosition: 100,
      stepRotation: 90,
      treeData: [],
      treeDefaultProps: {
        children: 'children',
        label: 'label'
      },
      checked: false,
      cameraData: [],
      object: {
        ModelName: '',
        object: null,
        ModelId: '',
        position: {
          x: 0,
          y: 0,
          z: 0
        },
        rotation: {
          x: 0,
          y: 0,
          z: 0
        },
        positionOrigin: {
          x: 0,
          y: 0,
          z: 0
        },
        rotationOrigin: {
          x: 0,
          y: 0,
          z: 0
        }
      },
      s: null
    }
  },
  mounted() {
    const scope = this
    editor.objectIdSet = new Map()
    editor.objMaterial = new Map()
    editor.attachList = new Map()
    this.getConfig().then(res => {
      if (Object.hasOwnProperty.call(res, 'robotList')) {
        editor.robotList = res.robotList
      }
      if (Object.hasOwnProperty.call(res, 'WareHouseList')) {
        editor.WareHouseList = res.WareHouseList
      }
      if (Object.hasOwnProperty.call(res, 'transParentList')) {
        ModelListTransParentList = res.transParentList
      }
      if (Object.hasOwnProperty.call(res, 'connectType')) {
        editor.connectType = res.connectType
      }
      editor.mqttHost = res.MQTTHost
      editor.mqttPort = res.MQTTPort
      editor.ip = res.webSocketIp
      editor.opname = res.webSocketOpName
      editor.BSport = res.webSocketBSport
      editor.rootIp = res.NodeRootIp
      this.getProjectConfig()
    })
    editor.showMessage = function(message, type, time = 2000) {
      scope.$message({
        message: message,
        type: type,
        duration: time,
        center: true
      })
    }
    editor.addEventListener('dmtModelDBClick', function(event) {
      console.log('dmtModelDBClick', event)
    })
    // 24c18568-a699-4672-b809-60a6b06a5b8c 1016_CRCC_Reciprocator_01
    // 52307b84-2ac2-498c-b4f1-3af2718c5846 地面_1
    // e2ea004f-52e3-4335-b256-aa4303f26974 辅助设备33
    // 1b8aca07-15fd-42d7-b0c7-ed08429424fe 辅助设备33.001
    // a5e667c3-7817-491b-becc-4dc781ac309c 辅助设备341
    // f8a09042-c38c-4044-95ad-44cd8b4c37cc B1016_003
    // b00ac5cf-8500-4524-991e-1ec6d32b110b B1016_004
    //
    // 7c4f735d-52f6-40c6-93bd-d952046ffb16 B1023_001
    // f5c7dba7-b600-461f-9ecf-9d1700ea3c08 B1023_002
    // ba2f0d12-fc32-4c27-a331-dca4ea414976 B1023_003
    // 25267bd2-b3fe-4f18-b0a7-1112ae8d8bdd B1023_004
    // c5615437-8d00-45df-9994-a2a4fe62bf04 B1023_005
    // e767f4c0-ad7f-4b95-9df0-057ac3790b0e B1023_006
    // 60cbfa4c-cded-47b7-85fe-75f875be7175 B1023_008
    // 3509c60c-a00e-4fe3-9e0b-3720c7715b20 B1023_009
    // 761643bf-2d33-4638-a8f2-6f939dad3164 B1023_010
    // 836959a6-a6d2-4ed4-b134-d06aa0b44dee B1023_011
    // 7efd8a9a-6646-41b7-b754-cd16d973d24d B1027_001
    // 63e74059-bf65-4f57-942d-fac4231f5c02 B1027_002
    // c916efb5-97a2-4bff-b342-08538fd54064 B1027_003
    // f89a89f6-7f27-4ea6-9b5b-65bd076a8118 B1027_004
    // 2e7560f0-86c8-45c8-8059-db98cf76cc37 B1027_R1
    // fe6e333f-cb4e-48c2-b534-dfe639f1bab8 B1027_R2
    // 18d66ab1-1372-42b4-ab07-50936ed3e790 B1029_002
    // f6162245-3903-4c5b-9d33-d8d1ac9ec2a7 B1029_003
    // e5089214-e301-4349-b7ac-1246e93c8b7b B1029_004
    // 9794fa26-f3d0-468f-8379-1b08fa85ab7a B1029_R1
    // a41e5369-f0df-4dbe-9140-b7bee1d2c570 B1029_R2
    // ea29aca2-13a5-4758-9768-0eb630332176 B1033_002
    // 75189272-7698-4661-84d0-d17154a79fba B1033_002.001
    // e64249d7-d310-4a1e-a045-3339276ae234 B1034_002
    // 10a0fdb3-e29d-4add-a314-467f206ad4b2 B1040_001
    // 46fa4a75-09fa-4709-963f-a7b72b7dd928 B1040_002
    // 9eff4a7e-6015-4197-9f07-186643f0b3d3 B1040_002_2
    // b211df70-4288-4249-9a46-c9547c548c23 B1040_003
    // 1d8da3ee-e01a-4c87-9d38-f507e069f670 B1040_004
    // e38b5ba0-e5fb-4330-b246-84c998ada635 B1040_R1
    // 199a41c0-732a-438e-a30e-567cac7610a4 B1040_R2
    // 38d09851-54a1-4eec-8b54-58982fb916ec B1041_001
    // a5889893-d9ca-492f-9a2d-017148fdb1fa B1041_002
    // 1c75cdac-daac-4032-ba59-cd639c4a721f B1041_002_2
    // ae1a872e-61e8-4eab-a551-a0768a967898 B1041_003
    // b83dc9b0-a5d1-4c4f-b12a-4487aa6a699d B1041_004
    // 84488108-fff6-41cb-bbd4-bddebd935aca B1041_R1
    // d1e63687-e514-4725-b2b4-dabb9311e554 B1041_R2
    // 71fba1dc-24b7-4fc6-bda5-82a41dde956c carA-33
    // d24366d7-9ce6-4ae5-9e6b-90fd54b85d32 carA-34
    // af759b25-df55-4157-9760-09393eaff9f1 CRCC_dianqigui
    // f641b043-5b64-434d-892c-292af38bde9e CRCC_HuLan
    // 2e2f403e-965c-4a1b-b428-2c5fe556bc36 CRCC_HuLan_Door01
    // 3eb12bb3-5a6e-462a-88de-fd9d348d6e2d CRCC_HuLan_Door02
    // 3daab35f-15a1-4a8d-a144-a5ead630e600 CRCC_Reciprocator_Plane33
    //
    // 8503054d-d1c7-4775-b1a9-aae117b2f99f CRCC_Reciprocator_Plane34
    // a9012bf0-5ecf-48ff-a5b5-629de0d48612 CRCC_Robot_01
    // a7139eca-bbeb-4769-ac0b-e615d45b0f96 CRCC_Robot_02
    // c86c1303-6078-45f0-87ed-8e57efe460df guidao33
    //
    // 6410e511-0b1e-47a4-b1a9-094c1dcec9e7 guidao34
    const ModelPositionConfig = [
      // x 1040
      {
        name: 'B1040_001',
        ModelId: '10a0fdb3-e29d-4add-a314-467f206ad4b2',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_002',
        ModelId: '46fa4a75-09fa-4709-963f-a7b72b7dd928',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_002_2',
        ModelId: '9eff4a7e-6015-4197-9f07-186643f0b3d3',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_003',
        ModelId: 'b211df70-4288-4249-9a46-c9547c548c23',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_004',
        ModelId: '1d8da3ee-e01a-4c87-9d38-f507e069f670',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_R1',
        ModelId: 'e38b5ba0-e5fb-4330-b246-84c998ada635',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      {
        name: 'B1040_R2',
        ModelId: '199a41c0-732a-438e-a30e-567cac7610a4',
        axis: 'x',
        type: 'position',
        delta: -27000,
        valueFactory: 0.001
      },
      // x y 1021
      {
        name: '辅助设备33.001',
        ModelId: '1b8aca07-15fd-42d7-b0c7-ed08429424fe',
        axis: 'x',
        type: 'position',
        delta: -41000,
        valueFactory: 0.001
      },
      {
        name: 'CRCC_Reciprocator_Plane33.001',
        ModelId: '95fcfcd5-dc2e-4be8-a296-160ccb4d0201',
        axis: 'x',
        type: 'position',
        delta: -41000,
        valueFactory: 0.001
      },
      {
        name: 'guidao33.001',
        ModelId: 'bbe8ef46-ab01-40ba-bc78-00829a621c75',
        axis: 'x',
        type: 'position',
        delta: -41000,
        valueFactory: 0.001
      },
      {
        name: 'B1021-004',
        ModelId: '987865a5-25ef-4a59-a8ad-56284e585856',
        axis: 'x',
        type: 'position',
        delta: -41000,
        valueFactory: 0.001
      },
      {
        name: 'B1033_002.001',
        ModelId: '75189272-7698-4661-84d0-d17154a79fba',
        axis: 'x',
        type: 'position',
        delta: -41000,
        valueFactory: 0.001
      },
      {
        name: '辅助设备33.001',
        ModelId: '1b8aca07-15fd-42d7-b0c7-ed08429424fe',
        axis: 'y',
        type: 'position',
        delta: 3000,
        valueFactory: 0.001
      },
      {
        name: 'CRCC_Reciprocator_Plane33.001',
        ModelId: '95fcfcd5-dc2e-4be8-a296-160ccb4d0201',
        axis: 'y',
        type: 'position',
        delta: 3000,
        valueFactory: 0.001
      },
      {
        name: 'guidao33.001',
        ModelId: 'bbe8ef46-ab01-40ba-bc78-00829a621c75',
        axis: 'y',
        type: 'position',
        delta: 3000,
        valueFactory: 0.001
      },
      {
        name: 'B1021-004',
        ModelId: '987865a5-25ef-4a59-a8ad-56284e585856',
        axis: 'y',
        type: 'position',
        delta: 3000,
        valueFactory: 0.001
      },
      {
        name: 'B1033_002.001',
        ModelId: '75189272-7698-4661-84d0-d17154a79fba',
        axis: 'y',
        type: 'position',
        delta: 3000,
        valueFactory: 0.001
      },
      // x 地面
      {
        name: '地面_1',
        ModelId: '52307b84-2ac2-498c-b4f1-3af2718c5846',
        axis: 'x',
        type: 'position',
        delta: -13000,
        valueFactory: 0.001
      },
      // x 1023
      {
        name: 'B1023_001',
        ModelId: '7c4f735d-52f6-40c6-93bd-d952046ffb16',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_002',
        ModelId: 'f5c7dba7-b600-461f-9ecf-9d1700ea3c08',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_003',
        ModelId: 'ba2f0d12-fc32-4c27-a331-dca4ea414976',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_004',
        ModelId: '25267bd2-b3fe-4f18-b0a7-1112ae8d8bdd',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_005',
        ModelId: 'c5615437-8d00-45df-9994-a2a4fe62bf04',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_006',
        ModelId: 'e767f4c0-ad7f-4b95-9df0-057ac3790b0e',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_008',
        ModelId: '60cbfa4c-cded-47b7-85fe-75f875be7175',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_009',
        ModelId: '3509c60c-a00e-4fe3-9e0b-3720c7715b20',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_010',
        ModelId: '761643bf-2d33-4638-a8f2-6f939dad3164',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      {
        name: 'B1023_011',
        ModelId: '836959a6-a6d2-4ed4-b134-d06aa0b44dee',
        axis: 'x',
        type: 'position',
        delta: 2000,
        valueFactory: 0.001
      },
      // x y 1027
      {
        name: 'B1027_001',
        ModelId: '7efd8a9a-6646-41b7-b754-cd16d973d24d',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_002',
        ModelId: '63e74059-bf65-4f57-942d-fac4231f5c02',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_003',
        ModelId: 'c916efb5-97a2-4bff-b342-08538fd54064',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_004',
        ModelId: 'f89a89f6-7f27-4ea6-9b5b-65bd076a8118',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_R1',
        ModelId: '2e7560f0-86c8-45c8-8059-db98cf76cc37',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_R2',
        ModelId: 'fe6e333f-cb4e-48c2-b534-dfe639f1bab8',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_001',
        ModelId: '7efd8a9a-6646-41b7-b754-cd16d973d24d',
        axis: 'y',
        type: 'position',
        delta: -5000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_002',
        ModelId: '63e74059-bf65-4f57-942d-fac4231f5c02',
        axis: 'y',
        type: 'position',
        delta: -5000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_003',
        ModelId: 'c916efb5-97a2-4bff-b342-08538fd54064',
        axis: 'y',
        type: 'position',
        delta: -5000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_004',
        ModelId: 'f89a89f6-7f27-4ea6-9b5b-65bd076a8118',
        axis: 'y',
        type: 'position',
        delta: -5000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_R1',
        ModelId: '2e7560f0-86c8-45c8-8059-db98cf76cc37',
        axis: 'y',
        type: 'position',
        delta: -5000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_R2',
        ModelId: 'fe6e333f-cb4e-48c2-b534-dfe639f1bab8',
        axis: 'y',
        type: 'position',
        delta: 1200,
        valueFactory: 0.001
      },
      // x 1029
      {
        name: 'B1029_002',
        ModelId: '18d66ab1-1372-42b4-ab07-50936ed3e790',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_003',
        ModelId: 'f6162245-3903-4c5b-9d33-d8d1ac9ec2a7',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_004',
        ModelId: 'e5089214-e301-4349-b7ac-1246e93c8b7b',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_R1',
        ModelId: '9794fa26-f3d0-468f-8379-1b08fa85ab7a',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_R2',
        ModelId: 'a41e5369-f0df-4dbe-9140-b7bee1d2c570',
        axis: 'x',
        type: 'position',
        delta: -4500,
        valueFactory: 0.001
      },
      // y 1033
      {
        name: '辅助设备33',
        ModelId: 'e2ea004f-52e3-4335-b256-aa4303f26974',
        axis: 'y',
        type: 'position',
        delta: 10000,
        valueFactory: 0.001
      },
      {
        name: 'carA-33',
        ModelId: '71fba1dc-24b7-4fc6-bda5-82a41dde956c',
        axis: 'y',
        type: 'position',
        delta: 10000,
        valueFactory: 0.001
      },
      {
        name: 'CRCC_Reciprocator_Plane33',
        ModelId: '3daab35f-15a1-4a8d-a144-a5ead630e600',
        axis: 'y',
        type: 'position',
        delta: 10000,
        valueFactory: 0.001
      },
      {
        name: 'guidao33',
        ModelId: 'c86c1303-6078-45f0-87ed-8e57efe460df',
        axis: 'y',
        type: 'position',
        delta: 10000,
        valueFactory: 0.001
      },
      // y 1034
      {
        name: '辅助设备341',
        ModelId: 'a5e667c3-7817-491b-becc-4dc781ac309c',
        axis: 'y',
        type: 'position',
        delta: 9000,
        valueFactory: 0.001
      },
      {
        name: 'carA-34',
        ModelId: 'd24366d7-9ce6-4ae5-9e6b-90fd54b85d32',
        axis: 'y',
        type: 'position',
        delta: 9000,
        valueFactory: 0.001
      },
      {
        name: 'CRCC_Reciprocator_Plane34',
        ModelId: '8503054d-d1c7-4775-b1a9-aae117b2f99f',
        axis: 'y',
        type: 'position',
        delta: 9000,
        valueFactory: 0.001
      },
      {
        name: 'guidao34',
        ModelId: '6410e511-0b1e-47a4-b1a9-094c1dcec9e7',
        axis: 'y',
        type: 'position',
        delta: 9000,
        valueFactory: 0.001
      },
      // y 1041
      {
        name: 'B1041_001',
        ModelId: '38d09851-54a1-4eec-8b54-58982fb916ec',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_002',
        ModelId: 'a5889893-d9ca-492f-9a2d-017148fdb1fa',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_002_2',
        ModelId: '1c75cdac-daac-4032-ba59-cd639c4a721f',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_003',
        ModelId: 'ae1a872e-61e8-4eab-a551-a0768a967898',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_004',
        ModelId: 'b83dc9b0-a5d1-4c4f-b12a-4487aa6a699d',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_R1',
        ModelId: '84488108-fff6-41cb-bbd4-bddebd935aca',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_R2',
        ModelId: 'd1e63687-e514-4725-b2b4-dabb9311e554',
        axis: 'y',
        type: 'position',
        delta: -8000,
        valueFactory: 0.001
      }
    ]
    const carPositionConfig = [
      {
        name: 'B1021_car_4',
        ModelId: '987865a5-25ef-4a59-a8ad-56284e585856',
        axis: 'x',
        delta: 2742,
        valueFactory: 0.001
      },
      {
        name: 'B1040_car_4',
        ModelId: 'd21dfb58-5209-4c5d-855e-8a27294b3bef',
        axis: 'x',
        delta: 10000,
        valueFactory: 0.001
      },
      {
        name: 'B1041_car_4',
        ModelId: '314d90eb-22a8-4e00-a498-d5f9cc16b19f',
        axis: 'x',
        delta: 10000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_car_4',
        ModelId: 'caad2cbf-db1e-49dc-ac0d-62d59217c6c0',
        axis: 'x',
        delta: 7000,
        valueFactory: 0.001
      },
      {
        name: 'B1027_机器人1移动辊道的位置',
        ModelId: '2e7560f0-86c8-45c8-8059-db98cf76cc37',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_机器人2移动辊道的位置',
        ModelId: 'fe6e333f-cb4e-48c2-b534-dfe639f1bab8',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_上面的框架',
        ModelId: '7efd8a9a-6646-41b7-b754-cd16d973d24d',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1027_辊道',
        ModelId: 'c916efb5-97a2-4bff-b342-08538fd54064',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_car_4',
        ModelId: 'c2dff096-b393-4dc2-820f-adf5566c3f1c',
        axis: 'x',
        delta: 7000,
        valueFactory: 0.001
      },
      {
        name: 'B1029_机器人1移动辊道的位置',
        ModelId: 'a41e5369-f0df-4dbe-9140-b7bee1d2c570',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_机器人2移动辊道的位置',
        ModelId: '9794fa26-f3d0-468f-8379-1b08fa85ab7a',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      },
      {
        name: 'B1029_辊道',
        ModelId: 'f6162245-3903-4c5b-9d33-d8d1ac9ec2a7',
        axis: 'x',
        delta: 4500,
        valueFactory: 0.001
      }
    ]
    const carPositionTimer = setInterval(() => {
      if (window.editor && window.editor.isOk) {
        for (const iterator of ModelPositionConfig) {
          const Model = window.editor.getObjectById(iterator['ModelId'])
          const delta = iterator['delta']
          const valueFactory = iterator['valueFactory']
          const axis = iterator['axis']
          const type = iterator['type']
          if (Model) {
            Model[type][axis] += (delta * valueFactory)
          }
        }
        for (const iterator of carPositionConfig) {
          const Model = editor.getObjectById(iterator['ModelId'])
          if (Model) {
            Model.position[iterator['axis']] += (iterator['delta'] * iterator['valueFactory'])
          }
        }
        scope.setModelColor()
        clearInterval(carPositionTimer)
      }
    }, 1000)
    // 部分车体位置的配置
  },
  created() {
  },
  methods: {
    setModelColor(value) {
      // editor.getObjectById('52307b84-2ac2-498c-b4f1-3af2718c5846').children[0].material.color.r = 243.0 / 255.0
      // editor.getObjectById('52307b84-2ac2-498c-b4f1-3af2718c5846').children[0].material.color.g = 255.0 / 255.0
      // editor.getObjectById('52307b84-2ac2-498c-b4f1-3af2718c5846').children[0].material.color.b = 255.0 / 255.0
      editor.getObjectById('52307b84-2ac2-498c-b4f1-3af2718c5846').children[0].material.color = new THREE.Color(value)
    },
    sortChinese(arr, dataLeven) { // 参数：arr 排序的数组; dataLeven 数组内的需要比较的元素属性
      /* 获取数组元素内需要比较的值 */
      function getValue(option) { // 参数： option 数组元素
        if (!dataLeven) return option
        var data = option
        dataLeven.split('.').filter(function(item) {
          data = data[item]
        })
        return data + ''
      }
      arr.sort(function(item1, item2) {
        return getValue(item1).localeCompare(getValue(item2), 'zh-CN')
      })
      return arr
    },
    handleNodeClick(data) {
      console.log(data)
      editor.selected = data.Model
      for (let i = 0; i < editor.selectedLast.length; i++) {
        editor.selectedLast[i].material = editor.objMaterial.get(editor.selectedLast[i].id).clone()
      }
      editor.selectedLast = []
      editor.selected.traverse(function(child) {
        if (child.isMesh) {
          child.material.color = new THREE.Color('#00893D')
          editor.selectedLast.push(child)
        }
      })

      this.object = {
        ModelName: '',
        ModelId: '',
        position: {
          x: 0,
          y: 0,
          z: 0
        },
        rotation: {
          x: 0,
          y: 0,
          z: 0
        },
        positionOrigin: {
          x: 0,
          y: 0,
          z: 0
        },
        rotationOrigin: {
          x: 0,
          y: 0,
          z: 0
        }
      }
      this.object.ModelId = data.Model.userData.ModelId
      this.object.ModelName = data.Model.userData.name
      const position = JSON.parse(JSON.stringify(data.Model.position))
      const rotation = JSON.parse(JSON.stringify(data.Model.rotation))
      console.log(position)
      console.log(rotation)
      this.object.positionOrigin.x = position.x
      this.object.positionOrigin.y = position.y
      this.object.positionOrigin.z = position.z
      this.object.rotationOrigin.x = rotation._x
      this.object.rotationOrigin.y = rotation._y
      this.object.rotationOrigin.z = rotation._z
      editor.selectedLast = editor.selected
    },
    ModelPositionChange() {
      editor.selected.position.x = this.object.positionOrigin.x + this.object.position.x / 1000
      editor.selected.position.y = this.object.positionOrigin.y + this.object.position.y / 1000
      editor.selected.position.z = this.object.positionOrigin.z + this.object.position.z / 1000
    },
    ModelRotationChange() {
      editor.selected.rotation.x = this.object.rotationOrigin.x + this.object.rotation.x / 180 * Math.PI
      editor.selected.rotation.y = this.object.rotationOrigin.y + this.object.rotation.y / 180 * Math.PI
      editor.selected.rotation.z = this.object.rotationOrigin.z + this.object.rotation.z / 180 * Math.PI
    },
    getConfig() {
      return new Promise((resolve, reject) => {
        axios.get('./DMT_WEB/config/config.json').then(res => {
          const configData = res.data
          resolve(configData)
        }).catch(err => {
          reject(err)
        })
      })
    },
    /**
       * 获取项目配置文件，用于初始隐藏模型
       */
    getProjectConfig() {
      const P1 = new Promise(function(resolve, reject) {
        axios({
          method: 'get',
          url: './DMT_WEB/models/DTDATA.json'
        }).then((res) => {
          editor.animOperations = {}
          editor.moveTrigger = {}
          res.data.forEach(n => {
            Object.keys(n).forEach(function(key) {
              /**
                       * 获取播放数据并解析数据
                       */
              if (key === 'OperationTree') {
                n[key].forEach(CraftData => {
                  editor.CraftList[CraftData.CraftCode] = {}
                  editor.CraftList[CraftData.CraftCode]['CraftName'] = CraftData.CraftName
                  editor.CraftList[CraftData.CraftCode]['Varieties'] = CraftData.Varieties
                  editor.CraftList[CraftData.CraftCode]['CurrPlay'] = CraftData.CurrPlay
                  if (CraftData.CraftPlayData.length < 2) {
                    editor.animOperations[CraftData.CraftCode] = ''
                  } else {
                    editor.animOperations[CraftData.CraftCode] = JSON.parse(CraftData.CraftPlayData)
                  }
                  editor.moveTrigger[CraftData.CraftCode] = {
                    moveStatus: 0,
                    myVarSetInterval: null,
                    doAnimation: false,
                    currentFrame: 0,
                    pausedFrame: 0,
                    animOperations: editor.animOperations[CraftData.CraftCode],
                    simPaceTime: 20,
                    moveStatusPosition: 0
                  }
                })
              }
              /**
                       * HandlerType: 1:显隐,2:自转,3行为
                       * HandlerCode: 模型或者工艺代码
                       * HandlerValue: 显隐：0/1 ,自传：正负转速&axis,行为暂停播放：0/1
                       * TagValue:信号值
                       */
              if (key === 'TagTriggerHandler') {
                n[key].forEach(TagActListValue => {
                  if (editor.TagActList[TagActListValue.TagID]) {
                    editor.TagActList[TagActListValue.TagID].push({
                      HandlerType: TagActListValue.HandlerType,
                      HandlerCode: TagActListValue.HandlerCode,
                      HandlerValue: TagActListValue.HandlerValue,
                      TagValue: TagActListValue.TagValue,
                      JointType: TagActListValue.JointType,
                      Axis: TagActListValue.Axis,
                      Flip: TagActListValue.Flip,
                      Value: TagActListValue.Value,
                      ValueFactor: TagActListValue.ValueFactor
                    })
                  } else {
                    editor.TagActList[TagActListValue.TagID] = []
                    editor.TagActList[TagActListValue.TagID].push({
                      HandlerType: TagActListValue.HandlerType,
                      HandlerCode: TagActListValue.HandlerCode,
                      HandlerValue: TagActListValue.HandlerValue,
                      TagValue: TagActListValue.TagValue,
                      JointType: TagActListValue.JointType,
                      Axis: TagActListValue.Axis,
                      Flip: TagActListValue.Flip,
                      Value: TagActListValue.Value,
                      ValueFactor: TagActListValue.ValueFactor
                    })
                  }
                })
              }
            })
          })
          resolve(1)
        })
      })
      const P2 = new Promise(function(resolve, reject) {
        axios({
          method: 'get',
          url: './DMT_WEB/models/RobotPlan_Process.json'
        }).then((res) => {
          editor.sceneConfig = res.data.sceneConfig // 场景配置
          editor.attachments = res.data.attachments // 附加物体
          editor.resources = res.data.resources // 场景模型资源
          editor.resourcesTree = res.data.resourcesTree // 模型树
          editor.cameraState = res.data.cameraState // 场景相机位置
          editor.ProjectCode = res.data.ProjectCode // 项目代码
          editor.resourcesTree.forEach(res => {
            if (res.treeType === 'OriginModel') {
              ModelList.push(res.name)
            }
          })
          editor.resources.forEach(res => {
            editor.objectIdUUidMap.set(res.id, res)
          })
          editor.attachments.forEach(res => {
            editor.attachList.set(res.RootId, res.attachList)
          })
          resolve(1)
        }).catch((error) => { console.log(error) })
      })
      Promise.all([P1, P2]).then(res => {
        this.init()
        // this.getCameraData()
      })
    },
    /**
       * 设定模型初始状态
       */
    setModelSates() {
      return
      // 模型的显示隐藏
      editor.resourcesTree.forEach(res => {
        if (res.visible === '0') {
          if (editor.getObjectById(res.id)) {
            editor.getObjectById(res.id).visible = !!(parseInt(res.visible))
          }
        }
      })
      const treeRes = editor.resourcesTree
      for (const treeResValue of treeRes) {
        if (treeResValue.treeType !== 'folder') {
          const currentModel = editor.getObjectById(treeResValue.id)

          if (Object.hasOwnProperty.call(treeResValue, 'WireFrame') && treeResValue.WireFrame) {
            editor.setModelWireFrame(currentModel, true)
          }
          if (Object.hasOwnProperty.call(treeResValue, 'transParent') && treeResValue.transParent) {
            editor.setTransparent(treeResValue.id, 0.3)
          }
          if (currentModel) currentModel.visible = !!parseInt(treeResValue.visible)
        }
      }
    },

    /**
       * 设定场景初始状态
       * @param type
       */
    setSceneStates(type) {
      switch (type) {
        case '0':
          scene.background = new THREE.Color('#dcdcdc')
          break
        case '1':
          scene.background = new THREE.Color(editor.sceneConfig.RenderColorModel.color)
          break
        case '2':
          if (editor.sceneConfig.RenderColorModel.image === '') {
            editor.scene.background = new THREE.Color(editor.sceneConfig.RenderColorModel.color)
            return
          }
          new THREE.TextureLoader().load(editor.sceneConfig.RenderColorModel.image === '', function(texture) {
            scene.background = texture
            texture.dispose()
          })
          break
        default:
          scene.background = new THREE.Color('#dcdcdc')
          break
      }
    },
    /**
       * 初始化场景信息
       */
    init() {
      const scope = this
      container = document.getElementById('viewPort')
      clock = new THREE.Clock()
      scene = new THREE.Scene()
      editor.scene = scene
      const width = container.clientWidth
      const height = container.clientHeight
      const k = width / height
      const s = 100
      camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 0.001, 2000)
      camera.position.set(editor.cameraPosition, editor.cameraPosition, editor.cameraPosition)
      camera.lookAt(scene.position)
      camera.up.x = 0
      camera.up.y = 0
      camera.up.z = 1
      scene.add(camera)
      editor.camera = camera
      axesHelper = new THREE.AxesHelper(1)
      scene.add(axesHelper)

      renderer = new THREE.WebGLRenderer({ antialias: true })
      renderer.setPixelRatio(window.devicePixelRatio)
      renderer.setSize(container.clientWidth, container.clientHeight)
      renderer.setClearColor(0x666666, 0)
      renderer.toneMapping = THREE.ACESFilmicToneMapping
      renderer.toneMappingExposure = 0.8
      renderer.shadowMap.enabled = true
      renderer.hadowMapEnabled = true
      renderer.shadowMap.type = THREE.PCFSoftShadowMap
      renderer.outputColorSpace = THREE.SRGBColorSpace
      renderer.textureEncoding = THREE.sRGBEncoding

      // editor.WeldLight1 = this.drawWeldLight()
      // editor.WeldLight2 = this.drawWeldLight()

      const pmremGenerator = new THREE.PMREMGenerator(renderer)
      pmremGenerator.compileEquirectangularShader()
      const loader = new GLTFLoader().setPath('./DMT_WEB/models/')
      const dracoLoader = new DRACOLoader()
      new RGBELoader().setDataType(THREE.FloatType)
        .load('./DMT_WEB/assets/venice_sunset_1k.hdr', function(texture) {
          const envMap = pmremGenerator.fromEquirectangular(texture).texture
          console.log(envMap)
          envMap.flipY = true
          scene.environment = envMap
          scene.background = new THREE.Color('#081f48')
          texture.dispose()
          pmremGenerator.dispose()
        })
      this.setSceneStates(editor.sceneConfig.RenderColorModel.model)
      dracoLoader.setDecoderPath('./DMT_WEB/draco/')
      loader.setDRACOLoader(dracoLoader)
      editor.getObjectById = function(ModelId) {
        let currentModel = null
        const currentModelData = editor.objectIdSet.get(ModelId)
        if (currentModelData) currentModel = currentModelData.object
        return currentModel
      }
      editor.solveAttachModel = function(ModelId, attach = true) {
      }
      editor.removeObject = function(object) {
        if (object === null) return
        if (object.parent === null) return
        object.parent.remove(object)
      }
      /**
       * 设置模型线框
       * @param currentObject
       * @param WireframeValue
       */
      editor.setModelWireFrame = function(currentObject, WireframeValue) {
        currentObject.traverse(obj => {
          if (obj instanceof THREE.Mesh) {
            obj.material = editor.objMaterial.get(obj.id).clone()
            obj.material['wireframe'] = WireframeValue
            obj.material.needsUpdate = true
          }
        })
      }

      /**
       * 模型透明
       * @param ModelId
       * @param Opacity 透明度
       */
      editor.setTransparent = function(ModelId, Opacity = 0.3) {
        new Promise((resolve, reject) => {
          const TransModel = editor.getObjectById(ModelId)
          if (!TransModel) {
            console.warn('模型不存在！（setTransparent）')
            reject(false)
          } else {
            TransModel.traverse(obj => {
              if (obj.material) {
                const material_yuan = editor.objMaterial.get(obj.id).clone()
                obj.material = material_yuan
                if (Opacity !== 1) {
                  obj.material = new THREE.MeshStandardMaterial({
                    color: material_yuan.color,
                    side: 2,
                    transparent: true,
                    opacity: Opacity
                  })
                }
              }
            })
            resolve(true)
          }
        })
      }

      editor.drawPartTextInfo = function(ModelId, TagValue) {
        new Promise((resolve, reject) => {
          let LabelInfo = editor.ModelLabelList.get(ModelId)
          const TransModel = editor.getObjectById(ModelId)
          if (TransModel) {
            if (!LabelInfo) {
              LabelInfo = {
                position: scope.getDeltaPosition(new THREE.Vector3(), { x: 0, y: 0, z: 0.5 }),
                label: TagValue,
                object: null
              }
              editor.ModelLabelList.set(ModelId, LabelInfo)
            }
            if (LabelInfo.object) editor.removeObject(LabelInfo.object)
            if (TransModel.visible) {
              LabelInfo.label = TagValue.replaceAll('\\n', '\n')
              const spriteLabel = new SpriteText(LabelInfo.label, 0.2, '#000000')
              // spriteLabel.borderColor = '#30ff00'
              // spriteLabel.borderWidth = [0.3, 0.2]
              spriteLabel.backgroundColor = 'rgb(255,183,0)'
              spriteLabel.position.copy(LabelInfo.position)
              LabelInfo.object = spriteLabel
              TransModel.add(spriteLabel)
            }
          }
        })
      }
      container.appendChild(renderer.domElement)
      container.addEventListener('dblclick', this.ondblclick, false)
      editor.cameraControls = new DmtControl(editor.camera, renderer.domElement)
      editor.cameraControls.listenToKeyEvents(window) // optional
      editor.cameraControls.update()

      const light1 = new THREE.AmbientLight(new THREE.Color('#ffffff'), 1)
      light1.name = 'ambient_light'
      editor.cameraControls.object.add(light1)

      const light2 = new THREE.DirectionalLight(new THREE.Color('#ffffff'), 1)
      light2.position.set(0.5, 0, 0.866) // ~60º
      light2.name = 'main_light'
      editor.cameraControls.object.add(light2)

      // document.getElementById('orientCubeWrapperDiv').style.display = 'none'
      window.addEventListener('resize', this.onWindowResize, false)
      const encoding = THREE.sRGBEncoding
      editor.cameraControls.resetState(editor.cameraState.target, editor.cameraState.position, editor.cameraState.zoom0)
      // 加载模型
      for (let i = 0; i < ModelList.length; i++) {
        loader.load(ModelList[i] + '.glb', function(gltf) {
          const currentModel = gltf.scene.children[0]
          if (currentModel.name === 'Plane') {
            Plane = currentModel
          }
          currentModel.traverse(child => {
            if (child['material']) {
              child['material'].metalness = 1
              if (child['material'].map) child['material'].map.encoding = encoding
              if (child['material'].emissiveMap) child['material'].emissiveMap.encoding = encoding
              if (child['material'].map || child['material'].emissiveMap) child['material'].needsUpdate = true
              editor.objMaterial.set(child.id, child['material'])
            }
          })
          scene.add(currentModel)
          scope.setObjectByConfig(currentModel)
          ModelListId.push(gltf.scene.id)
          modelCount += 1
          scope.$refs.modelProcess.innerText = '正在加载模型' + (modelCount / ModelList.length * 100).toFixed(2) + '%'
          if (modelCount === ModelList.length) {
            scope.$refs.modelProcess.style.display = 'none'
            scope.lookObject(scene)
            scope.setModelSates()
            scope.connectService()
          }
        }, (xhr) => {
          // eslint-disable-next-line handle-callback-err
        }, (error) => {
          modelCount += 1
          console.log(`加载模型${ModelList[i].ModelName}出错!`)
          if (modelCount === ModelList.length) {
            scope.$refs.modelProcess.style.display = 'none'
            scope.lookObject(scene)
            scope.setModelSates()
            scope.connectService()
          }
        })
      }
      this.animate()
    },

    /**
       * 自适应窗口尺寸
       */
    onWindowResize() {
      renderer.setSize(container.clientWidth, container.clientHeight)
      const s = 100; const k = container.clientWidth / container.clientHeight // 窗口宽高比
      camera.left = -s * k
      camera.right = s * k
      camera.top = s
      camera.bottom = -s
      camera.updateProjectionMatrix()
      this.render()
    },
    /**
       * 根据有配置文件设置模型初始化属性
       * @param object
       */
    setObjectByConfig(object) {
      const objectId = object.userData['ModelId']
      const objectResource = editor.objectIdUUidMap.get(objectId)
      if (objectResource) {
        object.position.copy(
          new THREE.Vector3(parseFloat(objectResource.location.position.x),
            parseFloat(objectResource.location.position.y),
            parseFloat(objectResource.location.position.z)
          ))
        object.quaternion.copy(
          new THREE.Quaternion(parseFloat(objectResource.location.quaternion.x),
            parseFloat(objectResource.location.quaternion.y),
            parseFloat(objectResource.location.quaternion.z),
            parseFloat(objectResource.location.quaternion.w)
          ))
        object.visible = Boolean(parseInt(objectResource.visible))
      }
    },
    /**
       * 渲染
       */
    animate() {
      this.render()
      requestAnimationFrame(this.animate)
      editor.attachList.forEach((attackList, ModelId) => {
        const ModelAttachParent = editor.getObjectById(ModelId)
        if (ModelAttachParent) {
          if (!ModelAttachParent.lastMatrixWorld.equals(ModelAttachParent.matrixWorld)) {
            for (const attackListElement of attackList) {
              const attachModel = editor.getObjectById(attackListElement.ModelId)
              if (attachModel) {
                const newMatrixWord = ModelAttachParent.matrixWorld.clone()
                const cubeTransWorld = newMatrixWord.clone().multiply(ModelAttachParent.lastMatrixWorld.clone().invert()).clone()
                const cube2OldWorld = attachModel.matrixWorld.clone()
                const cube2NewWorld = cubeTransWorld.clone().multiply(cube2OldWorld)
                const cube2ParentWorld = attachModel.parent.matrixWorld.clone()
                const cube2ParentNew = (cube2ParentWorld.invert()).multiply(cube2NewWorld)
                const position = new THREE.Vector3()
                const quaternion = new THREE.Quaternion()
                const scale = new THREE.Vector3()
                cube2ParentNew.decompose(position, quaternion, scale)
                attachModel.quaternion.copy(quaternion)
                attachModel.position.copy(position)
                attachModel.updateMatrixWorld()
              }
            }
            ModelAttachParent.lastMatrixWorld = ModelAttachParent.matrixWorld.clone()
          }
        }
      })
      TWEEN.update()
    },

    /**
     * 渲染
     */
    render() {
      renderer.render(scene, camera)
      this.sendCameraState(camera.zoom < editor.cameraStateZoom)
      this.updatePosition(editor.selected)
    },
    connectService() {
      switch (editor.connectType) {
        case 1:
          connect(editor)
          break
        case 2:
          connectMqtt(editor)
          break
        default:
          break
      }
    },
    // drawWeldLight() {
    //   const geometry = new THREE.BufferGeometry()
    //   const vertices = []
    //   const textureLoader = new THREE.TextureLoader()
    //   const sprite1 = textureLoader.load('./css/lensflare0.png')
    //   const x = 0
    //   const y = 0.3
    //   const z = -0.07
    //   const materials = []
    //   vertices.push(x, y, z)
    //   geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3))
    //   const parameters = [
    //     [[1.0, 1, 1], sprite1, 50]
    //   ]
    //   const sprite = parameters[ 0 ][ 1 ]
    //   const size = parameters[ 0 ][ 2 ]
    //
    //   materials[ 0 ] = new THREE.PointsMaterial({ size: size, map: sprite, blending: THREE.AdditiveBlending, depthTest: false, transparent: true })
    //   return new THREE.Points(geometry, materials[0])
    // },
    /**
       * 解析模型
       * @param object
       */
    lookObject(object) {
      object.traverse(function(child) {
        if (!child) return
        // 避免modelId重复
        if (Object.hasOwnProperty.call(child.userData, 'ModelId')) {
          if (editor.objectIdSet.has(child.userData['ModelId'])) {
            child.userData['ModelId'] = child.uuid
            editor.objectIdSet.set(child.uuid, {
              ModelId: child.id,
              Name: child.name,
              position: JSON.parse(JSON.stringify(child.position)),
              rotation: JSON.parse(JSON.stringify(child.rotation)),
              quaternion: JSON.parse(JSON.stringify(child.quaternion)),
              object: child,
              matrix: child.matrix.clone(),
              lastValue: null
            })
          } else {
            editor.objectIdSet.set(child.userData['ModelId'], {
              ModelId: child.id,
              Name: child.name,
              position: JSON.parse(JSON.stringify(child.position)),
              rotation: JSON.parse(JSON.stringify(child.rotation)),
              quaternion: JSON.parse(JSON.stringify(child.quaternion)),
              object: child,
              matrix: child.matrix.clone(),
              lastValue: null
            })
          }
        }
      })
      for (const robotListInfo in editor.robotList) {
        for (const info of editor.robotList[robotListInfo]) {
          info.object = editor.getObjectById(info.ModelId)
          info.matrix = info.object ? info.object.matrix.clone() : null
          info.lastValue = null
        }
      }
      object.traverse(function(child) {
        child.lastMatrixWorld = child.matrixWorld.clone()
      })
      window.editor = editor

      for (let i = 0; i < editor.resourcesTree.length; i++) {
        if (editor.resourcesTree[i].name.length > 2) {
          const currentModel = editor.getObjectById(editor.resourcesTree[i].id)
          if (currentModel) {
            this.treeData.push({
              id: editor.resourcesTree[i].id,
              label: editor.resourcesTree[i].name,
              userData: currentModel.userData,
              Model: currentModel,
              ModelId: currentModel.userData.ModelId
            })
          }
        }
      }
      this.treeData = this.sortChinese(this.treeData, 'label')
      for (let i = 0; i < this.treeData.length; i++) {
        console.log(this.treeData[i].ModelId, this.treeData[i].label)
      }
    },
    /**
     * 获取预置焦点
     */
    getCameraData() {
      var param = []
      param[0] = ['ProjectCode', editor.ProjectCode]
      var Data = this.CreateData('3', 'select * from dbo.[基础数据_焦点预置]', param)
      this.ExecDatabase(Data).then(response => {
        this.cameraData = response.data
      })
    },
    /**
     * 点击后 到达预置焦点
     */
    setViewCamera() {
      if (this.cameraData.length === 0) return
      const scope = this
      const viewOperation = document.getElementById('viewOperationParent')
      const viewOperationChild = document.getElementById('viewOperationChild')
      viewOperation.onmouseover = function() {
        viewOperationChild.style.display = 'block'
      }
      viewOperation.onmouseout = function() {
        viewOperationChild.style.display = 'none'
      }
      setTimeout(() => {
        for (const info of this.cameraData) {
          $('#cameraViewBtn' + info.焦点代码).on('click', function(e) {
            const data = JSON.parse(info.焦点位置)
            const target = data.target
            const position = data.position
            const zoom0 = data.zoom0
            const id = info.焦点代码
            $('#cameraViewBtn' + info.焦点代码).css({ 'background': '#00893d', 'color': '#fff' })
            editor.cameraControls.resetState(target, position, zoom0)
            for (const infoColor of scope.cameraData) {
              if (id !== infoColor.焦点代码) {
                $('#cameraViewBtn' + infoColor.焦点代码).css({ 'background': '#fff', 'color': '#606266' })
              }
            }
          })
        }
      }, 1000)
    },
    getMousePosition(dom, x, y) {
      const rect = dom.getBoundingClientRect()
      return [(x - rect.left) / rect.width, (y - rect.top) / rect.height]
    },
    ondblclick(event) {
      try {
        const array = this.getMousePosition(container, event.clientX, event.clientY)
        onUpPosition.fromArray(array)
        let intersects = this.getIntersects(onUpPosition, editor.scene.children)
        intersects = intersects.filter(res => {
          return res.object.visible
        })
        if (intersects.length > 0) {
          const rootObjId = intersects[0].object.userData['RootId']
          editor.selected = editor.getObjectById(rootObjId)
          editor.dispatchEvent({
            type: 'dmtModelDBClick',
            ModelId: editor.selected.userData['ModelId'],
            ModelName: editor.selected.userData['name']
          })
        } else {
          editor.selected = null
          editor.dispatchEvent({
            type: 'dmtModelDBClick',
            ModelId: '',
            ModelName: ''
          })
        }
      } catch (e) {
        editor.selected = null
        editor.dispatchEvent({
          type: 'dmtModelDBClick',
          ModelId: '',
          ModelName: ''
        })
      }
    },
    getIntersects(point, objects) {
      mouse.set((point.x * 2) - 1, -(point.y * 2) + 1)
      raycaster.setFromCamera(mouse, camera)
      return raycaster.intersectObjects(objects, true)
    },
    sendCameraState(state) {
      this.$emit('changeCameraState', state)// 自定义事件  传递值“子向父组件传值”
    },
    updatePosition() {
      if (editor.selected) {
        const targetPosition = editor.selected.getWorldPosition(new THREE.Vector3()).clone().project(camera)
        const halfWidth = window.innerWidth / 2
        const halfHeight = window.innerHeight / 2
        const position = {
          left: targetPosition.x * halfWidth + halfWidth - 200,
          top: -targetPosition.y * halfHeight + halfHeight - 500
        }
        this.$emit('clickModel', editor.selected, position)// 自定义事件  传递值“子向父组件传值”
      }
    },
    getDeltaPosition(positionModel, positionLabel) {
      return new THREE.Vector3((positionLabel.x - positionModel.x), (positionLabel.y - positionModel.y), (positionLabel.z - positionModel.z))
    }
  }
}
</script>
<style>
html{
  height: 99%;
}
body {
  height: 100%;
}
#app {
  height: 100%;
}
</style>
