<template>
  <div class="app-container bjyp-page">
    <!-- 搜索区 -->
    <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="0" />
          <el-option label="已处理" :value="1" />
          <el-option label="已完成" :value="2" />
        </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="100" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="openAnalysis(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="analysisVisible" title="研判分析" width="900px" :before-close="closeAnalysis" @opened="onDialogOpened">
      <!-- 设备基本信息 -->
      <div class="analysis-header">
        <el-descriptions :column="3" border size="small">
          <el-descriptions-item label="设备名称">{{ currentAlarm.equipmentName }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ currentAlarm.id }}</el-descriptions-item>
          <el-descriptions-item label="设备位置">{{ currentAlarm.location }}</el-descriptions-item>
          <el-descriptions-item label="报警等级">
            <span :class="levelClass(currentAlarm.warningLevel)">{{ levelText(currentAlarm.warningLevel) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="报警时间">{{ currentAlarm.warningTime }}</el-descriptions-item>
          <el-descriptions-item label="监测指标">{{ currentAlarm.warningType || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 监测曲线 -->
      <div class="analysis-chart-section">
        <div class="chart-title-bar">
          <span class="chart-title">监测曲线</span>
          <div class="chart-tabs">
            <span class="chart-tab" :class="{ active: chartPeriod === '24h' }" @click="changeChartPeriod('24h')">24小时</span>
            <span class="chart-tab" :class="{ active: chartPeriod === '7d' }" @click="changeChartPeriod('7d')">7天</span>
            <span class="chart-tab" :class="{ active: chartPeriod === '15d' }" @click="changeChartPeriod('15d')">15天</span>
            <span class="chart-tab" :class="{ active: chartPeriod === '30d' }" @click="changeChartPeriod('30d')">30天</span>
          </div>
        </div>
        <div id="bjypChart" class="chart-container"></div>
      </div>

      <!-- 对比分析 -->
      <div class="analysis-compare-section">
        <div class="compare-title">对比分析</div>
        <div class="compare-content">
          <div class="compare-stats">
            <div class="stat-box">
              <div class="stat-label">日均值</div>
              <div class="stat-value">{{ currentAlarm.dailyAvg }}</div>
            </div>
            <div class="stat-box">
              <div class="stat-label">月均值</div>
              <div class="stat-value">{{ currentAlarm.monthlyAvg }}</div>
            </div>
            <div class="stat-box highlight">
              <div class="stat-label">当前值</div>
              <div class="stat-value">{{ currentAlarm.currentValue }}</div>
            </div>
            <div class="stat-box">
              <div class="stat-label">阈值</div>
              <div class="stat-value">{{ currentAlarm.thresholdValue }}</div>
            </div>
          </div>
          <div class="compare-table-wrap">
            <el-table :data="upDownStreamData" border size="small" style="width: 100%">
              <el-table-column prop="name" label="设备名称" min-width="120" />
              <el-table-column prop="direction" label="方向" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.direction === '上游' ? 'info' : 'primary'" size="small">{{ row.direction }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="value" label="监测值" width="100" />
              <el-table-column prop="threshold" label="阈值" width="100" />
              <el-table-column label="状态" width="80">
                <template #default="{ row }">
                  <span :style="{ color: row.value > row.threshold ? '#f56c6c' : '#67c23a' }">
                    {{ row.value > row.threshold ? '超标' : '正常' }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 研判结论 -->
      <div class="analysis-conclusion-section">
        <div class="conclusion-title">研判结论</div>
        <el-form :model="conclusionForm" label-width="80px" style="margin-top: 12px">
          <el-form-item label="研判结果" required>
            <el-select v-model="conclusionForm.result" placeholder="请选择研判结果" style="width: 240px">
              <el-option label="误报" value="误报" />
              <el-option label="设备故障" value="设备故障" />
              <el-option label="真实报警" value="真实报警" />
              <el-option label="待观察" value="待观察" />
            </el-select>
          </el-form-item>
          <el-form-item label="研判说明" required>
            <el-input v-model="conclusionForm.desc" type="textarea" :rows="3" placeholder="请输入研判说明" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="closeAnalysis">取消</el-button>
        <el-button type="primary" @click="submitConclusion">提交研判</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bjyp">
import { ref, computed, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getEquipmentPage } 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 = { 0: '待处理', 1: '已处理', 2: '已完成' }

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 = { 0: 'warning', 1: 'info', 2: '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: 0,
    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 res = await getEquipmentPage(1, 1000, equipParams)
    const pageData = res.code !== undefined ? res.data : res
    const records = pageData.records || pageData.rows || []

    let equipRecords = []
    records.forEach(row => {
      if (row.alarmStatus === 1) {
        equipRecords.push(convertEquipToWarning(row))
      }
    })

    allMergedData.value = equipRecords
    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 analysisVisible = ref(false)
const currentAlarm = ref({})
const chartPeriod = ref('24h')
let chartInstance = null

const conclusionForm = ref({
  result: '',
  desc: ''
})

const upDownStreamData = ref([])

function generateUpDownStream(alarm) {
  const base = parseFloat(alarm.currentValue) || 1.5
  const threshold = parseFloat(alarm.thresholdValue) || 2.0
  return [
    { name: (alarm.equipmentName || '-') + '（上游A）', direction: '上游', value: (base * 0.72).toFixed(2), threshold: threshold },
    { name: (alarm.equipmentName || '-') + '（上游B）', direction: '上游', value: (base * 0.85).toFixed(2), threshold: threshold },
    { name: (alarm.equipmentName || '-') + '（下游A）', direction: '下游', value: (base * 1.1).toFixed(2), threshold: threshold },
    { name: (alarm.equipmentName || '-') + '（下游B）', direction: '下游', value: (base * 0.95).toFixed(2), threshold: threshold }
  ]
}

function generateChartData(period) {
  const threshold = parseFloat(currentAlarm.value.thresholdValue) || 2.0
  let count = 0
  let unit = ''
  if (period === '24h') { count = 24; unit = '时' }
  else if (period === '7d') { count = 7; unit = '日' }
  else if (period === '15d') { count = 15; unit = '日' }
  else { count = 30; unit = '日' }

  const times = []
  const values = []
  const baseVal = threshold * 0.6
  for (let i = 0; i < count; i++) {
    if (period === '24h') {
      times.push(i + unit)
    } else {
      times.push('第' + (i + 1) + unit)
    }
    const noise = (Math.random() - 0.5) * baseVal * 0.4
    if (i >= count - 3) {
      values.push(parseFloat((threshold + Math.random() * baseVal * 0.3).toFixed(2)))
    } else {
      values.push(parseFloat(Math.max(0, baseVal + noise).toFixed(2)))
    }
  }
  return { times, values, threshold }
}

async function openAnalysis(row) {
  currentAlarm.value = {
    ...row,
    dailyAvg: '1.50',
    monthlyAvg: '1.35'
  }
  upDownStreamData.value = generateUpDownStream(currentAlarm.value)
  conclusionForm.value = { result: '', desc: '' }
  chartPeriod.value = '24h'
  analysisVisible.value = true
}

function closeAnalysis() {
  analysisVisible.value = false
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
}

function onDialogOpened() {
  nextTick(() => {
    initChart()
  })
}

function initChart() {
  const container = document.getElementById('bjypChart')
  if (!container) return
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(container)
  updateChart()
}

function updateChart() {
  if (!chartInstance) return
  const data = generateChartData(chartPeriod.value)
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['监测值', '阈值'], bottom: 0 },
    grid: { left: '3%', right: '4%', top: '10%', bottom: '15%', containLabel: true },
    xAxis: { type: 'category', data: data.times, boundaryGap: false },
    yAxis: { type: 'value', name: currentAlarm.value.warningType || '值' },
    series: [
      {
        name: '监测值',
        type: 'line',
        data: data.values,
        smooth: true,
        lineStyle: { color: '#409eff', width: 2 },
        itemStyle: { color: '#409eff' },
        areaStyle: { color: 'rgba(64,158,255,0.15)' }
      },
      {
        name: '阈值',
        type: 'line',
        data: Array(data.times.length).fill(data.threshold),
        lineStyle: { color: '#f56c6c', width: 2, type: 'dashed' },
        itemStyle: { color: '#f56c6c' }
      }
    ]
  })
}

function changeChartPeriod(period) {
  chartPeriod.value = period
  updateChart()
}

function submitConclusion() {
  if (!conclusionForm.value.result) {
    ElMessage.warning('请选择研判结果')
    return
  }
  if (!conclusionForm.value.desc) {
    ElMessage.warning('请输入研判说明')
    return
  }
  const idx = tableData.value.findIndex(item => item.id === currentAlarm.value.id)
  if (idx !== -1) {
    tableData.value[idx].status = 1
  }
  ElMessage.success('研判提交成功')
  closeAnalysis()
}

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

<style scoped>
.bjyp-page .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;
}

/* 弹窗内部样式 */
.analysis-header {
  margin-bottom: 16px;
}

.chart-title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.chart-title {
  font-size: 15px;
  font-weight: bold;
}
.chart-tabs {
  display: flex;
  gap: 8px;
}
.chart-tab {
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  transition: all 0.2s;
}
.chart-tab.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
.chart-container {
  width: 100%;
  height: 280px;
}

.analysis-compare-section {
  margin-top: 16px;
}
.compare-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 12px;
}
.compare-content {
  display: flex;
  gap: 20px;
}
.compare-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 120px;
}
.stat-box {
  padding: 8px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  text-align: center;
}
.stat-box .stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}
.stat-box .stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}
.stat-box.highlight {
  border-color: #f56c6c;
  background: #fef0f0;
}
.stat-box.highlight .stat-value {
  color: #f56c6c;
}
.compare-table-wrap {
  flex: 1;
}

.analysis-conclusion-section {
  margin-top: 16px;
  border-top: 1px solid #e4e7ed;
  padding-top: 16px;
}
.conclusion-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 0;
}
</style>
