<template>
  <div>
    <div class="allShow">
      <div class="title">
        <span class="title-text">{{ Title }}</span>
      </div>
      <!--       <div class="user-info-position">
        <UserInfo @logout="handleLogout" />
      </div> -->
      <div class="dmt-container">
        <div class="dmt-inner-container">
          <div class="dmt-content">
            <d-m-t v-if="showDmtCom" ref="dmtCom" @changeCameraState="changeCameraState" containerHeight="100%"
              containerWidth="100%" />
          </div>
        </div>
        <div class="dmt-tip">
          注：旋转：单指拖动；平移：双指同时拖动；缩放：双指捏合或张开
        </div>
      </div>

      <div class="components-column">
        <!-- 按钮栏 -->
        <div class="component-box" style="height: 60px; padding: 5px 0px">
          <BoxBorders />
          <ControlButton :drawing-visible="drawingDialogVisible" @watch-paper="handleWatchPaper" />
        </div>

        <!-- 数据输入框 -->
        <div class="component-box" style="height: 80px">
          <BoxBorders />
          <div class="data-box-container">
            <div class="data-box-text">
              <span class="data-box-text-title"> 订单号 </span>
              <input class="data-box-text-value editable-input" v-model="orderNum" @blur="saveData"
                @keyup.enter="saveData" />
            </div>
            <div class="data-box-text">
              <span class="data-box-text-title"> 机型号 </span>
              <input class="data-box-text-value editable-input" v-model="machineModel" @blur="saveData"
                @keyup.enter="saveData" />
            </div>
            <div class="data-box-text">
              <span class="data-box-text-title"> 数量 </span>
              <input class="data-box-text-value editable-input" v-model="number" @blur="saveData"
                @keyup.enter="saveData" />
            </div>
          </div>
        </div>

        <!-- andon -->
        <div class="component-box" style="height: 150px">
          <BoxBorders />
          <Andon mode="portrait" />
        </div>

        <!-- 伺服负载曲线 -->
        <div class="component-box" style="height: 230px;">
          <BoxBorders />
          <ServoLoadCurve />
        </div>

        <!-- 刀具使用时长 -->
        <div class="component-box">
          <BoxBorders />
          <ToolUseTime />
        </div>

        <!-- 零部件只能预测性维护 -->
        <div class="component-box">
          <BoxBorders />
          <PartMaintenance />
        </div>

        <!-- 7日工作时长统计 -->
        <div class="component-box">
          <BoxBorders />
          <SenveWorkTime />
        </div>

        <!-- 实时状态 -->
        <div class="component-box" style="height: 120px">
          <BoxBorders />
          <NowStatus />
        </div>

        <!-- OEE分析 -->
        <div class="component-box" style="height: 170px">
          <BoxBorders />
          <OEEAnalysis />
        </div>

        <!-- 质量管理 -->
        <div class="component-box" style="height: 320px">
          <BoxBorders />
          <QualityManagement />
        </div>

        <!-- 报警 -->
        <div class="component-box" style="height: 200px">
          <BoxBorders />
          <Warning />
        </div>

        <!-- 设备运行履历 -->
        <div class="component-box" style="height: 160px;">
          <BoxBorders />
          <EquipmentRuntimeHistory />
        </div>
      </div>
    </div>

    <!-- 图纸查看器 (支持缩放、拖拽、旋转) -->
    <el-image-viewer
      v-if="drawingDialogVisible"
      :url-list="drawingImages"
      :initial-index="0"
      :zoom-rate="1.2"
      :min-scale="0.2"
      :max-scale="7"
      @close="handleCloseDrawing"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 组件导入
import ControlButton from '@/components/layout/ControlButton.vue'
import ServoLoadCurve from '@/components/layout/ServoLoadCurve.vue'
import ToolUseTime from '@/components/layout/ToolUseTime.vue'
import PartMaintenance from '@/components/layout/PartMaintenance.vue'
import SenveWorkTime from '@/components/layout/SenveWorkTime.vue'
import NowStatus from '@/components/layout/NowStatus.vue'
import EquipmentRuntimeHistory from '@/components/layout/EquipmentRuntimeHistory.vue'
import Warning from '@/components/layout/Warning.vue'
import DMT from '@/components/DMT/index.vue'
import OEEAnalysis from '@/components/layout/OEEAnalysis.vue'
import QualityManagement from '@/components/layout/QualityManagement.vue'
import Andon from '@/components/layout/Andon.vue'
import UserInfo from '@/components/layout/UserInfo.vue'
import { throttle } from '@/utils/tool'
import BoxBorders from '@/components/layout/BoxBorders.vue'
const router = useRouter()

