<template>
  <div class="result-list">
    <el-card shadow="never" class="search-card">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item
          label="所属任务"
          prop="taskId"
        >
          <el-select
            v-model="queryParams.taskId"
            filterable
            placeholder="请选择所属任务"
            clearable
            class="query-select"
          >
            <el-option
              v-for="task in taskOptions"
              :key="task.value"
              :label="task.label"
              :value="task.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结果名称" prop="resultName">
          <el-input
            v-model="queryParams.resultName"
            placeholder="请输入结果名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="结果类型" prop="resultType">
          <el-select v-model="queryParams.resultType" clearable placeholder="全部" class="query-select">
            <el-option
              v-for="item in resultTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="resultStatus">
          <el-select v-model="queryParams.resultStatus" clearable placeholder="全部" class="query-select">
            <el-option
              v-for="item in resultStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="告警级别" prop="alarmLevel">
          <el-select v-model="queryParams.alarmLevel" clearable placeholder="全部" class="query-select">
            <el-option
              v-for="item in alarmLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="id" label="结果 ID" min-width="100" show-overflow-tooltip />
        <el-table-column prop="resultName" label="结果名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="resultType" label="结果类型" min-width="110">
          <template #default="{ row }">
            {{ getOptionLabel(resultTypeOptions, row.resultType) }}
          </template>
        </el-table-column>
        <el-table-column prop="resultStatus" label="状态" min-width="140">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.resultStatus)">
              {{ getOptionLabel(resultStatusOptions, row.resultStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmLevel" label="告警级别" min-width="110">
          <template #default="{ row }">
            {{ row.alarmLevel == null ? '-' : getOptionLabel(alarmLevelOptions, row.alarmLevel) }}
          </template>
        </el-table-column>
        <el-table-column prop="alarmLevel" label="图片/视频" min-width="110">
          <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="handleOpenMedia(row)"
                >
                查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="taskName" label="所属任务" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" fixed="right" width="120" align="center">
          <template #default="{ row }">
            <el-button
              v-if="row.resultStatus === 'PENDING'"
              type="primary"
              link
              @click="openReviewDialog(row)"
            >
              复核
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无巡检结果" />
        </template>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="fetchList"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="reviewDialogVisible"
      title="人工复核"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetReviewForm"
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px"
      >
        <el-form-item label="复核结果" prop="resultStatus">
          <el-select v-model="reviewForm.resultStatus" placeholder="请选择复核结果">
            <el-option label="异常" value="ABNORMAL" />
            <el-option label="正常" value="NORMAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警级别" prop="alarmLevel">
          <el-select
            v-model="reviewForm.alarmLevel"
            :disabled="reviewForm.resultStatus !== 'ABNORMAL'"
            clearable
            placeholder="请选择告警级别"
          >
            <el-option
              v-for="item in alarmLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="复核说明" prop="reviewRemark">
          <el-input
            v-model="reviewForm.reviewRemark"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入复核说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="reviewSubmitting" @click="submitReview">
          提交
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="mediaDialogVisible"
      title="图片/视频"
      width="500px"
      :close-on-click-modal="false"
    > 
        <el-image
          v-if="mediaData.evidenceType === 'IMAGE'"
          :src="mediaData.evidenceUrl"
          style="width: 100%; height: 100%"
        />
        <IPlayer
          v-if="mediaData.evidenceType === 'VIDEO'"
          :videoUrl="mediaData.evidenceUrl"
        />
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getTaskList } from '@/api/inspection/task'
import {
  getInspectionResultList,
  reviewInspectionResult
} from '@/api/inspection/result'


const queryFormRef = ref()
const reviewFormRef = ref()
const loading = ref(false)
const reviewSubmitting = ref(false)
const reviewDialogVisible = ref(false)
const tableData = ref([])
const taskOptions = ref([])
const total = ref(0)
const currentReviewId = ref(null)

const queryParams = reactive({
  taskId: null,
  resultName: '',
  resultType: null,
  resultStatus: null,
  alarmLevel: null,
  pageNum: 1,
  pageSize: 10
})

const reviewForm = reactive({
  resultStatus: '',
  alarmLevel: null,
  reviewRemark: '',
  reviewVersion: 0
})

const resultTypeOptions = [
  { label: '劳保穿戴', value: 'PPE' },
  { label: '仪表识别', value: 'METER' },
  { label: '人工巡检', value: 'MANUAL' }
]

const resultStatusOptions = [
  { label: '待处理', value: 'PENDING' },
  { label: '正常', value: 'NORMAL' },
  { label: '异常', value: 'ABNORMAL' },
  { label: '识别失败', value: 'RECOGNIZE_FAILED' }
]

const alarmLevelOptions = [
  { label: '1（提示）', value: 1 },
  { label: '2（警告）', value: 2 },
  { label: '3（严重）', value: 3 }
]

const validateAlarmLevel = (_rule, value, callback) => {
  if (reviewForm.resultStatus === 'ABNORMAL' && value == null) {
    callback(new Error('异常结果必须选择告警级别'))
    return
  }
  callback()
}

const reviewRules = {
  resultStatus: [
    { required: true, message: '请选择复核结果', trigger: 'change' }
  ],
  alarmLevel: [
    { validator: validateAlarmLevel, trigger: 'change' }
  ]
}

const getOptionLabel = (options, value) => {
  return options.find(item => item.value === value)?.label || value || '-'
}

const getStatusTagType = (status) => {
  if (status === 'ABNORMAL') return 'danger'
  if (status === 'NORMAL') return 'success'
  return 'info'
}

const buildQueryParams = () => {
  return Object.fromEntries(
    Object.entries(queryParams).filter(([, value]) => value !== '' && value != null)
  )
}

// 查询失败的消息由项目统一请求拦截器展示。
const fetchList = async () => {
  loading.value = true
  try {
    const response = await getInspectionResultList(buildQueryParams())
    tableData.value = response.rows || response.data?.rows || []
    total.value = response.total ?? response.data?.total ?? 0
  } finally {
    loading.value = false
  }
}

const loadTaskOptions = async () => {
  try {
    const response = await getTaskList({ pageNum: 1, pageSize: 10000 })
    const rows = response.rows || response.data?.rows || []
    taskOptions.value = rows.map(task => ({
      label: task.taskName || task.name || `任务 ${task.id ?? task.taskId}`,
      value: task.id ?? task.taskId
    }))

  } catch {
    // 请求层已统一提示错误，保留空选项等待用户重试页面。
    taskOptions.value = []
  }
}

const handleQuery = async () => {
  try {
    await queryFormRef.value?.validate()
    queryParams.pageNum = 1
    await fetchList()
  } catch {
    // 表单项会展示“所属任务”必填提示。
  }
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  Object.assign(queryParams, {
    resultName: '',
    resultType: null,
    resultStatus: null,
    alarmLevel: null,
    pageNum: 1,
    pageSize: 10
  })
  fetchList()
}

const handleSizeChange = () => {
  queryParams.pageNum = 1
  fetchList()
}

const openReviewDialog = (row) => {
  currentReviewId.value = row.id
  Object.assign(reviewForm, {
    resultStatus: row.resultStatus || 'ABNORMAL',
    alarmLevel: row.alarmLevel ?? null,
    reviewRemark: '',
    reviewVersion: row.reviewVersion ?? 0
  })
  reviewDialogVisible.value = true
  nextTick(() => reviewFormRef.value?.clearValidate())
}

const resetReviewForm = () => {
  currentReviewId.value = null
  Object.assign(reviewForm, {
    resultStatus: '',
    alarmLevel: null,
    reviewRemark: '',
    reviewVersion: 0
  })
  reviewFormRef.value?.clearValidate()
}

const submitReview = async () => {
  try {
    await reviewFormRef.value.validate()
  } catch {
    return
  }

  reviewSubmitting.value = true
  try {
    await reviewInspectionResult(currentReviewId.value, {
      alarmLevel: reviewForm.resultStatus === 'ABNORMAL' ? reviewForm.alarmLevel : null,
      resultStatus: reviewForm.resultStatus,
      reviewRemark: reviewForm.reviewRemark,
      reviewVersion: reviewForm.reviewVersion
    })
    ElMessage.success('复核成功')
    reviewDialogVisible.value = false
    await fetchList()
  } finally {
    reviewSubmitting.value = false
  }
}

const mediaDialogVisible = ref(false)
const mediaData = ref(null)

const handleOpenMedia = (row) => {
    mediaDialogVisible.value = true
    mediaData.value = row
}


watch(
  () => reviewForm.resultStatus,
  status => {
    if (status !== 'ABNORMAL') {
      reviewForm.alarmLevel = null
      nextTick(() => reviewFormRef.value?.clearValidate('alarmLevel'))
    }
  }
)

onMounted(async () => {
  await loadTaskOptions()
  await fetchList()
})
</script>

<style scoped lang="scss">
.result-list {
  width: 100%;
  height: 100%;

  .search-card {
    margin-bottom: 16px;

    :deep(.el-card__body) {
      padding-bottom: 2px;
    }
  }

  .query-select {
    width: 180px;
  }

  .table-card {
    min-width: 0;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  :deep(.el-dialog .el-select) {
    width: 100%;
  }
}
</style>
