<template>
  <!-- <div ref="containerRef" class="container" /> -->

  <el-row class="main-container">
    <el-col :span="10" style="height: 100%">
      <div ref="containerRef" class="container" />
    </el-col>
    <el-col :span="14" class="info-col">
      <el-card class="card" :body-style="{ padding: '10px' }">
        <h2 class="cardHead">单个装置基本信息</h2>

        <div class="cardBody">
          <el-row :gutter="0" class="info-row">
            <el-col :span="8">厂家：</el-col>
            <el-col :span="16">
              <el-tag type="primary">海湾公司</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">投运日期</el-col>
            <el-col :span="16">
              <el-tag type="primary">2014-08-08</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">电源电压：</el-col>
            <el-col :span="16">
              <el-tag type="primary">220V AC</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">布设位置</el-col>
            <el-col :span="16">
              <el-tag type="primary">35kV高压室</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">供电电压</el-col>
            <el-col :span="16">
              <el-tag type="primary">18-30V DC</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">输出电流：</el-col>
            <el-col :span="16">
              <el-tag type="primary">5A</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">IP等级</el-col>
            <el-col :span="16">
              <el-tag type="primary">IP30</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">相对湿度：</el-col>
            <el-col :span="16">
              <el-tag type="primary">5% ~ 95%</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">接线方式</el-col>
            <el-col :span="16">
              <el-tag type="primary">两线制(L+、L-)</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">尺寸(长x高x宽)</el-col>
            <el-col :span="16">
              <el-tag type="primary">350mm x 225mm x 125mm</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">报警灵敏度范围</el-col>
            <el-col :span="16">
              <el-tag type="primary">0.005% 至 20%obs/m</el-tag>
            </el-col>
          </el-row>

          <el-row :gutter="0" class="info-row">
            <el-col :span="8">运行条件</el-col>
            <el-col :span="16">
              <el-tag ref="conditionTagRef" type="primary" @mouseenter="checkOverflow">
                探测器环境(-5°C至45°C) / 采样空气(-20°C至60°C) / 湿度(5%至95%RH)
              </el-tag>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, nextTick } from 'vue';
import {
  AxesHelper,
  Color,
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
  AmbientLight,
  DirectionalLight,
  PointLight,
  MeshStandardMaterial,
  Vector2,
  Raycaster,
  CanvasTexture,
  SpriteMaterial,
  Sprite,
  Box3,
  Vector3,
  HemisphereLight
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GLTFLoader, GLTF } from 'three/examples/jsm/loaders/GLTFLoader';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';

const containerRef = ref<HTMLDivElement>();
const conditionTagRef = ref<any>();
const showTooltip = ref(false);

// 检查文本是否溢出
const checkOverflow = () => {
  nextTick(() => {
    if (conditionTagRef.value) {
      const element = conditionTagRef.value.$el || conditionTagRef.value;
      showTooltip.value = element.scrollWidth > element.clientWidth;
    }
  });
};

// 场景
const scene = new Scene();

// 创建摄像机
const camera = new PerspectiveCamera(
  45,
  containerRef.value?.clientWidth! / containerRef.value?.clientHeight!,
  0.1,
  1000
);
camera.position.set(-40, 20, 30);
camera.lookAt(scene.position);

// 渲染器
const renderer = new WebGLRenderer({
  antialias: true, // 启用抗锯齿
  alpha: true, // 启用透明背景
  preserveDrawingBuffer: true // 保持绘图缓冲区
});
renderer.setClearColor(new Color('#131519'));
renderer.setSize(containerRef.value?.clientWidth!, containerRef.value?.clientHeight!);
renderer.shadowMap.enabled = true;
renderer.setPixelRatio(window.devicePixelRatio || 1); // 设置像素比率

// 轨道摄像机
const orbitControls = new OrbitControls(camera, renderer.domElement);
orbitControls.autoRotate = false;
orbitControls.autoRotateSpeed = 5;
orbitControls.dampingFactor = 0.1;
orbitControls.enableDamping = true;
orbitControls.enableRotate = true;
orbitControls.minDistance = 10;
orbitControls.maxPolarAngle = Math.PI * 0.5;

// 物体
scene.add(new AxesHelper(20));

