<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1450px">
    <div v-loading="formLoading" style="min-width: 1400px; height: 600px; overflow: auto">
      <!-- 第一行：设备封面和基本信息 -->
      <div class="header-section">
        <div class="cover-container">
          <el-image
            :src="formData.deviceCover"
            fit="cover"
            class="device-cover"
            :preview-src-list="[formData.deviceCover]"
            preview-teleported
          />
        </div>
        <div class="basic-info">
          <div class="info-row">
            <span class="label">设备名称：</span>
            <span class="value">{{ formData.deviceName || '' }}</span>
          </div>
          <div class="info-row">
            <span class="label">设备编码：</span>
            <span class="value">{{ formData.deviceNumber || '' }}</span>
          </div>
          <div class="info-row">
            <span class="label">负责人：</span>
            <span class="value">{{ formData.responsibleName || '' }}</span>
          </div>
          <div class="info-row">
            <span class="label">部门名称：</span>
            <span class="value">{{ formData.deviceDeptName || '' }}</span>
          </div>
          <div class="info-row">
            <span class="label">设备位置：</span>
            <span class="value">{{ formData.usageLocationName || '' }}</span>
          </div>
          <div class="info-row">
            <span class="label">设备状态：</span>
            <span class="value">{{
              getDictLabel(DICT_TYPE.DEVICE_STATUS, formData.deviceStatus) || ''
            }}</span>
          </div>
          <div class="info-row">
            <span class="label">计量设备：</span>
            <span class="value">{{ formData.measurementNumber ? '是' : '否' }}</span>
          </div>
          <div class="info-row">
            <span class="label">计量编号：</span>
            <span class="value">{{ formData.measurementNumber || '' }}</span>
          </div>
        </div>
      </div>

      <!-- 第二行：选项卡 -->
      <div class="tab-section">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic" />
          <el-tab-pane label="资料" name="documents" />
          <el-tab-pane label="维修" name="maintenance" />
          <el-tab-pane label="保养" name="upkeep" />
        </el-tabs>
      </div>

      <!-- 基本信息选项卡内容 -->
      <div v-if="activeTab === 'basic'">
        <!-- 设备信息 -->
        <div class="detail-section">
          <div class="section-title">设备信息</div>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="资产编号">{{
              formData.assetNumber || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="序列号">{{
              formData.serialNumber || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="类别">{{
              formData.deviceCategoryName || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="设备来源">{{
              getDictLabel(DICT_TYPE.DEVICE_SOURCE, formData.deviceSource) || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="使用状态">{{
              getDictLabel(DICT_TYPE.USAGE_STATUS, formData.usageStatus) || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="设备等级">{{
              getDictLabel(DICT_TYPE.DEVICE_LEVEL, formData.deviceLevel) || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="设备类型">{{
              formData.deviceCategoryName || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="供应商编码">{{
              formData.supplierCode || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="供应商名称">{{
              formData.supplierName || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="品牌">{{ formData.brand || '' }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{
              formData.specificationModel || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="生产编号">{{
              formData.productionNumber || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="购置日期">{{
              formatDate(formData.purchaseDate) || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="采购金额">{{
              formData.purchaseAmount || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="入账方式">{{
              getDictLabel(DICT_TYPE.ACCOUNTING_METHOD, formData.accountingMethod) || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="启用日期">{{
              formatDate(formData.commissioningDate) || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="保修期至">{{
              formData.warrantyPeriod || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="预计报废日期">{{
              formatDate(formData.scrapDate) || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="技术参数" :span="3">{{
              formData.technicalParameters || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="单位">{{ formData.unit || '' }}</el-descriptions-item>
            <el-descriptions-item label="功率">{{ formData.power || '' }}</el-descriptions-item>

            <el-descriptions-item label="重量">{{ formData.weight || '' }}</el-descriptions-item>
            <el-descriptions-item label="体积">{{ formData.volume || '' }}</el-descriptions-item>
            <el-descriptions-item label="温度">{{
              formData.temperature || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="湿度">{{ formData.humidity || '' }}</el-descriptions-item>
            <!--            <el-descriptions-item label="电子标签码">{{ formData.electronicTagCode || '' }}</el-descriptions-item>-->
            <el-descriptions-item label="备注" :span="3">{{
              formData.remark || ''
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 计量信息 -->
        <div class="detail-section" v-if="formData.measurementNumber">
          <div class="section-title">计量信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="计量编号">{{
              measurementInfo.measurementNumber || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="计量范围">{{
              measurementInfo.measurementRange || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="允许误差">{{
              measurementInfo.allowableError || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="计量点位">{{
              measurementInfo.measurementPoint || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="管理等级">{{
              measurementInfo.manageLevel || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="仪器精度">{{
              measurementInfo.instrumentPrecision || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="计量方式">{{
              measurementInfo.measurementMethod || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="上次计量日期">{{
              formatDate(measurementInfo.lastMeasurementDate) || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="下次计量日期">{{
              formatDate(measurementInfo.nextMeasurementDate) || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="计量周期">{{
              measurementInfo.measurementCycle || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="提醒时间">{{
              measurementInfo.reminderTime || ''
            }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{
              measurementInfo.responsiblePerson || ''
            }}</el-descriptions-item>

            <el-descriptions-item label="说明" :span="2">{{
              measurementInfo.description || ''
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 设备图片 -->
        <div class="detail-section" v-if="deviceImgList && deviceImgList.length > 0">
          <div class="section-title">设备图片</div>
          <div class="image-gallery">
            <el-image
              v-for="(img, index) in deviceImgList"
              :key="index"
              :src="img"
              :preview-src-list="deviceImgList"
              :initial-index="index"
              fit="cover"
              class="gallery-image"
              preview-teleported
            />
          </div>
        </div>
      </div>

      <!-- 设备资料 -->
      <div v-if="activeTab === 'documents'">
        <div class="detail-section" v-if="deviceFilesList && deviceFilesList.length > 0">
          <el-table :data="deviceFilesList">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="资料分类" prop="model">
              <template #default="scope">
                {{ getDictLabel(DICT_TYPE.DEVICE_FILES_MODEL, scope.row.model) || '' }}
              </template>
            </el-table-column>
            <el-table-column label="资料名称" prop="fileName" />
            <el-table-column label="操作">
              <el-button link type="primary" @click="handleDownload(scope.row.fileUrl)">
                下载
              </el-button>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无数据" />
      </div>

      <!-- 维修工单 -->
      <div v-if="activeTab === 'maintenance'">
        <ContentWrap>
          <el-table row-key="id" :data="workOrdersList">
            <el-table-column label="序号" type="index" align="center" width="60" fixed="left" />
            <el-table-column
              label="维修单号"
              align="center"
              prop="orderNumber"
              width="120"
              fixed="left"
            />
            <el-table-column label="报修人" align="center" prop="reporterName" width="140">
              <template #default="scope">
                {{ scope.row.reporterName }}
                {{ scope.row.reporterPhone }}
              </template>
            </el-table-column>
            <el-table-column
              label="报修时间"
              align="center"
              prop="reportTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="故障类型" align="center" prop="faultType">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.DEVICE_FAULT_TYPE" :value="scope.row.faultType" />
              </template>
            </el-table-column>
            <el-table-column label="故障等级" align="center" prop="faultLevel" fixed="right">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.DEVICE_FAULT_LEVEL" :value="scope.row.faultLevel" />
              </template>
            </el-table-column>
            <el-table-column label="来源" align="center" prop="reportSource">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.DEVICE_REPORT_SOURCE" :value="scope.row.reportSource" />
              </template>
            </el-table-column>
            <el-table-column label="来源单号" align="center" prop="sourceOrderNumber" width="100" />
            <el-table-column label="工单状态" align="center" prop="state" fixed="right" width="100">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.DEVICE_WORK_ORDER_STATE" :value="scope.row.state" />
              </template>
            </el-table-column>
            <el-table-column
              label="计划维修时间"
              align="center"
              prop="plannedMaintenanceTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="处理人" align="center" prop="assigneeName" width="140">
              <template #default="scope">
                {{ scope.row.assigneeName }}
                {{ scope.row.assigneePhone }}
              </template>
            </el-table-column>
            <el-table-column
              label="实际开始时间"
              align="center"
              prop="actualStartTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column
              label="实际完成时间"
              align="center"
              prop="actualEndTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="维修方式" align="center" prop="maintenanceType">
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.DEVICE_MAINTENANCE_TYPE"
                  :value="scope.row.maintenanceType"
                />
              </template>
            </el-table-column>
            <el-table-column label="验收人" align="center" prop="inspectorName" />
            <el-table-column
              label="验收时间"
              align="center"
              prop="inspectionTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="160px"
            />
            <el-table-column label="操作" align="center" min-width="120px" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row)"
                  v-hasPermi="['device:work-orders:update']"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="workOrdersTotal"
            v-model:page="workOrdersQueryParams.pageNo"
            v-model:limit="workOrdersQueryParams.pageSize"
            @pagination="getWorkOrdersList"
          />
        </ContentWrap>

        <!--        <el-empty description="暂无数据" />-->
      </div>

      <!-- 保养任务 -->
      <div v-if="activeTab === 'upkeep'">
        <ContentWrap>
          <el-table row-key="id" :data="upkeepList">
            <el-table-column
              label="任务编号"
              align="center"
              prop="taskNumber"
              width="140"
              fixed="left"
            />
            <el-table-column label="保养类型" align="center" prop="maintenanceType" fixed="left">
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.DEVICE_MAINTENANCE_TASK_TYPE"
                  :value="scope.row.maintenanceType"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="任务状态"
              align="center"
              prop="taskStatus"
              width="120"
              fixed="right"
            >
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.DEVICE_MAINTENANCE_TASK_STATUS"
                  :value="scope.row.taskStatus"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="开始时间"
              align="center"
              prop="planStartTime"
              :formatter="dateFormatter"
              width="160px"
            />
            <el-table-column
              label="结束时间"
              align="center"
              prop="planEndTime"
              :formatter="dateFormatter"
              width="160px"
            />

            <el-table-column
              label="执行时间"
              align="center"
              prop="actualStartTime"
              :formatter="dateFormatter"
              width="160px"
            />

            <el-table-column label="负责人" align="left" prop="responsibleName" />
            <el-table-column label="协同处理人" align="left" prop="collaboratorNames" width="140" />
            <el-table-column
              label="保养说明"
              align="left"
              prop="maintenanceInstructions"
              width="200"
            />
            <el-table-column
              label="验收时间"
              align="center"
              prop="updateTime"
              :formatter="dateFormatter"
              width="160px"
            />

            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="操作" align="center" min-width="120px" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="openForm('update', scope.row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="upkeepTotal"
            v-model:page="upkeepQueryParams.pageNo"
            v-model:limit="upkeepQueryParams.pageSize"
            @pagination="getUpkeepList"
          />
        </ContentWrap>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
  <detailForm ref="formRef" />
</template>

<script setup lang="ts">
import { getStrDictOptions, getBoolDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { InfoApi, InfoVO } from '@/api/device/info'
import { MeasurementApi, MeasurementVO } from '@/api/device/measurement'
import { FilesApi, FilesVO } from '@/api/device/files'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { WorkOrdersApi, WorkOrdersVO } from '@/api/device/workorders'
import { MaintenanceTasksApi, MaintenanceTasksVO } from '@/api/device/maintenancetasks'
import detailForm from './detailForm.vue'

/** 设备基本信息 详情 */
defineOptions({ name: 'InfoDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const activeTab = ref('basic') // 当前激活的选项卡
const formData = ref({}) // 表单数据
const deviceImgList = ref([]) // 设备图片列表
const measurementInfo = ref({}) // 计量信息
const deviceFilesList = ref([]) // 设备图片列表

const workOrdersList = ref<WorkOrdersVO[]>([]) // 列表的数据
const workOrdersTotal = ref(0) // 列表的总页数
const workOrdersQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: 0
})
const getWorkOrdersList = async () => {
  try {
    const data = await WorkOrdersApi.getWorkOrdersPage(workOrdersQueryParams)
    workOrdersList.value = data.list
    workOrdersTotal.value = data.total
  } finally {
  }
}

const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

const upkeepList = ref<MaintenanceTasksVO[]>([]) // 列表的数据
const upkeepTotal = ref(0) // 列表的总页数
const upkeepQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: 0
})
const getUpkeepList = async () => {
  try {
    const data = await MaintenanceTasksApi.getMaintenanceTasksPage(upkeepQueryParams)
    upkeepList.value = data.list
    upkeepTotal.value = data.total
  } finally {
  }
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  dialogTitle.value = '设备详情'
  activeTab.value = 'basic'

  resetForm()

  if (id) {
    formLoading.value = true
    try {
      formData.value = await InfoApi.getInfo(id)
      // 处理设备图片
      deviceImgList.value = formData.value.deviceImg ? formData.value.deviceImg.split(',') : []
      // 获取计量信息（假设有相关API）
      await getMeasurementInfo(id)
      await getDeviceFiles(id)

      workOrdersQueryParams.deviceId = id
      await getWorkOrdersList()
      upkeepQueryParams.deviceId = id
      getUpkeepList()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取计量信息 */
const getMeasurementInfo = async (deviceId: number) => {
  try {
    // 这里假设有获取计量信息的API，根据实际情况调整
    measurementInfo.value = await MeasurementApi.getMeasurementByDeviceId(deviceId)
  } catch (error) {
    console.error('获取计量信息失败:', error)
    measurementInfo.value = {}
  }
}
/** 获取设备资料 */
const getDeviceFiles = async (deviceId: number) => {
  try {
    // 这里假设有获取计量信息的API，根据实际情况调整
    deviceFilesList.value = await FilesApi.listByDeviceId(deviceId)
  } catch (error) {
    console.error('获取设备资料失败:', error)
    deviceFilesList.value = []
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {}
  deviceImgList.value = []
  measurementInfo.value = {}
  deviceFilesList.value = {}
}
const handleDownload = (fileUrl: string) => {
  window.open(fileUrl, '_blank')
}
</script>

<style scoped>
/* 头部信息样式 */
.header-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.cover-container {
  flex-shrink: 0;
}

.device-cover {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.basic-info {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-row .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-row .value {
  color: #303133;
  flex: 1;
}

/* 选项卡样式 */
.tab-section {
  margin-bottom: 20px;
}

:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  font-weight: 500;
}

/* 详情区域样式 */
.detail-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
  margin-bottom: 15px;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}

/* 图片画廊样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.gallery-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  transition: transform 0.2s;
}

.gallery-image:hover {
  transform: scale(1.05);
}

/* 空选项卡样式 */
.empty-tab {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 描述列表样式 */
:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
  background: #f5f7fa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>