// 响应式数据
const Title = ref('')
const drawingDialogVisible = ref(false)
const drawingImages = ['/PNG/图纸.png']  // 图纸图片列表
const hour = ref('00')
const minute = ref('00')
const second = ref('00')
const year = ref('1900')
const month = ref('01')
const day = ref('01')
const week = ref('一')
const orderNum = ref('10007801')
const machineModel = ref('20-021')
const number = ref('100')

// 添加一个状态来跟踪DMT是否应该显示
const dmtShouldShow = ref(true)

const dmtCom = ref(null)
const showDmtCom = ref(true) // 设置为 true，始终显示

// 计算属性
const formattedTime = computed(() => `${hour.value}:${minute.value}:${second.value}`)
const formattedDate = computed(() => `${year.value}/${month.value}/${day.value}`)

// 方法
const changeCameraState = (state: boolean) => {
  // 摄像头状态改变逻辑
}

const updateTime = () => {
  const now = new Date()
  hour.value = String(now.getHours()).padStart(2, '0')
  minute.value = String(now.getMinutes()).padStart(2, '0')
  second.value = String(now.getSeconds()).padStart(2, '0')
  year.value = String(now.getFullYear())
  month.value = String(now.getMonth() + 1).padStart(2, '0')
  day.value = String(now.getDate()).padStart(2, '0')

  const weeks = ['日', '一', '二', '三', '四', '五', '六']
  week.value = weeks[now.getDay()] ?? '一'
}
// 修改：添加对图纸对话框的监听
watch(drawingDialogVisible, (newVal) => {
  if (!newVal) {
    // 对话框关闭后，确保DMT保持显示
    setTimeout(() => {
      showDmtCom.value = true
    }, 100)
  }
})
const handleCloseDrawing = () => {
  drawingDialogVisible.value = false
  // 确保DMT组件不会被重新加载
  if (!showDmtCom.value) {
    showDmtCom.value = true
  }
}

const saveData = () => {
  const dataToSave = {
    orderNum: orderNum.value,
    machineModel: machineModel.value,
    number: number.value,
  }

  try {
    localStorage.setItem('machineData', JSON.stringify(dataToSave))
  } catch (e) {
    console.error('保存数据失败:', e)
  }
}

const loadSavedData = () => {
  try {
    const savedData = localStorage.getItem('machineData')
    if (savedData) {
      const data = JSON.parse(savedData)
      orderNum.value = data.orderNum || orderNum.value
      machineModel.value = data.machineModel || machineModel.value
      number.value = data.number || number.value
    }
  } catch (e) {
    console.error('加载保存数据失败:', e)
  }
}

// 按钮事件处理函数
const handleOpenDoor = () => {
  console.log('开门按钮点击 - Portrait')
  // 可以在这里添加额外的开门后逻辑
}

const handleCloseDoor = () => {
  console.log('关门按钮点击 - Portrait')
  // 可以在这里添加额外的关门后逻辑
}

// 修改：优化查看图纸方法
const handleWatchPaper = () => {
  console.log('查看图纸按钮点击 - Portrait')

  // 先设置对话框可见
  drawingDialogVisible.value = true

  // 不操作DMT组件，让它保持原状
  // 只是添加一个短暂延迟确保UI更新
  setTimeout(() => {
    // 这里可以添加其他逻辑，但不涉及DMT组件
  }, 50)
}
// 修改：优化关闭图纸方法
const handleCloseDrawingDialog = () => {
  console.log('关闭图纸对话框 - Portrait')
  drawingDialogVisible.value = false
  // 不操作DMT组件状态
}

// 修改：优化退出登录方法
const handleLogout = () => {
  console.log('退出账号按钮点击 - Portrait')

  // 先清理DMT资源
  if (dmtCom.value && dmtCom.value.disposeThreeResources) {
    dmtCom.value.disposeThreeResources()
  }

  // 设置状态为false
  showDmtCom.value = false

  localStorage.removeItem('isAuthenticated')
  router.push('/')
}