// 环境光：增强整体亮度
const ambientLight = new AmbientLight('#ffffff', 1.8); // 强度从 0.6 提高到 1.0
scene.add(ambientLight);

// 平行光
const directionalLight = new DirectionalLight('#ffffff', 1.8); // 强度从 0.2 提高到 0.8
scene.add(directionalLight);
directionalLight.position.set(20, 20, 10);

// // 点光源
const pointLight = new PointLight('#ffffff', 1.8, 1800); // 强度从 0.5 提高到 1.0
scene.add(pointLight);
pointLight.position.set(0, 40, 0);

// 创建一个悬浮的框
const canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
const ctx = canvas.getContext('2d');
if (ctx) {
  ctx.fillStyle = 'rgba(0,0,0,.7)';
  ctx.fillRect(0, 0, 200, 100);
  ctx.fillStyle = 'white';
  ctx.font = '21px 黑体';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('遥测：100111', 100, 30);
  ctx.fillText('温度：25℃', 90, 65);
}
const scaleFactor = 5;
const texture = new CanvasTexture(canvas);
const material = new SpriteMaterial({ map: texture });

const sprite1 = new Sprite(material);
sprite1.scale.set(scaleFactor, scaleFactor, scaleFactor);
sprite1.position.set(-9.644502679789724, 5.815449539931501 + 0.5, 21.66345220492572);

function animate() {
  requestAnimationFrame(animate);
  orbitControls.update();
  renderer.render(scene, camera);
}

let pitchObj = ref<any>();
let pitchMaterial = ref<any>();

// ResizeObserver 监听容器尺寸变化
let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  const container = containerRef.value!;
  container.appendChild(renderer.domElement);

  // 初始化摄像机和渲染器尺寸
  camera.aspect = container.clientWidth / container.clientHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(container.clientWidth, container.clientHeight);

  // 监听容器尺寸变化
  resizeObserver = new ResizeObserver(() => {
    camera.aspect = container.clientWidth / container.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(container.clientWidth, container.clientHeight);
  });
  resizeObserver.observe(container);

  const loader = new GLTFLoader();
  const dracoLoader = new DRACOLoader();
  loader.setDRACOLoader(dracoLoader);
  loader.load('/models/smokeSiren/smokeSiren.glb', (gltf: GLTF) => {
    console.log('3D:', gltf);

    // 计算模型的边界框
    // const box = new Box3().setFromObject(gltf.scene);
    // const size = box.getSize(new Vector3());
    // const center = box.getCenter(new Vector3());

    // console.log('模型边界框信息:');
    // console.log('最小点:', box.min);
    // console.log('最大点:', box.max);
    // console.log('中心点坐标:', center);
    // console.log('尺寸 (宽×高×深):', size);
    // console.log('宽度 (X轴):', size.x);
    // console.log('高度 (Y轴):', size.y);
    // console.log('深度 (Z轴):', size.z);

    // const sprite = new Sprite(material);
    // sprite.scale.set(scaleFactor, scaleFactor, scaleFactor);
    // sprite.position.set(size.x / 2 - 5, size.y / 2 - 5, size.z / 2);
    // scene.add(sprite);

    gltf.scene.scale.set(1, 1, 1);
    scene.add(gltf.scene);
  });

  // 创建射线检测器
  const raycaster = new Raycaster();
  const mouse = new Vector2();

  // 添加点击事件监听
  renderer.domElement.addEventListener('mousedown', (event: MouseEvent) => {
    const rect = container.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    mouse.x = (x / container.clientWidth) * 2 - 1;
    mouse.y = -(y / container.clientHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(scene.children, true);
  });

  animate();
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
});
</script>

<style scoped>
.main-container {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  height: 100%;
  position: relative; /* 确保定位上下文 */
}

.info-col {
  height: 100%;
  overflow: hidden;
}

.card {
  height: 100%;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

.card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.cardHead {
  margin: 0 0 15px 0;
  padding: 0;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  color: #ffffff;
}

.cardBody {
  font-size: 12px;
}

.info-row {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.info-row :deep(.el-col) {
  display: flex;
  align-items: center;
}

.info-row :deep(.el-tag) {
  /* width: 100%; */
  justify-content: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  display: flex;
  align-items: center;
  height: 100%;
}

.ellipsis-tag {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  height: 100%;
}

.condition-tag {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>
