<template>
  <div class="risk-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="管网ID">
          <el-input v-model="searchForm.networkId" placeholder="请输入管网ID" clearable />
        </el-form-item>
        <el-form-item label="风险等级">
          <el-select v-model="searchForm.riskLevel" placeholder="请选择" clearable>
            <el-option v-for="d in riskLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </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="networkId" label="管网ID" min-width="130" />
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag :color="getRiskColorValue(row.riskColor)" effect="dark" size="small">{{ getDictLabel(riskLevelDict, row.riskLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="riskScore" label="风险评分" width="100" />
        <el-table-column prop="riskColor" label="风险颜色" width="90">
          <template #default="{ row }">
            <span :style="{ display: 'inline-block', width: 16, height: 16, background: getRiskColorValue(row.riskColor), borderRadius: 4, verticalAlign: 'middle' }"></span>
            <span style="margin-left: 6px">{{ getDictLabel(riskColorDict, row.riskColor) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="assessmentModel" label="评估模型" width="120" />
        <el-table-column prop="assessmentTime" label="评估时间" width="160" />
        <el-table-column prop="assessmentPerson" label="评估人" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">编辑</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="风险评估详情" v-model="detailVisible" width="700px">
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="风险ID">{{ detailData.riskId }}</el-descriptions-item>
        <el-descriptions-item label="管网ID">{{ detailData.networkId }}</el-descriptions-item>
        <el-descriptions-item label="风险等级">{{ getDictLabel(riskLevelDict, detailData.riskLevel) }}</el-descriptions-item>
        <el-descriptions-item label="风险评分">{{ detailData.riskScore }}</el-descriptions-item>
        <el-descriptions-item label="评估模型">{{ detailData.assessmentModel }}</el-descriptions-item>
        <el-descriptions-item label="评估人">{{ detailData.assessmentPerson }}</el-descriptions-item>
        <el-descriptions-item label="风险构成要素" :span="2">{{ detailData.riskFactors }}</el-descriptions-item>
        <el-descriptions-item label="防护目标" :span="2">{{ detailData.protectiveTargets }}</el-descriptions-item>
        <el-descriptions-item label="危险源" :span="2">{{ detailData.hazardSources }}</el-descriptions-item>
        <el-descriptions-item label="维修历史" :span="2">{{ detailData.repairHistorySummary }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="650px" destroy-on-close>
      <el-form :model="formData" ref="formRef" label-width="100px">
        <el-form-item label="管网ID" prop="networkId">
          <el-input v-model="formData.networkId" placeholder="请输入管网ID" />
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="formData.riskLevel" style="width: 100%">
            <el-option v-for="d in riskLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险评分">
          <el-input-number v-model="formData.riskScore" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="风险颜色">
          <el-select v-model="formData.riskColor" style="width: 100%">
            <el-option v-for="d in riskColorDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="评估模型">
          <el-input v-model="formData.assessmentModel" />
        </el-form-item>
        <el-form-item label="评估人">
          <el-input v-model="formData.assessmentPerson" />
        </el-form-item>
        <el-form-item label="评估时间">
          <el-date-picker v-model="formData.assessmentTime" type="datetime" style="width: 100%" />
        </el-form-item>
        <el-form-item label="风险要素">
          <el-input v-model="formData.riskFactors" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="防护目标">
          <el-input v-model="formData.protectiveTargets" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="危险源">
          <el-input v-model="formData.hazardSources" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="2" />
        </el-form-item>
      </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 { getRiskPage, getRiskById, addRisk, updateRisk, deleteRisk } from '@/api/pipeNetwork/hazard'
import { getDicts } from '@/api/system/dict/data'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = reactive({ networkId: '', riskLevel: '' })
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const detailVisible = ref(false)
const detailData = ref(null)
const formData = reactive({
  riskId: '', networkId: '', riskLevel: '', riskScore: null, riskColor: '',
  assessmentModel: '', assessmentTime: '', assessmentPerson: '',
  riskFactors: '', protectiveTargets: '', hazardSources: '', repairHistorySummary: '', remark: ''
})

const riskLevelDict = ref([])
const riskColorDict = ref([])

const riskColorValueMap = { '0': '#F56C6C', '1': '#E6A23C', '2': '#F4D03F', '3': '#409EFF' }

function getDictLabel(dict, value) {
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}
function getRiskColorValue(value) {
  return riskColorValueMap[value] || '#909399'
}

async function loadDicts() {
  const [levelRes, colorRes] = await Promise.all([
    getDicts('risk_level'),
    getDicts('risk_color')
  ])
  riskLevelDict.value = levelRes.data
  riskColorDict.value = colorRes.data
}

async function loadData() {
  loading.value = true
  try {
    const res = await getRiskPage(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, { networkId: '', riskLevel: '' }); handleSearch() }
function handleAdd() {
  dialogTitle.value = '新增评估'
  Object.assign(formData, { riskId: '', networkId: '', riskLevel: '', riskScore: null, riskColor: '', assessmentModel: '', assessmentTime: '', assessmentPerson: '', riskFactors: '', protectiveTargets: '', hazardSources: '', repairHistorySummary: '', remark: '' })
  dialogVisible.value = true
}
function handleEdit(row) { dialogTitle.value = '编辑'; Object.assign(formData, row); dialogVisible.value = true }
async function handleSave() {
  try {
    if (formData.riskId) { await updateRisk(formData); ElMessage.success('修改成功') }
    else { await addRisk(formData); ElMessage.success('新增成功') }
    dialogVisible.value = false; loadData()
  } catch (e) { console.error(e) }
}
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该评估记录？', '提示', { type: 'warning' }).then(async () => {
    await deleteRisk(row.riskId); ElMessage.success('删除成功'); loadData()
  }).catch(() => {})
}
async function handleDetail(row) {
  try {
    const res = await getRiskById(row.riskId)
    detailData.value = res.data
    detailVisible.value = true
  } catch (e) { console.error(e) }
}

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

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