// 方向变化处理
const handleOrientationChange = () => {
  const width = window.innerWidth
  const height = window.innerHeight
  const currentRoute = router.currentRoute.value.name
  console.log('方向变化处理 - Portrait')

  // 保存DMT组件的状态
  const wasDmtVisible = showDmtCom.value

  // 如果方向不匹配，自动跳转到正确页面
  if (width > height && currentRoute !== 'Landscape') {
    router.push({ name: 'Landscape' })
  } else if (width <= height && currentRoute !== 'Portrait') {
    router.push({ name: 'Portrait' })
  }

  // 恢复DMT组件状态
  setTimeout(() => {
    if (wasDmtVisible) {
      showDmtCom.value = true
    }
  }, 100)
}


// 生命周期
onMounted(() => {
  try {
    Title.value = (window as any).dt_Config?.topBoxTitle
    loadSavedData()

    const timer = setInterval(updateTime, 1000)
    updateTime()
    handleOrientationChange()

    // 确保DMT组件显示
    showDmtCom.value = true

    // 创建节流版本
    const throttledOrientationChange = throttle(function () {
      handleOrientationChange()
    }, 500)
    window.addEventListener('resize', throttledOrientationChange)

    return () => {
      clearInterval(timer)
      window.removeEventListener('resize', throttledOrientationChange)
    }
  } catch (error) {
    console.error('组件挂载错误:', error)
  }
})

onUnmounted(() => {
  // MQTT 连接现在由 ControlButton 组件自己管理，无需在此断开
})
</script>

<style>
body {
  margin: 0;
  padding: 0;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #0e3261ff;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: rgb(10, 35, 82);
}

::-webkit-scrollbar-button {
  display: none;
}

::-webkit-scrollbar-corner {
  background: #dedede;
}
</style>

<style scoped="scoped">
/* 添加样式确保对话框不影响DMT */
:deep(.el-dialog) {
  position: absolute !important;
  z-index: 2000 !important;
}

:deep(.el-dialog__wrapper) {
  position: absolute !important;
  z-index: 2000 !important;
}

.allShow {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
  font-family:
    'Microsoft YaHei', 微软雅黑, 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-image: url('/PNG/背景.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
}

.user-info-position {
  position: absolute;
  top: 40px;
  left: 20px;
  z-index: 1000;
}

.title {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
}

.title-text {
  font-size: 1.5rem;
  text-align: center;
  letter-spacing: 2px;
  font-weight: bolder;
  background: linear-gradient(to bottom, white, #3c9fc0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  color: transparent;
}

.dmt-container {
  position: relative;
  height: 600px;
  margin: 10px;
}

.dmt-inner-container {
  height: 100%;
  width: 100%;
  position: absolute;
}

.dmt-content {
  width: 100%;
  height: 100%;
  filter: blur(10);
  z-index: 999;
}

.components-column {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin: 10px;
}

.component-box {
  position: relative;
  width: 100%;
  height: 300px;
  -webkit-box-shadow: rgb(24, 78, 135) 0 0 10px;
  -moz-box-shadow: rgb(24, 78, 135) 0 0 10px;
  box-shadow: inset 0 0 30px rgb(24, 78, 135);
}


.data-box-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.data-box-text {
  font-size: 12px;
  font-weight: bolder;
  text-align: center;
  color: white;
  margin: 5px;
  border: 1px solid #0070c0;
  padding: 8px;
  flex: 1;
}

.data-box-text-title {
  font-size: 14px;
  display: block;
  margin-bottom: 5px;
}

.data-box-text-value {
  font-size: 16px;
}

.editable-input {
  background: transparent;
  border: none;
  color: white;
  font-size: 16px;
  font-weight: bolder;
  text-align: center;
  width: 100px;
  outline: none;
  padding: 0;
  margin: 0;
  cursor: pointer;
  color: #409eff;
}

.editable-input:focus {
  border: 1px solid #0070c0;
  border-radius: 4px;
}

.drawing-dialog-content {
  text-align: center;
  width: 100%;
  height: 40vh;
  overflow: auto;
}

.drawing-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .allShow {
    transform: none !important;
    position: relative !important;
    left: 0 !important;
    top: 0 !important;
    width: 100vw !important;
    min-height: 100vh !important;
    height: auto !important;
  }

  .components-column {
    margin: 5px;
  }

  .component-box {
    height: 250px;
  }

  .dmt-container {
    height: 300px;
  }
}

@media (max-width: 480px) {
  .title-text {
    font-size: 1.2rem;
  }

  .component-box {
    height: 220px;
  }

  .dmt-container {
    height: 250px;
  }
}

.dmt-tip {
  position: absolute;
  bottom: -5px;
  right: 5px;
  font-size: 12px;
  color: #ffffff;
  opacity: 0.7;
  z-index: 1000;
}
</style>
