<template>
  <div class="hazard-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="隐患类型">
          <el-select v-model="searchForm.hazardType" placeholder="请选择" clearable style="width:140px">
            <el-option v-for="d in hazardTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="隐患等级">
          <el-select v-model="searchForm.hazardLevel" placeholder="请选择" clearable style="width:140px">
            <el-option v-for="d in hazardLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.hazardStatus" placeholder="请选择" clearable style="width:140px">
            <el-option v-for="d in hazardStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="报送状态">
          <el-select v-model="searchForm.isSubmitted" placeholder="请选择" clearable style="width:140px">
            <el-option label="未报送" :value="0" />
            <el-option label="已报送" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联管网">
          <el-select v-model="searchForm.networkId" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="n in networkOptions" :key="n.networkId" :label="n.networkName" :value="n.networkId" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联设备">
          <el-select v-model="searchForm.equipmentId" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="e in equipmentOptions" :key="e.equipmentId" :label="e.equipmentName" :value="e.equipmentId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="hazardNo" label="隐患编号" width="120" />
        <el-table-column prop="hazardType" label="隐患类型" width="100">
          <template #default="{ row }">{{ getDictLabel(hazardTypeDict, row.hazardType) }}</template>
        </el-table-column>
        <el-table-column prop="hazardLevel" label="隐患等级" width="90">
          <template #default="{ row }">
            <el-tag :type="levelTag(row.hazardLevel)">{{ getDictLabel(hazardLevelDict, row.hazardLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hazardDesc" label="隐患描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="hazardSource" label="隐患来源" width="100">
          <template #default="{ row }">{{ getDictLabel(hazardSourceDict, row.hazardSource) }}</template>
        </el-table-column>
        <el-table-column prop="hazardStatus" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="statusTag(row.hazardStatus)">{{ getDictLabel(hazardStatusDict, row.hazardStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联管网" width="140">
          <template #default="{ row }">{{ getNetworkName(row.networkId) }}</template>
        </el-table-column>
        <el-table-column label="关联设备" width="140">
          <template #default="{ row }">{{ getEquipmentName(row.equipmentId) }}</template>
        </el-table-column>
        <el-table-column prop="reportUnit" label="上报单位" width="120" />
        <el-table-column prop="reportTime" label="上报时间" width="160" />
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleSubmitHazard(row)" :disabled="row.isSubmitted === 1">
              {{ row.isSubmitted === 1 ? '已报送' : '报送' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNum" v-model:page-size="pageSize" :total="total"
        layout="total, prev, pager, next, sizes" :page-sizes="[10, 20, 50]"
        @change="loadData" style="margin-top: 16px; justify-content: flex-end"
      />
    </el-card>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="750px" destroy-on-close>
      <el-form :model="formData" ref="formRef" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="隐患编号" prop="hazardNo">
              <el-input v-model="formData.hazardNo" placeholder="请输入隐患编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隐患类型" prop="hazardType">
              <el-select v-model="formData.hazardType" style="width: 100%">
                <el-option v-for="d in hazardTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隐患等级" prop="hazardLevel">
              <el-select v-model="formData.hazardLevel" style="width: 100%">
                <el-option v-for="d in hazardLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隐患来源">
              <el-select v-model="formData.hazardSource" style="width: 100%">
                <el-option v-for="d in hazardSourceDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联管网">
              <el-select v-model="formData.networkId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="n in networkOptions" :key="n.networkId" :label="n.networkName" :value="n.networkId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联设备">
              <el-select v-model="formData.equipmentId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="e in equipmentOptions" :key="e.equipmentId" :label="e.equipmentName" :value="e.equipmentId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报单位">
              <el-input v-model="formData.reportUnit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报时间">
              <el-date-picker v-model="formData.reportTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="隐患描述">
              <el-input v-model="formData.hazardDesc" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="整改方案">
              <el-input v-model="formData.rectifyPlan" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改期限">
              <el-date-picker v-model="formData.rectifyDeadline" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改责任人">
              <el-input v-model="formData.rectifyPerson" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度">
              <el-input-number v-model="formData.longitude" :precision="10" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度">
              <el-input-number v-model="formData.latitude" :precision="10" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHazardPage, addHazard, updateHazard, deleteHazard, submitHazard } from '@/api/pipeNetwork/hazard'
import { getDicts } from '@/api/system/dict/data'
import { getPipeNetworkOptions, getEquipmentByTopLevelType } from '@/api/pipeNetwork/basic'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = reactive({ hazardType: '', hazardLevel: '', hazardStatus: '', isSubmitted: null, networkId: '', equipmentId: '' })
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const formData = reactive({
  hazardId: '', hazardNo: '', hazardType: '', hazardLevel: '', hazardDesc: '',
  hazardSource: '', hazardStatus: '2', reportUnit: '', reportTime: '',
  rectifyPlan: '', rectifyDeadline: '', rectifyPerson: '',
  networkId: '', equipmentId: '', longitude: null, latitude: null
})

const hazardTypeDict = ref([])
const hazardLevelDict = ref([])
const hazardStatusDict = ref([])
const hazardSourceDict = ref([])
const networkOptions = ref([])
const equipmentOptions = ref([])

function getDictLabel(dict, value) {
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}

function levelTag(value) {
  const map = { '0': 'danger', '1': 'warning', '2': 'info', '3': '' }
  return map[value] || 'info'
}
function statusTag(value) {
  const map = { '0': 'info', '1': 'success', '2': 'warning', '3': '' }
  return map[value] || 'info'
}

async function loadDicts() {
  const [typeRes, levelRes, statusRes, sourceRes] = await Promise.all([
    getDicts('hazard_type'),
    getDicts('hazard_level'),
    getDicts('hazard_status'),
    getDicts('hazard_source')
  ])
  hazardTypeDict.value = typeRes.data
  hazardLevelDict.value = levelRes.data
  hazardStatusDict.value = statusRes.data
  hazardSourceDict.value = sourceRes.data
}

async function loadData() {
  loading.value = true
  try {
    const res = await getHazardPage(pageNum.value, pageSize.value, searchForm)
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) { console.error(e) } finally { loading.value = false }
}
function handleSearch() { pageNum.value = 1; loadData() }
function handleReset() {
  Object.assign(searchForm, { hazardType: '', hazardLevel: '', hazardStatus: '', isSubmitted: null, networkId: '', equipmentId: '' })
  handleSearch()
}
async function loadNetworkOptions() {
  if (networkOptions.value.length > 0) return
  try { const res = await getPipeNetworkOptions(); networkOptions.value = res.data || [] } catch (e) { console.error(e) }
}
async function loadEquipmentOptions() {
  if (equipmentOptions.value.length > 0) return
  try { const res = await getEquipmentByTopLevelType('燃气'); equipmentOptions.value = res.data || [] } catch (e) { console.error(e) }
}
function getNetworkName(id) {
  const found = networkOptions.value.find(n => n.networkId === id)
  return found ? found.networkName : id || '-'
}
function getEquipmentName(id) {
  const found = equipmentOptions.value.find(e => e.equipmentId === id)
  return found ? found.equipmentName : id || '-'
}
function handleAdd() {
  dialogTitle.value = '新增'
  Object.assign(formData, { hazardId: '', hazardNo: '', hazardType: '', hazardLevel: '', hazardDesc: '', hazardSource: '', hazardStatus: '2', reportUnit: '', reportTime: '', rectifyPlan: '', rectifyDeadline: '', rectifyPerson: '', networkId: '', equipmentId: '', longitude: null, latitude: null })
  dialogVisible.value = true
  loadNetworkOptions(); loadEquipmentOptions()
}
function handleEdit(row) { dialogTitle.value = '编辑'; Object.assign(formData, row); dialogVisible.value = true; loadNetworkOptions(); loadEquipmentOptions() }
async function handleSave() {
  try {
    if (formData.hazardId) { await updateHazard(formData); ElMessage.success('修改成功') }
    else { await addHazard(formData); ElMessage.success('新增成功') }
    dialogVisible.value = false; loadData()
  } catch (e) {
    const msg = e?.response?.data?.msg || e?.message || '操作失败'
    ElMessage.error(msg)
  }
}
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该隐患记录？', '提示', { type: 'warning' }).then(async () => {
    await deleteHazard(row.hazardId); ElMessage.success('删除成功'); loadData()
  }).catch(() => {})
}
async function handleSubmitHazard(row) {
  ElMessageBox.confirm('确认报送该隐患？', '提示', { type: 'warning' }).then(async () => {
    await submitHazard(row.hazardId); ElMessage.success('报送成功'); loadData()
  }).catch(() => {})
}

onMounted(async () => { await loadDicts(); loadData(); loadNetworkOptions(); loadEquipmentOptions() })
</script>

<style scoped>
.hazard-container { padding: 16px; }
.search-card { margin-bottom: 16px; }
</style>
