<template>
  <div class="app-container dqyjgl-page">
    <!-- ==================== 顶部统计区 ==================== -->
    <div class="stats-panel">
      <!-- 左侧4个统计指标 -->
      <div class="stats-left">
        <div class="stat-item" v-for="item in statItems" :key="item.label">
          <div class="stat-value" :class="item.cls">{{ item.value }}</div>
          <div class="stat-label">{{ item.label }}</div>
        </div>
      </div>
      <!-- 中间3个环形图 -->
      <div class="stats-center">
        <div class="ring-chart-box" v-for="chart in ringCharts" :key="chart.title">
          <div :id="chart.id" class="ring-chart"></div>
          <div class="ring-legend">
            <div class="legend-row" v-for="(leg, i) in chart.legends.value" :key="i">
              <span class="legend-dot" :style="{ background: leg.color }"></span>
              <span class="legend-text">{{ leg.name }}</span>
              <span class="legend-num">{{ leg.value }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧数字指标 -->
      <!-- <div class="stats-right">
        <div class="right-metric">
          <el-icon class="metric-icon"><Promotion /></el-icon>
          <span class="metric-num">212</span>
        </div>
        <div class="right-metric">
          <el-icon class="metric-icon orange"><Promotion /></el-icon>
          <span class="metric-num">128</span>
        </div>
      </div> -->
    </div>

    <!-- ==================== 筛选区 ==================== -->
    <div class="filter-panel">
      <div class="filter-tabs">
        <div class="tab-item" :class="{ active: activeTab === tab }" v-for="tab in tabs" :key="tab"
          @click="handleTabChange(tab)">{{ tab }}</div>
      </div>
      <div class="filter-form">
        <el-input v-model="filters.equipmentName" placeholder="预警名称" clearable style="width:150px" />
        <el-date-picker v-model="filters.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" style="width:260px" value-format="YYYY-MM-DD" />
        <el-select v-model="filters.warningLevel" placeholder="预警级别" clearable style="width:150px">
          <el-option label="严重" :value="1" />
          <el-option label="重要" :value="2" />
          <el-option label="一般" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleClear">重置</el-button>
      </div>
    </div>

    <!-- ==================== 数据表格 ==================== -->
    <div class="table-panel">
      <el-table :data="tableData" border stripe style="width:100%" v-loading="loading">
        <el-table-column prop="warningNo" label="预警编号" width="140" />
        <el-table-column prop="equipmentName" label="预警名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="warningLevel" label="预警级别" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="levelTagType(row.warningLevel)" size="small">{{ levelText(row.warningLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningType" label="预警类型" width="110" align="center">
          <template #default="{ row }">
            {{ equipmentTypeMap.get(String(row.warningType)) || row.warningType || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="warningSpecial" label="预警专项" width="110" align="center" show-overflow-tooltip />
        <el-table-column prop="location" label="位置" min-width="160" show-overflow-tooltip />
        <el-table-column prop="createTime" label="预警时间" width="160" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">查看</el-button>
            <!-- <el-button type="info" link size="small" @click="handleClose(row)"
              v-if="row.status !== 'CLOSED' && row.status !== 'HANDLED'">关闭</el-button> -->
            <el-button type="danger" link 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" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end" @size-change="loadData" @current-change="loadData" />
    </div>

    <!-- ==================== 查看详情弹窗 ==================== -->
    <el-dialog v-model="detailVisible" title="预警详情" width="650px" :close-on-click-modal="false">
      <div class="detail-content" v-if="currentOrder">
        <!-- 预警信息 -->
        <div class="section-box">
          <div class="section-title">预警信息</div>
          <el-form label-width="90px" size="default">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预警编号">{{ currentOrder.warningNo }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预警名称">{{ currentOrder.equipmentName }}</el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预警级别">
                  <el-tag :type="levelTagType(currentOrder.warningLevel)" size="small">{{
                    levelText(currentOrder.warningLevel) }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预警类型">{{ equipmentTypeMap.get(String(currentOrder.warningType)) ||
                  currentOrder.warningType }}</el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预警专项">{{ currentOrder.warningSpecial || '-' }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-tag :type="statusTagType(currentOrder.status)" size="small">{{ statusText(currentOrder.status)
                  }}</el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预警时间">{{ currentOrder.createTime }}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布人">{{ currentOrder.publisher || '-' }}</el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="位置">
              <div class="desc-text">{{ currentOrder.location }}</div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 人员安排 -->
        <!-- <div class="section-box">
          <div class="section-title">
            接收人员安排
            <el-button type="primary" size="small" style="float:right" @click="showAddPersonDialog">添加</el-button>
          </div>
          <el-table :data="currentOrder.personnel" border size="small" style="width:100%">
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="phone" label="联系方式" />
            <el-table-column prop="dept" label="部门" />
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button link type="danger" size="small"
                  @click="currentOrder.personnel.splice($index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div> -->
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加人员弹窗 -->
    <el-dialog v-model="addPersonVisible" title="添加人员" width="450px">
      <el-form :model="personForm" :rules="personRules" ref="personFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="personForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="personForm.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="部门" prop="dept">
          <el-input v-model="personForm.dept" placeholder="请输入部门" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addPersonVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddPersonConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dqyjgl">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Promotion } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getWarningCurrentPage, updateWarningStatus, deleteWarning, getEquipmentTypeList } from '@/api/drainage'
