<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="任务ID" prop="taskId">
        <el-input
v-model="queryParams.taskId" class="!w-240px" clearable placeholder="请输入任务ID"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
v-model="queryParams.deviceName" class="!w-240px" clearable placeholder="请输入设备名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择状态">
          <el-option label="待执行" value="PENDING" />
          <el-option label="正常" value="NORMAL" />
          <el-option label="异常" value="ABNORMAL" />
          <el-option label="已错过" value="MISSED" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="!w-240px"
          @change="handleDateRangeChange" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="实例ID" align="center" prop="id" width="80" />
      <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="120" />
      <el-table-column label="执行时间窗口" align="center" min-width="200">
        <template #default="{ row }">
          <div class="text-12px">
            <div>开始：{{ formatDateTime(row.windowStartTime) }}</div>
            <div>结束：{{ formatDateTime(row.windowEndTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最新记录ID" align="center" prop="latestRecordId" width="120">
        <template #default="{ row }">
          {{ row.latestRecordId || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="openDetail(row.id)" v-hasPermi="['iot:inspection-instance:query']">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <Dialog v-model="detailVisible" title="实例详情" width="800px">
    <!-- 实例基本信息 -->
    <el-descriptions :column="2" border>
      <el-descriptions-item label="实例ID">{{ detailData.id }}</el-descriptions-item>
      <el-descriptions-item label="任务ID">{{ detailData.taskId }}</el-descriptions-item>
      <el-descriptions-item label="设备ID">{{ detailData.deviceId }}</el-descriptions-item>
      <el-descriptions-item label="设备名称">{{ detailData.deviceName }}</el-descriptions-item>
      <el-descriptions-item label="窗口开始时间" :span="2">{{ formatDateTime(detailData.windowStartTime)
      }}</el-descriptions-item>
      <el-descriptions-item label="窗口结束时间" :span="2">{{ formatDateTime(detailData.windowEndTime)
      }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="getStatusTag(detailData.status)">
          {{ getStatusLabel(detailData.status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="最新记录ID">{{ detailData.latestRecordId || '-' }}</el-descriptions-item>
      <el-descriptions-item label="创建者">{{ detailData.creator || '-' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime || '') }}</el-descriptions-item>
    </el-descriptions>

    <!-- 点检记录列表 -->
    <div class="mt-4">
      <div class="flex justify-between items-center mb-3">
        <h4 class="text-lg font-medium">点检记录</h4>
      </div>
      <el-table :data="recordsList" :stripe="true" :show-overflow-tooltip="true" v-loading="recordsLoading">
        <el-table-column label="记录ID" align="center" prop="id" width="80" />
        <el-table-column label="提交人" align="center" prop="submitterUserName" width="100" />
        <el-table-column label="点检结果" align="center" prop="resultStatus" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.resultStatus)">
              {{ getStatusLabel(row.resultStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="照片数量" align="center" prop="photos" width="100">
          <template #default="{ row }">
            {{ row.photos?.length || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="结果摘要" align="center" min-width="150">
          <template #default="{ row }">
            <el-button v-if="row.resultSummary" link type="primary" @click="openResultSummaryDialog(row.resultSummary)">
              查看摘要
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewRecordDetail(row.id)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </Dialog>



  <!-- 记录详情弹窗 -->
  <Dialog v-model="recordDetailVisible" title="记录详情" width="600px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="记录ID">{{ recordDetailData.id }}</el-descriptions-item>
      <el-descriptions-item label="实例ID">{{ recordDetailData.instanceId }}</el-descriptions-item>
      <el-descriptions-item label="提交人ID">{{ recordDetailData.submitterUserId }}</el-descriptions-item>
      <el-descriptions-item label="提交人姓名">{{ recordDetailData.submitterUserName }}</el-descriptions-item>
      <el-descriptions-item label="点检结果">
        <el-tag :type="getStatusTag(recordDetailData.resultStatus)">
          {{ getStatusLabel(recordDetailData.resultStatus) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="结果摘要" :span="2">{{ recordDetailData.resultSummary || '-' }}</el-descriptions-item>
      <el-descriptions-item label="异常描述" :span="2">{{ recordDetailData.abnormalDesc || '-' }}</el-descriptions-item>
      <el-descriptions-item label="提交时间">{{ formatDateTime(recordDetailData.submitTime || '') }}</el-descriptions-item>
      <el-descriptions-item label="照片" :span="2" v-if="recordDetailData.photos?.length">
        <div class="flex flex-wrap gap-2">
          <el-image
v-for="(photo, index) in recordDetailData.photos" :key="index" :src="photo.url"
            :preview-src-list="recordDetailData.photos.map(p => p.url)"
            style="width: 80px; height: 80px; border-radius: 4px;" fit="cover" />
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </Dialog>

  <!-- 结果摘要解析弹窗 -->
  <Dialog v-model="resultSummaryVisible" title="点检结果摘要" width="800px">
    <div v-if="parsedResultSummary.length > 0">
      <div v-for="(item, index) in parsedResultSummary" :key="index" class="mb-4">
        <el-card class="result-summary-card">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="font-medium text-lg">{{ item.name }}</span>
              <el-tag :type="getStatusTag(item.status)">
                {{ getStatusLabel(item.status) }}
              </el-tag>
            </div>
          </template>

          <div class="space-y-3">
            <div>
              <span class="text-gray-600 font-medium">检查内容：</span>
              <span>{{ item.desc }}</span>
            </div>

            <div v-if="item.status === 'ABNORMAL'">
              <div v-if="item.abnormal_reason" class="mb-2">
                <span class="text-gray-600 font-medium">异常描述：</span>
                <span class="text-red-600">{{ item.abnormal_reason }}</span>
              </div>

              <div v-if="item.picurl" class="mt-3">
                <span class="text-gray-600 font-medium">异常图片：</span>
                <div class="flex flex-wrap gap-2 mt-2">
                  <el-image
v-for="(url, urlIndex) in item.picurl.split(',')" :key="urlIndex" :src="url.trim()"
                    :preview-src-list="item.picurl.split(',').map(u => u.trim())"
                    style="width: 100px; height: 100px; border-radius: 4px;" fit="cover"
                    class="border border-gray-200" />
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div v-else class="text-center text-gray-500 py-8">
      暂无解析数据
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
// 提交点检记录功能已移除，无需 Plus 图标与上传类型
import * as InspectionInstanceApi from '@/api/iot/inspection/instance'
import * as InspectionRecordApi from '@/api/iot/inspection/record'
import type { InspectionInstanceVO, InspectionInstancePageReqVO } from '@/api/iot/inspection/instance'
import type { InspectionRecordVO } from '@/api/iot/inspection/record'

defineOptions({ name: 'InspectionInstance' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<InspectionInstanceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
// 计算默认日期范围：昨天到三天后
const getDefaultDateRange = () => {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  yesterday.setHours(0, 0, 0, 0)

  const threeDaysLater = new Date()
  threeDaysLater.setDate(threeDaysLater.getDate() + 3)
  threeDaysLater.setHours(23, 59, 59, 999)

  return {
    dateFrom: yesterday.toISOString().split('T')[0],
    dateTo: threeDaysLater.toISOString().split('T')[0]
  }
}

const defaultDateRange = getDefaultDateRange()

const queryParams = reactive<InspectionInstancePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  taskId: undefined,
  deviceName: undefined,
  status: undefined,
  dateFrom: defaultDateRange.dateFrom,
  dateTo: defaultDateRange.dateTo
})
const queryFormRef = ref() // 搜索的表单

// 日期范围选择器
const dateRange = ref<[string, string]>([defaultDateRange.dateFrom, defaultDateRange.dateTo])

// 详情相关
const detailVisible = ref(false)
const detailData = ref<InspectionInstanceVO>({} as InspectionInstanceVO)


// 记录列表相关
const recordsList = ref<InspectionRecordVO[]>([])
const recordsLoading = ref(false)

// 记录详情相关
const recordDetailVisible = ref(false)
const recordDetailData = ref<InspectionRecordVO>({} as InspectionRecordVO)

// 结果摘要解析相关
const resultSummaryVisible = ref(false)
const parsedResultSummary = ref<any[]>([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InspectionInstanceApi.getInspectionInstancePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 日期范围变化处理 */
const handleDateRangeChange = (value: [string, string] | null) => {
  if (value && value.length === 2) {
    queryParams.dateFrom = value[0]
    queryParams.dateTo = value[1]
  } else {
    queryParams.dateFrom = undefined
    queryParams.dateTo = undefined
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 重置日期范围到默认值
  dateRange.value = [defaultDateRange.dateFrom, defaultDateRange.dateTo]
  queryParams.dateFrom = defaultDateRange.dateFrom
  queryParams.dateTo = defaultDateRange.dateTo
  handleQuery()
}

/** 打开详情 */
const openDetail = async (id: number) => {
  try {
    const data = await InspectionInstanceApi.getInspectionInstance(id)
    detailData.value = data
    detailVisible.value = true

    // 同时加载记录列表
    await loadRecords(id)
  } catch (error) {
    message.error('获取详情失败')
  }
}

/** 加载记录列表 */
const loadRecords = async (instanceId: number) => {
  recordsLoading.value = true
  try {
    const data = await InspectionRecordApi.getInspectionRecordList(instanceId)
    recordsList.value = data
  } catch (error) {
    message.error('获取记录列表失败')
    recordsList.value = []
  } finally {
    recordsLoading.value = false
  }
}


/** 查看记录详情 */
const viewRecordDetail = async (id: number) => {
  try {
    const data = await InspectionRecordApi.getInspectionRecord(id)
    recordDetailData.value = data
    recordDetailVisible.value = true
  } catch (error) {
    message.error('获取记录详情失败')
  }
}


/** 获取状态标签 */
const getStatusTag = (status: string) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'NORMAL':
      return 'success'
    case 'ABNORMAL':
      return 'danger'
    case 'MISSED':
      return 'info'
    default:
      return 'info'
  }
}

/** 获取状态标签文本 */
const getStatusLabel = (status: string) => {
  switch (status) {
    case 'PENDING':
      return '待执行'
    case 'NORMAL':
      return '正常'
    case 'ABNORMAL':
      return '异常'
    case 'MISSED':
      return '未执行'
    default:
      return status
  }
}


/** 格式化日期时间 */
const formatDateTime = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}


/** 打开结果摘要弹窗 */
const openResultSummaryDialog = (resultSummary: string) => {
  try {
    // 解析JSON字符串
    const parsed = JSON.parse(resultSummary)

    // 确保是数组格式
    if (Array.isArray(parsed)) {
      parsedResultSummary.value = parsed
    } else {
      // 如果不是数组，包装成数组
      parsedResultSummary.value = [parsed]
    }

    resultSummaryVisible.value = true
  } catch (error) {
    console.error('解析结果摘要JSON失败:', error)
    message.error('结果摘要数据格式错误，无法解析')
    parsedResultSummary.value = []
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.flex {
  display: flex;
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-2 {
  gap: 0.5rem;
}

.text-12px {
  font-size: 12px;
}

.result-summary-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}

.space-y-3>*+* {
  margin-top: 0.75rem;
}

.text-gray-600 {
  color: #6b7280;
}

.text-red-600 {
  color: #dc2626;
}

.font-medium {
  font-weight: 500;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.border-gray-200 {
  border-color: #e5e7eb;
}
</style>
