<template>
  <div class="warn-container">
    <!-- 筛选表单 -->
    <el-card class="filter-card" shadow="never" style="border: 0">
      <el-form :model="filterForm" ref="filterFormRef">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="filterForm.deviceName"
                style="width: 200px"
                placeholder="请输入设备名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="通道" prop="channelName">
              <el-select
                v-model="filterForm.channelName"
                placeholder="请选择通道"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="item in channelList"
                  :label="item.channelName"
                  :key="item.channelSipId"
                  :value="item.channelName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="告警类型" prop="eventType">
              <el-select
                v-model="filterForm.eventType"
                placeholder="请选择告警类型"
                clearable
                class="!w-200px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.EVENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :icon="Search">查询</el-button>
              <el-button @click="handleReset" :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格数据 -->
    <el-card class="table-card" shadow="never" style="border: 0">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        height="500"
      >
        <el-table-column
          prop="deviceName"
          label="设备名称"
          align="center"
          width="150"
          fixed="left"
        />

        <el-table-column prop="channelName" label="通道名称" align="center" />
        <el-table-column prop="businessChannel" label="通道ID" align="center" />

        <el-table-column label="告警时间" align="center" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="activePostCount" label="已告警次数" align="center" />

        <el-table-column prop="warnType" label="告警类型" align="center" width="120">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.EVENT_TYPE" :value="row.eventType" />
          </template>
        </el-table-column>

        <el-table-column label="事件状态" align="center">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.EVENT_STATE" :value="row.eventState" />
          </template>
        </el-table-column>

        <el-table-column label="AI算法" prop="mpName" align="center" />

        <el-table-column
          prop="eventDescription"
          label="告警描述"
          align="center"
          width="160"
          show-overflow-tooltip
        />

        <el-table-column label="图片" align="center" width="150">
          <template #default="{ row }">
            <el-button
              link
              :loading="exportLoading(row.id)"
              v-if="row.imageUrl || row.url"
              type="primary"
              @click="openDetail(row)"
              >查看</el-button
            >
            <span v-else>无图片</span>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogTableVisible" title="告警图片" width="800">
        <el-image
          v-if="dialogTableVisible"
          :src="currentImageUrl"
          style="width: 100%; height: 100%"
          fit="contain"
        />
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        class="float-right mb-5"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { warnList } from '@/api/pms/video/warn'
import { DICT_TYPE, getDictLabel, getStrDictOptions } from '@/utils/dict'
import { Search, Refresh } from '@element-plus/icons-vue'
import { listChannel, getAlarmPic } from '@/api/pms/video/channel'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const filterFormRef = ref()

// 筛选表单数据
const filterForm = reactive({
  deviceName: '',
  channelName: '',
  eventType: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

let currentid = ref('')
const exportLoading = (id) => {
  if (id === currentid.value) {
    return true
  } else {
    return false
  }
}

// 初始化表格数据
const initTableData = async () => {
  // 这里可以调用API获取数据
  loading.value = true

  const res = await warnList({
    pageNo: pagination.currentPage,
    pageSize: pagination.pageSize,
    deviceName: filterForm.deviceName,
    channelName: filterForm.channelName,
    eventType: filterForm.eventType
  })

  tableData.value = res.list
  pagination.total = res.total
  loading.value = false
}

// 格式化时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
}

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  initTableData()
}

// 重置表单
const handleReset = () => {
  filterFormRef.value?.resetFields()
  initTableData()
}

// 刷新数据
const handleRefresh = () => {
  initTableData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  initTableData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  initTableData()
}

let currentImageUrl = ref('')
let dialogTableVisible = ref(false)
const openDetail = async (row) => {
  currentid.value = row.id
  exportLoading()

  const res = await getAlarmPic(row.id)

  // // 3. 创建 Blob URL
  const blobUrl = URL.createObjectURL(res)
  currentImageUrl.value = blobUrl

  exportLoading.value = false
  currentid.value = ''
  exportLoading()
  dialogTableVisible.value = true
}

let channelList = ref([])
// 页面加载时初始化数据
onMounted(() => {
  initTableData()

  listChannel({
    pageNo: 1,
    pageSize: 99
  }).then((response) => {
    channelList.value = response.list
  })
})
</script>

<style scoped lang="scss">
.warn-container {
  padding: 20px;

  .filter-card {
    margin-bottom: 10px;

    :deep(.el-card__body) {
      padding: 15px;
      padding-top: 15px !important;
      padding-bottom: 0px !important;
    }
  }

  .operation-row {
    margin-bottom: 20px;
  }

  .table-card {
    :deep(.el-card__body) {
      padding: 15px;
    }
  }
}
</style>
