<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>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } 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} from './configs/form';
  import {type QueryParamType, equipmentHighAlertList, deptList, exportTableData} 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);
  

  // 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.records || []
      console.log(res.records)
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptOptions.value = [];
    }
    
  };

  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)=>{
    ElMessage.warning('请给跳转地址')
  }


  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(() => {
    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;
  }
</style>
