<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Upload, Check, View } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/userStore'
import { useResourceStore } from '../stores/resourceStore'
import { useProfessionalModulesStore } from '../stores/professionalModulesStore'
import SidebarMenu from '../components/SidebarMenu.vue'
import BreadcrumbNav from '../components/BreadcrumbNav.vue'
import HudPageHero from '../components/shell/HudPageHero.vue'
import { formatDateTime } from '../utils/dateTimeFormatter'

const router = useRouter()
const { userInfo, getUserInfo } = useUserStore()
const resourceStore = useResourceStore()
const pro = useProfessionalModulesStore()

const tableData = ref([])
const searchForm = ref({ keyword: '', status: '', grade: '' })
const reviewVisible = ref(false)
const currentDefect = ref(null)
const reviewForm = ref({ review_note: '', pass: true })

const gradeType = { MILD: 'success', MODERATE: 'warning', SEVERE: 'danger', CRITICAL: 'danger' }
const statusType = {
  discovered: 'info',
  reviewing: 'warning',
  confirmed: 'primary',
  remediating: 'warning',
  closed: 'success',
}

const refreshList = () => {
  tableData.value = pro.listDefects(searchForm.value)
}

const resetSearch = () => {
  searchForm.value = { keyword: '', status: '', grade: '' }
  refreshList()
}

const importFromDetections = async () => {
  try {
    const { detections, error } = await resourceStore.fetchDetectionList(
      userInfo.value,
      1,
      100,
      true,
    )
    if (error) throw error
    const { added } = pro.importDefectsFromDetections(detections)
    ElMessage.success(`已从检测记录导入 ${added} 条安全隐患`)
    refreshList()
  } catch (e) {
    ElMessage.error('导入失败')
  }
}

const openReview = (row) => {
  currentDefect.value = row
  reviewForm.value = { review_note: row.review_note || '', pass: true }
  pro.updateDefectStatus(row.defect_id, 'reviewing')
  refreshList()
  reviewVisible.value = true
}

const submitReview = () => {
  const { ok, message } = pro.reviewDefect(currentDefect.value.defect_id, {
    reviewer: userInfo.value?.username || 'admin',
    review_note: reviewForm.value.review_note,
    pass: reviewForm.value.pass,
  })
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success(reviewForm.value.pass ? '已确认安全隐患' : '已退回待复核')
  reviewVisible.value = false
  refreshList()
}

const setStatus = (row, status) => {
  pro.updateDefectStatus(row.defect_id, status)
  ElMessage.success('状态已更新')
  refreshList()
}

const fmt = (v) => (v ? formatDateTime(v) : '—')

const stats = () => {
  const all = pro.defects.value
  return {
    total: all.length,
    open: all.filter((d) => d.status !== 'closed').length,
    reviewing: all.filter((d) => d.status === 'reviewing').length,
  }
}

onMounted(() => {
  getUserInfo().then(() => {
    if (!userInfo.value) router.push('/login')
    else refreshList()
  })
})
</script>

<template>
  <div class="iot-page shell-layout-root">
    <div class="main-container">
      <div class="sidebar"><SidebarMenu /></div>
      <div class="content-area">
        <BreadcrumbNav />
        <HudPageHero
          title="安全隐患台账"
          description="汇聚桥梁安全隐患检测与批量任务发现的隐患，支持复核、确认、处置与销项全生命周期管理。"
        />

        <el-row :gutter="12" class="stat-row">
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num">{{ stats().total }}</div>
              <div class="stat-label">台账总数</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num stat-warn">{{ stats().open }}</div>
              <div class="stat-label">未销项</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num">{{ stats().reviewing }}</div>
              <div class="stat-label">复核中</div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>安全隐患列表</h2>
              <div>
                <el-button type="primary" plain @click="importFromDetections">
                  <el-icon><Upload /></el-icon> 从检测记录导入
                </el-button>
                <el-button @click="refreshList"><el-icon><Refresh /></el-icon> 刷新</el-button>
              </div>
            </div>
          </template>

          <el-form :model="searchForm" inline class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="编号/桥区/类型" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" clearable placeholder="全部" style="width: 120px">
                <el-option
                  v-for="(label, key) in pro.defectStatusLabel"
                  :key="key"
                  :label="label"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="等级">
              <el-select v-model="searchForm.grade" clearable placeholder="全部" style="width: 110px">
                <el-option label="轻度" value="MILD" />
                <el-option label="中度" value="MODERATE" />
                <el-option label="重度" value="SEVERE" />
                <el-option label="严重" value="CRITICAL" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="refreshList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="tableData">
            <el-table-column prop="defect_code" label="编号" width="130" />
            <el-table-column prop="bridge_section" label="桥区" width="110" show-overflow-tooltip />
            <el-table-column prop="disease_type" label="隐患类型" width="120" />
            <el-table-column label="等级" width="80">
              <template #default="{ row }">
                <el-tag :type="gradeType[row.grade]" size="small">
                  {{ pro.gradeLabel[row.grade] || row.grade }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="severity_score" label="严重度" width="80" />
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="statusType[row.status]" size="small">
                  {{ pro.defectStatusLabel[row.status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="media_name" label="关联媒体" min-width="140" show-overflow-tooltip />
            <el-table-column label="发现时间" width="165">
              <template #default="{ row }">{{ fmt(row.discovered_at) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'discovered' || row.status === 'reviewing'"
                  link
                  type="primary"
                  @click="openReview(row)"
                >
                  <el-icon><View /></el-icon> 复核
                </el-button>
                <el-button
                  v-if="row.status === 'confirmed'"
                  link
                  type="warning"
                  @click="setStatus(row, 'remediating')"
                >
                  处置
                </el-button>
                <el-button
                  v-if="row.status === 'remediating'"
                  link
                  type="success"
                  @click="setStatus(row, 'closed')"
                >
                  <el-icon><Check /></el-icon> 销项
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="reviewVisible" title="安全隐患复核" width="480px">
      <el-form v-if="currentDefect" label-width="90px">
        <el-form-item label="隐患编号">{{ currentDefect.defect_code }}</el-form-item>
        <el-form-item label="复核结论">
          <el-radio-group v-model="reviewForm.pass">
            <el-radio :value="true">确认属实</el-radio>
            <el-radio :value="false">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="复核意见">
          <el-input v-model="reviewForm.review_note" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
</style>
