<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="handleCreate"> 新增 </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="tableQuery.queryParam.keyword"
                  placeholder="请输入隐患问题、地点、姓名、工号或联系电话"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.statusType" placeholder="请选择状态" clearable>
                  <el-option label="全部" :value="0" />
                  <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-input
                  v-model="tableQuery.queryParam.sourceTypeName"
                  placeholder="请输入提交类型"
                  class="act-search-input"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</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 #status="scope">
              <span>
                {{ getStatusTypeName(scope.row.statusType ?? getStatusType(scope.row.status)) }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 待审核：显示审核和查看 -->
                <template v-if="scope.row.status === 1">
                  <ActionButton text="审核" @click="handleApprove(scope.row.id)" />
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
                <!-- 审核通过（需求部门通过或安全部门通过）：显示查看和入账 -->
                <template v-else-if="scope.row.status === 2 || scope.row.status === 4">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton text="入账" @click="handleAccount(scope.row.id)" />
                </template>
                <!-- 审核不通过（需求部门驳回或安全部门驳回）：显示查看 -->
                <template v-else-if="scope.row.status === 3 || scope.row.status === 5">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
                <!-- 其他状态：显示查看 -->
                <template v-else>
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
              </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 setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, INVENTORY_TABLE_COLUMNS } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryHiddenDangerPage,
    deleteHiddenDanger,
    exportHiddenDanger,
    approveEmployeeHazardReport,
    accountEmployeeHazardReport,
    type QueryHiddenDangerReq,
    type HiddenDanger,
    type ApproveEmployeeHazardReportReq,
  } from '@/api/production-safety';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';

  const router = useRouter();

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(INVENTORY_TABLE_COLUMNS, TABLE_OPTIONS);

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

  // 将 status (1-7) 转换为 statusType (1-3)
  const getStatusType = (status: number): number => {
    // statusType = 1: 待审核 (status = 1)
    if (status === 1) {
      return 1;
    }
    // statusType = 2: 审核通过 (status = 2, 4, 6)
    if (status === 2 || status === 4 || status === 6) {
      return 2;
    }
    // statusType = 3: 审核不通过 (status = 3, 5, 7)
    if (status === 3 || status === 5 || status === 7) {
      return 3;
    }
    return 0;
  };

  // 根据 statusType 显示文本：1=待审核，2=审核通过，3=审核不通过
  const getStatusTypeName = (statusType: number): string => {
    if (statusType === 1) return '待审核';
    if (statusType === 2) return '审核通过';
    if (statusType === 3) return '审核不通过';
    return '-';
  };

  const tableQuery = reactive<QueryPageRequest<QueryHiddenDangerReq>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      keyword: '',
      statusType: undefined,
      sourceTypeName: '',
    },
  });

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryHiddenDangerPage(tableQuery);
      if (res) {
        tableData.value = res.records || [];
        pagination.total = res.totalRow || 0;
      }
    } catch (e) {
      console.error('获取隐患上报列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.keyword = '';
    tableQuery.queryParam.statusType = undefined;
    tableQuery.queryParam.sourceTypeName = '';
    handleSearch();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/api/employeeHazardReport/importEmployeeHazardReport'));
  const templateUrl = ref('');

  const handleImport = () => {
    batchImportVisible.value = true;
  };

  const handleUpdate = () => {
    batchImportVisible.value = false;
    getTableData();
  };

  const handleDownload = async () => {
    try {
      const exportParams: QueryHiddenDangerReq = {
        keyword: tableQuery.queryParam.keyword || undefined,
        statusType: tableQuery.queryParam.statusType,
        sourceTypeName: tableQuery.queryParam.sourceTypeName || undefined,
      };
      const response = await exportHiddenDanger(exportParams);
      if (response) {
        const fileName = `员工上报隐患管理_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出隐患上报失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

  const handleCreate = () => {
    router.push({
      name: 'employeeReportHiddenTroubleManagementItem',
      query: {
        operate: 'employee-report-hidden-trouble-create',
      },
    });
  };

  const handleEdit = (id: number) => {
    router.push({
      name: 'employeeReportHiddenTroubleManagementItem',
      query: {
        id,
        operate: 'employee-report-hidden-trouble-edit',
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteHiddenDanger(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除隐患上报失败:', e);
      ElMessage.error('删除失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'employeeReportHiddenTroubleManagementItem',
      query: {
        id,
        operate: 'employee-report-hidden-trouble-view',
      },
    });
  };

  const handleApprove = (id: number) => {
    router.push({
      name: 'employeeReportHiddenTroubleManagementItem',
      query: {
        id,
        operate: 'employee-report-hidden-trouble-approve',
      },
    });
  };

  const handleAccount = async (hazardId: number) => {
    try {
      await accountEmployeeHazardReport(hazardId);
      ElMessage.success('入账成功');
      getTableData();
    } catch (e) {
      console.error('入账失败:', e);
      ElMessage.error(e?.message || e?.data || '入账失败，请重试');
    }
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  @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>
