<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="设备名称">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="报警等级">
        <el-select v-model="queryParams.warningLevel" placeholder="请选择" clearable style="width: 160px">
          <el-option label="严重" :value="1" />
          <el-option label="重要" :value="2" />
          <el-option label="一般" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 140px">
          <el-option label="未下派" :value="-1" />
          <el-option label="待处理" :value="0" />
          <el-option label="已处理" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          value-format="YYYY-MM-DD"
        />
      </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-table :data="tableData" v-loading="loading" border style="width: 100%" size="default">
      <el-table-column label="报警编号" prop="id" min-width="80" align="center" />
      <el-table-column label="设备名称" prop="equipmentName" min-width="140" show-overflow-tooltip />
      <el-table-column label="报警时间" prop="warningTime" min-width="160" />
      <el-table-column label="报警等级" min-width="90" align="center">
        <template #default="{ row }">
          <span :class="levelClass(row.warningLevel)">{{ levelText(row.warningLevel) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报警内容" prop="content" min-width="180" show-overflow-tooltip />
      <el-table-column label="位置" prop="location" min-width="180" show-overflow-tooltip />
      <el-table-column label="处理状态" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)" size="small" effect="plain">{{ statusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <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"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="报警详情" width="680px" :before-close="handleClose">
      <div class="detail-panel">
        <div class="detail-top">
          <div class="detail-image">
            <el-icon :size="48" color="#b0c4de"><Monitor /></el-icon>
          </div>
          <div class="detail-info">
            <div class="detail-number">编号: {{ currentRow.id }}</div>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">设备名称</span>
                  <span class="info-value">{{ currentRow.equipmentName }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">报警时间</span>
                  <span class="info-value">{{ currentRow.warningTime }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">报警等级</span>
                  <span class="info-value">
                    <span :class="levelClass(currentRow.warningLevel)">{{ levelText(currentRow.warningLevel) }}</span>
                  </span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">处理状态</span>
                  <span class="info-value">
                    <el-tag :type="statusTagType(currentRow.status)" size="small" effect="plain">{{ statusText(currentRow.status) }}</el-tag>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">当前值</span>
                  <span class="info-value">{{ currentRow.currentValue || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">阈值</span>
                  <span class="info-value">{{ currentRow.thresholdValue || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">详细地址</span>
                  <span class="info-value">{{ currentRow.location }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">报警类型</span>
                  <span class="info-value">{{ currentRow.warningType || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <div class="info-item desc-item">
              <span class="info-label">描述</span>
              <span class="info-value desc-text">{{ currentRow.content }}</span>
            </div>
          </div>
        </div>
      </div>


    </el-dialog>
  </div>
</template>

<script setup name="Bjqd">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Monitor } from '@element-plus/icons-vue'
import { listUser, deptTreeSelect } from '@/api/system/user'
import { getEquipmentPage, getWarningCurrentPage, updateWarning, addWarning, firstApproveWarning } from '@/api/drainage'
import useUserStore from '@/store/modules/user'

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

// ==================== 搜索参数 ====================
const queryParams = ref({
  equipmentName: '',
  warningLevel: '',
  status: '',
  dateRange: []
})
const queryRef = ref(null)

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

function resetQuery() {
  queryParams.value = { equipmentName: '', warningLevel: '', status: '', dateRange: [] }
  pageNum.value = 1
  loadData()
}

// ==================== 等级/状态映射 ====================
const levelMap = { 1: '严重', 2: '重要', 3: '一般' }
const statusMap = { '-1': '未下派', 0: '待处理', 1: '已处理' }

function levelText(level) {
  return levelMap[level] || '-'
}
function levelClass(level) {
  const map = { 1: 'level-critical', 2: 'level-major', 3: 'level-minor' }
  return map[level] || ''
}
function statusText(status) {
  return statusMap[status] ?? '-'
}
function statusTagType(status) {
  const map = { '-1': 'info', 0: 'warning', 1: 'success' }
  return map[status] || 'info'
}

// ==================== 设备报警数据转换 ====================
function convertEquipToWarning(row) {
  return {
    id: `EQ_${row.equipmentId || row.id}`,
    equipmentId: row.equipmentId || row.id,
    equipmentName: row.equipmentName || '-',
    warningTime: row.updateTime || row.createTime || '-',
    warningLevel: 1,
    content: `设备${row.equipmentName}报警`,
    location: row.equipmentLocation || row.installLocation || '-',
    longitude: row.longitude,
    latitude: row.latitude,
    status: -1,
    currentValue: '',
    thresholdValue: '',
    warningType: '设备报警',
    source: 'equipment'
  }
}

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

async function loadData() {
  loading.value = true
  try {
    const equipParams = { equipmentTypeId: 'drainage' }
    if (queryParams.value.equipmentName) equipParams.equipmentName = queryParams.value.equipmentName

    // 并行加载设备报警和已下派的预警记录
    const [equipRes, warningRes] = await Promise.allSettled([
      getEquipmentPage(1, 1000, equipParams),
      getWarningCurrentPage(1, 1000, { warningType: '设备报警', isAdmin: true })
    ])

    // 解析设备报警
    let equipRecords = []
    if (equipRes.status === 'fulfilled') {
      const res = equipRes.value
      const pageData = res.code !== undefined ? res.data : res
      const records = pageData.records || pageData.rows || []
      records.forEach(row => {
        if (row.alarmStatus === 1) {
          equipRecords.push(convertEquipToWarning(row))
        }
      })
    }

    // 解析已下派的预警记录，用于匹配状态
    let dispatchedMap = {}
    if (warningRes.status === 'fulfilled') {
      const res = warningRes.value
      const pageData = res.code !== undefined ? res.data : res
      const records = pageData.records || pageData.rows || []
      records.forEach(w => {
        if (w.equipmentName) {
          dispatchedMap[w.equipmentName] = w
        }
      })
    }

    // 合并状态：匹配到预警记录的设备报警更新状态
    equipRecords.forEach(item => {
      const matched = dispatchedMap[item.equipmentName]
      if (matched) {
        item.status = matched.status >= 1 ? 1 : 0 // 0=待处理, 1=已处理
        item.firstApprover = matched.firstApprover
        item.firstApproverName = matched.firstApproverName
        item.warningId = matched.id // 保存关联的预警记录ID
      }
    })

    // 筛选状态
    let filtered = equipRecords
    if (queryParams.value.status !== '' && queryParams.value.status !== null) {
      filtered = equipRecords.filter(item => item.status === queryParams.value.status)
    }

    allMergedData.value = filtered
    total.value = allMergedData.value.length
    const start = (pageNum.value - 1) * pageSize.value
    tableData.value = allMergedData.value.slice(start, start + pageSize.value)
  } catch (error) {
    console.error('加载报警清单失败', error)
    ElMessage.error('加载报警清单失败')
  } finally {
    loading.value = false
  }
}

function handlePageChange() {
  const start = (pageNum.value - 1) * pageSize.value
  tableData.value = allMergedData.value.slice(start, start + pageSize.value)
}

function handleSizeChange() {
  pageNum.value = 1
  tableData.value = allMergedData.value.slice(0, pageSize.value)
}

// ==================== 查看详情 ====================
const dialogVisible = ref(false)
const currentRow = ref({})
const dispatchUserId = ref('')
const personOptions = ref([])

async function loadDrainageUsers() {
  try {
    // 先查找排水部门
    const treeRes = await deptTreeSelect()
    const treeData = treeRes.data || treeRes
    const findDept = (nodes) => {
      for (const node of nodes) {
        if (node.label && node.label.includes('排水')) return node
        if (node.children) {
          const found = findDept(node.children)
          if (found) return found
        }
      }
      return null
    }
    const drainageDept = findDept(treeData)
    if (drainageDept) {
      const userRes = await listUser({ deptId: drainageDept.id, status: '0', pageSize: 1000 })
      personOptions.value = (userRes.rows || userRes.data?.rows || []).map(u => ({
        userId: u.userId,
        nickName: u.nickName || u.userName
      }))
    }
  } catch (e) {
    console.error('加载排水单位人员失败', e)
  }
}

async function handleView(row) {
  currentRow.value = { ...row }
  dispatchUserId.value = ''
  dialogVisible.value = true
}

function handleClose() {
  dialogVisible.value = false
}

async function handleDispatch() {
  if (!dispatchUserId.value) {
    ElMessage.warning('请选择下派人员')
    return
  }
  try {
    const selectedUser = personOptions.value.find(p => p.userId === dispatchUserId.value)
    if (currentRow.value.source === 'equipment' || String(currentRow.value.id).startsWith('EQ_')) {
      // 设备报警：创建一条预警记录到后端，持久化下派信息
      await addWarning({
        equipmentName: currentRow.value.equipmentName,
        warningLevel: currentRow.value.warningLevel || 1,
        warningType: currentRow.value.warningType || '设备报警',
        content: currentRow.value.content,
        location: currentRow.value.location,
        warningTime: currentRow.value.warningTime,
        longitude: currentRow.value.longitude,
        latitude: currentRow.value.latitude,
        firstApprover: dispatchUserId.value,
        firstApproverName: selectedUser?.nickName || '',
        publishScope: 3,
        status: 0
      })
    } else {
      // 预警类型：直接更新firstApprover字段
      await updateWarning({
        id: currentRow.value.id,
        firstApprover: dispatchUserId.value,
        firstApproverName: selectedUser?.nickName || '',
        publishScope: 3
      })
    }
    ElMessage.success(`已下派给 ${selectedUser?.nickName || ''}`)
    dialogVisible.value = false
    loadData()
  } catch (e) {
    console.error('下派失败', e)
    ElMessage.error('下派失败，请重试')
  }
}

async function handleProcess(row) {
  try {
    await ElMessageBox.confirm('确认处理此报警？', '提示', { type: 'warning' })
    // 用关联的预警记录ID调用处理接口
    const warningId = row.warningId || row.id
    await firstApproveWarning(warningId, {
      userId: userStore.id,
      userName: userStore.name
    })
    ElMessage.success('处理成功')
    loadData()
  } catch (e) {
    if (e !== 'cancel') {
      console.error('处理失败', e)
      ElMessage.error('处理失败，请重试')
    }
  }
}

// ==================== 生命周期 ====================
onMounted(() => {
  loadDrainageUsers()
  loadData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 84px);
}

.search-form {
  margin-bottom: 16px;
  padding: 16px 16px 0;
  background: #f5f7fa;
  border-radius: 6px;
}

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

/* 等级彩色文字 */
.level-critical {
  color: #f56c6c;
  font-weight: 700;
}

.level-major {
  color: #e6a23c;
  font-weight: 700;
}

.level-minor {
  color: #409eff;
  font-weight: 600;
}

/* 详情弹窗 */
.detail-panel {
  padding: 0 4px;
}

.detail-top {
  display: flex;
  gap: 24px;
}

.detail-image {
  width: 150px;
  height: 150px;
  flex-shrink: 0;
  background: #dce6f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #c0cfe0;
}

.detail-info {
  flex: 1;
}

.detail-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 14px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  line-height: 22px;
}

.info-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
  min-width: 65px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.desc-item {
  align-items: flex-start;
}

.desc-text {
  line-height: 22px;
  color: #606266;
}

/* 底部操作区 */
.detail-footer {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.dispatch-row {
  display: flex;
  align-items: center;
}

.dispatch-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
  white-space: nowrap;
}
</style>
