<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">告警列表</div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div class="act-search">
            <section class="select-box">
                <div class="select-box--item">
                <span>搜索设备编号：</span>
                <el-input
                  v-model="queryParams.queryParam.deviceNo"
                  placeholder="请输入设备编号"
                  class="act-search-input"
                  clearable
                />
              </div>
              <div class="select-box--item">
                <span>搜索设备名称：</span>
                <el-input
                  v-model="queryParams.queryParam.deviceName"
                  placeholder="请输入设备名称"
                  class="act-search-input"
                  clearable
                />
              </div>
              <div class="select-box--item">
                <span>设备类型：</span>
                <el-select
                  v-model="queryParams.queryParam.deviceType"
                  placeholder="请选择设备类型"
                  clearable
                  class="act-search-input"
                >
                  <el-option
                    v-for="opt in DEVICE_CATEGORY_OPTIONS"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>告警类型：</span>
                <el-select
                  v-model="queryParams.queryParam.alarmType"
                  placeholder="请选择设备类型"
                  clearable
                  class="act-search-input"
                >
                  <el-option
                    v-for="opt in Alarm_TYPE_OPTIONS"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>所属部门：</span>
                <el-cascader
                  v-model="useDeptPath"
                  :options="deptTreeList"
                  :props="deptCascaderProps"
                  :show-all-levels="false"
                  placeholder="请选择责任部门"
                  class="act-search-input"
                  filterable
                  clearable
                  @change="handleUseDeptChange"
                />
              </div>
              <div>
                <span>计划日期范围：</span>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="queryTableList">查询</el-button>
              <el-button @click="handleRestParams">重置</el-button>
              <el-button plain  @click="handleDownload">
               导出
              </el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #deviceType="scope">
                {{ DEVICE_TYPE[scope.row.deviceType]}}
            </template>
            <template #alarmType="scope">
                {{ ALARM_TYPE[scope.row.alarmType]}}
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton
                  text="查看"
                  @click="handleView(scope.row)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <el-dialog v-model="DetailDialog" @close="DetailDialog = false" width="60%" title="告警详情">
        <div class="title">设备信息</div>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="设备类型" >
                    {{ DEVICE_TYPE[detail.deviceType]}}
                </el-descriptions-item>
                <el-descriptions-item label="设备名称" >
                    {{ detail.deviceName }}
                </el-descriptions-item>
                <el-descriptions-item label="设备编号" >
                    {{ detail.deviceNo }}
                </el-descriptions-item>
                <el-descriptions-item label="所属部门" >
                    {{ detail.deptName }}
                </el-descriptions-item>
                <el-descriptions-item label="所在位置" >
                    {{ detail.regionName }}
                </el-descriptions-item>
            </el-descriptions>
        <div class="title">告警信息</div>
            <el-form label-width="150px" :inline="false">
                <el-form-item label="问题状态：">
                    <el-tag :type="detail.alarmStatus==='solved'?'primary':'warning'">
                        {{ ALARM_STATUS[detail.alarmStatus]}}
                    </el-tag>
                </el-form-item>
                <el-form-item label="告警时间：">
                    {{detail.firstAlarmTime}}
                </el-form-item>
                <el-form-item label="告警次数：">
                    {{detail.alarmCount}}
                </el-form-item>
                <el-form-item label="告警内容：">
                    {{detail.alarmContent}}
                </el-form-item>
            </el-form>
        <div class="title">处理信息</div>
            <el-form label-width="150px" :inline="false">
                <el-form-item label="处理人：">
                    {{ detail.handleUserName}}
                </el-form-item>
                <el-form-item label="处理时间：">
                    {{detail.handleTime}}
                </el-form-item>
                <el-form-item label="处理状态：">
                    <el-tag :type="detail.handleStatus==='handled'?'primary':'warning'">
                        {{HANDLE_STATUS[detail.handleStatus]}}
                    </el-tag>
                </el-form-item>
                <el-form-item label="现场描述：">
                    {{detail.handleDesc}}
                </el-form-item>
            </el-form>
        <template #footer>
            <el-button @click="DetailDialog = false">取消</el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage, ElTag } from 'element-plus';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, SPECIAL_EQUIPMENT_TABLE_COLUMNS } from './configs/tables';
  import { DEVICE_CATEGORY_OPTIONS, Alarm_TYPE_OPTIONS, DEVICE_TYPE, ALARM_TYPE, type DETAIL_DATA_TYPE, ALARM_STATUS, HANDLE_STATUS} from './configs/form';
  import {type QueryParamType, equipmentHighAlertList, deptList, exportTableData, DeviceTypeList} from '@/api/equipment-high-alert-List'
  import { downloadByData } from '@/utils/file/download';

  import dayjs from 'dayjs';
  const loading = ref(false);
  const dateRange = ref<[string, string] | null>(null);
  const DetailDialog = ref<boolean>(false)
  const detail = reactive({}) as DETAIL_DATA_TYPE
  const alarmTypeData = ref([])
  // BasicTable
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(SPECIAL_EQUIPMENT_TABLE_COLUMNS, TABLE_OPTIONS);

  const queryParams = reactive<QueryParamType>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      //设备编码
      deviceNo: undefined,
      //设备名称
      deviceName: undefined,
      // 设备类型
      deviceType: undefined,
      // 告警类型
      alarmType: undefined,
      // 所属部门
      deptName: undefined,
      // 开始时间
      startTime: undefined,
      // 结束
      endTime: undefined,
    },
  });

  // 部门树（queryAllDeptTree 样式）
  const deptOptions = ref<any[]>([]);
  const useDeptPath = ref<number[]>([]);
  const deptCascaderProps = {
    expandTrigger: 'click',
    checkStrictly: true,
    value: 'id',
    label: 'deptName',
  };

  const tableData = ref([]);
  const deptTreeList = ref([])
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    queryParams.pageSize = value;
    queryParams.pageNumber = 1;
    queryTableList();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    queryParams.pageNumber = value;
    queryTableList();
  };

  const getDeptList = async () => {
    try {
      let res = await deptList()
      deptTreeList.value = res || []
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptOptions.value = [];
    }
    
  };
  const loadDeviceTypeList = async ()=> {
    let res = await DeviceTypeList()
    if(res){
        alarmTypeData.value = res
    }
  }
  const loadDeptTree = async () => {
    try {
      const res = await getAllDepartments();
      deptOptions.value = formatDeptTree(res);
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptOptions.value = [];
    }
  };

  const handleUseDeptChange = (val: number[]) => {
    if (Array.isArray(val) && val.length) {
      queryParams.queryParam.deptName = JSON.stringify(val[val.length - 1]);
    } else {
      queryParams.queryParam.deptName = undefined;
    }
  };

  const handleView = (row)=>{
    DetailDialog.value = true
    Object.assign(detail, row)
  }


  const queryTableList = () => {
    loading.value = true;
    tableConfig.loading = true;
    let data = {
        pageNumber: queryParams.pageNumber,
        pageSize: queryParams.pageSize,
        queryParam:{
            ...queryParams.queryParam,
            startTime: dateRange.value?.[0] ?? undefined,
            endTime: dateRange.value?.[1] ?? undefined,
        }
    }
    equipmentHighAlertList(data)
      .then((res: any) => {
        tableData.value = res?.records;
        pagination.total = res?.totalRow ?? res?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
        tableConfig.loading = false;
      });
  };
