<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 style="position: relative">
            <el-button
              type="primary"
              class="search-table-container--button"
              @click="$router.push({ name: 'specialEquipmentManageAdd' })"
            >
              添加 
            </el-button>
            <el-button plain class="search-table-container--button" @click="handleImport">
              导入
            </el-button>
          </div>

          <div class="act-search">
            <section class="select-box">
              <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.categoryId"
                  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.typeId"
                  placeholder="请选择设备种类"
                  clearable
                  class="act-search-input"
                >
                  <el-option
                    v-for="opt in DEVICE_TYPE_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.deviceStatus"
                  placeholder="请选择状态"
                  clearable
                  class="act-search-input"
                >
                  <el-option label="在用" :value="1" />
                  <el-option label="停用" :value="2" />
                  <el-option label="报废" :value="3" />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>使用部门：</span>
                <el-cascader
                  v-model="useDeptPath"
                  :options="deptOptions"
                  :props="deptCascaderProps"
                  :show-all-levels="false"
                  placeholder="请选择责任部门"
                  class="act-search-input"
                  filterable
                  clearable
                  @change="handleUseDeptChange"
                />
              </div>
              <div class="select-box--item">
                <span>责任部门：</span>
                <el-cascader
                  v-model="responsibilityDeptPath"
                  :options="deptOptions"
                  :props="deptCascaderProps"
                  :show-all-levels="false"
                  placeholder="请选择责任部门"
                  class="act-search-input"
                  filterable
                  clearable
                  @change="handleDeptChange"
                />
              </div>
              <div class="select-box--item">
                <span>使用单位：</span>
                <el-input
                  v-model="queryParams.queryParam.useUnit"
                  placeholder="请输入使用单位"
                  class="act-search-input"
                  clearable
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="queryTableList">查询</el-button>
              <el-button @click="handleRestParams">重置</el-button>
              <el-button plain class="search-table-container--button" @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 #deviceStatus="scope">
              <span>
                {{ getStatusText(scope.row.deviceStatus, scope.row.deviceStatusName) }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton
                  text="查看"
                  @click="$router.push({ name: 'specialEquipmentManageView', query: { id: scope.row.id } })"
                />
                <ActionButton
                  text="编辑"
                  @click="$router.push({ name: 'specialEquipmentManageEdit', query: { id: scope.row.id } })"
                />
                <ActionButton
                  text="删除"
                  :popconfirm="{ title: '确定要删除该特种设备设施吗？' }"
                  @confirm="handleDelete(scope.row)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="下载模板"
      :show-template="false"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    querySpecialEquipmentPage,
    deleteSpecialEquipment,
    exportSpecialEquipment,
    type SpecialEquipment,
    type SpecialEquipmentQueryParam,
  } from '@/api/production-safety/special-equipment';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import BasicTable from '@/components/BasicTable.vue';
  import BatchImport from '@/components/batch-import/BatchImport.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, DEVICE_TYPE_OPTIONS } from './configs/form';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { downloadByData } from '@/utils/file/download';

  const loading = ref(false);

  // BasicTable
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(SPECIAL_EQUIPMENT_TABLE_COLUMNS, TABLE_OPTIONS);

  const queryParams = reactive<QueryPageRequest<SpecialEquipmentQueryParam>>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      deviceName: '',
      isUseDepartment: undefined,
      deviceStatus: undefined,
      categoryId: undefined,
      typeId: undefined,
      responsibilityDeptId: undefined,
      useUnit: '',
    },
  });

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

  const tableData = ref<SpecialEquipment[]>([]);

  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 getStatusText = (status?: number, statusName?: string) => {
    if (statusName) return statusName;
    if (status === 1) return '在用';
    if (status === 2) return '停用';
    if (status === 3) return '报废';
    return '-';
  };

  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.isUseDepartment = val[val.length - 1];
    } else {
      queryParams.queryParam.isUseDepartment = undefined;
    }
  };

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

  const queryTableList = () => {
    loading.value = true;
    tableConfig.loading = true;
    querySpecialEquipmentPage(queryParams)
      .then((res: any) => {
        tableData.value = (res?.records ?? res?.list ?? []) as SpecialEquipment[];
        pagination.total = res?.totalRow ?? res?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
        tableConfig.loading = false;
      });
  };
// 导出相关
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/specialEquipment/importInventory'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-law-regulation-template.xlsx');

  const handleImport = () => {
    batchImportVisible.value = true;
  };
  const handleUpdate = () => {
    batchImportVisible.value = false;
    queryTableList();
  };
  const handleDownload = async () => {
    try {
      const response = await exportSpecialEquipment(queryParams);
      if (response) {
        const fileName = `特种设备设施管理_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出特种设备设施管理失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  const handleDelete = (row: SpecialEquipment) => {
    if (!row.id) return;
    deleteSpecialEquipment(row.id!)
      .then(() => {
        ElMessage.success('删除成功');
        queryTableList();
      })
      .catch(() => {});
  };

  const handleRestParams = () => {
    pagination.pageNumber = 1;
    pagination.pageSize = 10;
    queryParams.pageNumber = 1;
    queryParams.pageSize = 10;
    queryParams.queryParam = {
      deviceName: '',
      isUseDepartment: undefined,
      deviceStatus: undefined,
      categoryId: undefined,
      typeId: undefined,
      responsibilityDeptId: undefined,
      useUnit: '',
    };
    responsibilityDeptPath.value = [];
    useDeptPath.value = [];
    queryTableList();
  };

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