<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>
          </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.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-select
                  v-model="queryParams.queryParam.isUseDepartment"
                  placeholder="是否使用部门"
                  clearable
                  class="act-search-input"
                >
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </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>
            </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>
  </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,
    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 useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, SPECIAL_EQUIPMENT_TABLE_COLUMNS } from './configs/tables';

  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: '',
      deviceStatus: undefined,
      categoryId: undefined,
      typeId: undefined,
      isUseDepartment: undefined,
      responsibilityDeptId: undefined,
      useUnit: '',
    },
  });

  // 类别/种类名称（目前接口只支持按 ID 查，这里仅作为显示搜索占位）
  const categoryName = ref('');
  const typeName = ref('');

  // 部门树（queryAllDeptTree 样式）
  const deptOptions = ref<any[]>([]);
  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 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 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: '',
      deviceStatus: undefined,
      categoryId: undefined,
      typeId: undefined,
      isUseDepartment: undefined,
      responsibilityDeptId: undefined,
      useUnit: '',
    };
    categoryName.value = '';
    typeName.value = '';
    responsibilityDeptPath.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 *;
</style>