import useUserStore from '@/store/modules/user'

// ==================== 用户信息 ====================
const userStore = useUserStore()
const isAdmin = computed(() => userStore.roles && userStore.roles.includes('admin'))

// ==================== 表格数据 ====================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)

// ==================== 等级/状态工具方法 ====================
function levelText(level) {
  const map = { 1: '严重', 2: '重要', 3: '一般' }
  return map[level] || '-'
}
function levelTagType(level) {
  const map = { 1: 'danger', 2: 'warning', 3: '' }
  return map[level] || 'info'
}
function statusText(status) {
  const map = { DRAFT: '草稿', PENDING: '待办', PROCESSING: '处置中', RELEASED: '已发布', HANDLED: '已处置', CLOSED: '已解除' }
  return map[status] ?? '-'
}
function statusTagType(status) {
  const map = { DRAFT: 'info', PENDING: 'warning', PROCESSING: 'warning', RELEASED: 'success', HANDLED: 'success', CLOSED: '' }
  return map[status] || 'info'
}

// ==================== 设备类型映射 ====================
const equipmentTypeMap = ref(new Map())

async function loadEquipmentTypes() {
  try {
    const res = await getEquipmentTypeList('2')
    const list = res.code !== undefined ? res.data : res
    const map = new Map()
    if (Array.isArray(list)) {
      list.forEach(item => {
        map.set(String(item.id), item.typeName)
      })
    }
    equipmentTypeMap.value = map
  } catch (error) {
    console.error('加载设备类型列表失败', error)
  }
}

// ==================== 统计指标 ====================
const statItems = computed(() => {
  const list = tableData.value
  return [
    { label: '今日预警', value: total.value, cls: '' },
    { label: '待办', value: list.filter(o => o.status === 'PENDING').length, cls: 'red' },
    { label: '处置中', value: list.filter(o => o.status === 'PROCESSING').length, cls: '' },
    { label: '已发布', value: list.filter(o => o.status === 'RELEASED').length, cls: '' }
  ]
})