// 导出相关
  const handleDownload = async () => {
    try {
      const response = await exportTableData(queryParams.queryParam);
      if (response) {
        const fileName = `告警列表_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出告警列表失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  const handleRestParams = () => {
    pagination.pageNumber = 1;
    pagination.pageSize = 10;
    queryParams.pageNumber = 1;
    queryParams.pageSize = 10;
    queryParams.queryParam = {
      //设备编码
      deviceNo: undefined,
      //设备名称
      deviceName: undefined,
      // 设备类型
      deviceType: undefined,
      // 所属部门
      deptName: undefined,
      // 开始时间
      startTime: undefined,
      // 结束
      endTime: undefined,
    };
    useDeptPath.value = [];
    dateRange.value = null
    queryTableList();
  };

  onMounted(() => {
    loadDeviceTypeList()
    getDeptList()
    loadDeptTree();
    queryTableList();
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;

  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item) {
    font-size: 14px !important;
  }
  :deep(.flexContent) {
    display: flex;
  }
  :deep(.breadcrumb .title) {
    margin-left: 0;
  }

  :deep(.el-form) {
    flex: 1;
    display: flex;
    row-gap: 15px;
    flex-wrap: wrap;
  }
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
  :deep(main) {
    display: flex;
    flex-direction: column;
  }
  .search-form {
    min-width: 800px;
    display: flex;

    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 20px;
  }

  .button-content {
    margin-bottom: 20px;
  }
  .table-content {
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
  }
  .page-content {
    display: flex;
    justify-content: flex-end;
  }
  .dateRange {
    align-items: flex-end;
  }
  .title {
    margin:10px;
    position: relative;
    &::after{
        content: '';
        position: absolute;
        left: -8px;
        top: 3px;
        width:4px;
        height: 14px;
        background-color: #409eff;
    }
  }
</style>