// ==================== 环形图配置 ====================
const statusLegends = computed(() => [
  { name: '草稿', value: tableData.value.filter(o => o.status === 'DRAFT').length, color: '#909399' },
  { name: '待办', value: tableData.value.filter(o => o.status === 'PENDING').length, color: '#E6A23C' },
  { name: '处置中', value: tableData.value.filter(o => o.status === 'PROCESSING').length, color: '#409EFF' },
  { name: '已发布', value: tableData.value.filter(o => o.status === 'RELEASED').length, color: '#67C23A' }
])
const levelLegends = computed(() => [
  { name: '严重', value: tableData.value.filter(o => o.warningLevel === 1).length, color: '#F56C6C' },
  { name: '重要', value: tableData.value.filter(o => o.warningLevel === 2).length, color: '#E6A23C' },
  { name: '一般', value: tableData.value.filter(o => o.warningLevel === 3).length, color: '#409EFF' }
])
const typeLegends = computed(() => {
  const types = [...new Set(tableData.value.map(o => o.warningType).filter(Boolean))]
  const colors = ['#409EFF', '#E6A23C', '#67C23A', '#F56C6C']
  return types.map((t, i) => ({
    name: equipmentTypeMap.value.get(String(t)) || t,
    value: tableData.value.filter(o => o.warningType === t).length,
    color: colors[i % colors.length]
  }))
})
const ringCharts = [
  { id: 'statusChart', title: '状态', legends: statusLegends },
  { id: 'levelChart', title: '级别', legends: levelLegends },
  { id: 'typeChart', title: '类型', legends: typeLegends }
]

// ==================== 筛选 ====================
const tabs = ['全部', '草稿', '待办', '处置中', '已发布']
const activeTab = ref('全部')
const filters = ref({
  equipmentName: '',
  dateRange: null,
  warningLevel: ''
})

// ==================== 数据加载 ====================
async function loadData() {
  loading.value = true
  try {
    const params = {
      equipmentType: 'drainage',
      warningType: '2'
    }
    if (filters.value.equipmentName) params.equipmentName = filters.value.equipmentName
    if (filters.value.warningLevel) params.warningLevel = filters.value.warningLevel
    if (filters.value.dateRange && filters.value.dateRange.length === 2) {
      params.startTime = filters.value.dateRange[0]
      params.endTime = filters.value.dateRange[1]
    }
    // 告诉后端只返回当前预警（未处置的）
    params.currentOnly = true
    // Tab 映射为状态筛选
    const tabStatusMap = { '草稿': 'DRAFT', '待办': 'PENDING', '处置中': 'PROCESSING', '已发布': 'RELEASED' }
    if (activeTab.value !== '全部' && tabStatusMap[activeTab.value] !== undefined) {
      params.status = tabStatusMap[activeTab.value]
    }
    // 普通用户只能看到发给自己的预警，管理员能看到所有预警
    params.userId = userStore.id
    params.isAdmin = isAdmin.value
    // 传递部门ID，用于按部门可见性过滤（publish_scope=2）
    if (userStore.deptId) {
      params.deptId = userStore.deptId
    }
    const res = await getWarningCurrentPage(pageNum.value, pageSize.value, params)
    const pageData = res.code !== undefined ? res.data : res
    tableData.value = pageData.records || []
    total.value = pageData.total || 0
  } catch (error) {
    console.error('加载当前预警列表失败', error)
    ElMessage.error('加载当前预警列表失败')
  } finally {
    loading.value = false
    nextTick(() => initCharts())
  }
}

function handleSearch() {
  pageNum.value = 1
  loadData()
}

function handleClear() {
  filters.value = { equipmentName: '', dateRange: null, warningLevel: '' }
  activeTab.value = '全部'
  pageNum.value = 1
  loadData()
}

function handleTabChange(tab) {
  activeTab.value = tab
  pageNum.value = 1
  loadData()
}

// ==================== 操作：关闭/删除 ====================
async function handleClose(row) {
  try {
    await ElMessageBox.confirm('确认关闭该预警？', '提示', { type: 'warning' })
    await updateWarningStatus(row.id, { status: 'CLOSED' })
    ElMessage.success('预警已关闭')
    loadData()
  } catch (error) {
    if (error !== 'cancel') console.error('关闭预警失败', error)
  }
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确认删除该预警？删除后不可恢复。', '提示', { type: 'warning' })
    await deleteWarning(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') console.error('删除预警失败', error)
  }
}

// ==================== 详情弹窗 ====================
const detailVisible = ref(false)
const currentOrder = ref(null)

function handleView(row) {
  currentOrder.value = { ...row, personnel: [] }
  detailVisible.value = true
}

// ==================== 添加人员弹窗 ====================
const addPersonVisible = ref(false)
const personFormRef = ref(null)
const personForm = ref({ name: '', phone: '', dept: '' })
const personRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  dept: [{ required: true, message: '请输入部门', trigger: 'blur' }]
}

function showAddPersonDialog() {
  personForm.value = { name: '', phone: '', dept: '' }
  addPersonVisible.value = true
}

function handleAddPersonConfirm() {
  personFormRef.value.validate(valid => {
    if (!valid) return
    if (currentOrder.value) {
      currentOrder.value.personnel.push({ ...personForm.value })
    }
    addPersonVisible.value = false
  })
}

// ==================== ECharts 初始化 ====================
function initCharts() {
  ringCharts.forEach(chart => {
    const dom = document.getElementById(chart.id)
    if (!dom) return
    const instance = echarts.getInstanceByDom(dom)
    if (instance) instance.dispose()

    const legends = chart.legends.value
    const chartInstance = echarts.init(dom)
    chartInstance.setOption({
      title: {
        text: chart.title,
        left: 'center',
        top: 'center',
        textStyle: { fontSize: 13, color: '#333', fontWeight: 'normal' }
      },
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      series: [{
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: { show: false },
        emphasis: { label: { show: false } },
        data: legends.map(l => ({ name: l.name, value: l.value, itemStyle: { color: l.color } }))
      }]
    })
  })
}

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

<style scoped>
.dqyjgl-page {
  padding: 16px;
  background: #f5f5f5;
  min-height: calc(100vh - 84px);
}

/* ==================== 顶部统计区 ==================== */
.stats-panel {
  display: flex;
  align-items: stretch;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px 20px;
  margin-bottom: 12px;
  gap: 20px;
}

.stats-left {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  min-width: 130px;
  padding-right: 16px;
  border-right: 1px solid #ebeef5;
}

.stat-item {
  display: flex;
  align-items: baseline;
  gap: 8px;
  padding: 6px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

.stat-value.red {
  color: #F56C6C;
}

.stat-label {
  font-size: 13px;
  color: #909399;
}

.stats-center {
  display: flex;
  gap: 16px;
  flex: 1;
}

.ring-chart-box {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.ring-chart {
  width: 130px;
  height: 130px;
  flex-shrink: 0;
}

.ring-legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-row {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #606266;
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-text {
  white-space: nowrap;
}

.legend-num {
  font-weight: 600;
  margin-left: 4px;
}

.stats-right {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 16px;
  min-width: 80px;
  border-left: 1px solid #ebeef5;
  padding-left: 16px;
}

.right-metric {
  display: flex;
  align-items: center;
  gap: 6px;
}

.metric-icon {
  font-size: 22px;
  color: #E6A23C;
}

.metric-icon.orange {
  color: #F56C6C;
}

.metric-num {
  font-size: 22px;
  font-weight: 700;
  color: #303133;
}

/* ==================== 筛选区 ==================== */
.filter-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 12px;
}

.filter-tabs {
  display: flex;
  gap: 0;
  margin-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.tab-item {
  padding: 8px 20px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-item:hover {
  color: #409EFF;
}

.tab-item.active {
  color: #409EFF;
  border-bottom-color: #409EFF;
  font-weight: 600;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* ==================== 表格区 ==================== */
.table-panel {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

.priority-一般 {
  color: #409EFF;
}

.priority-重要 {
  color: #E6A23C;
}

.priority-紧急 {
  color: #F56C6C;
  font-weight: 600;
}

/* ==================== 详情弹窗 ==================== */
.detail-content {
  padding: 0 8px;
}

.steps-wrap {
  margin-bottom: 24px;
  padding: 8px 0;
}

.section-box {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  overflow: hidden;
}

.desc-text {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  max-height: 120px;
  overflow-y: auto;
}

:deep(.el-form-item__label) {
  color: #909399;
}

:deep(.el-form-item__content) {
  color: #303133;
}
</style>
