<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>
            <el-button plain class="search-table-container--button" @click="handleDownload">
              导出
            </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.dangerLevel"
                  placeholder="请选择隐患等级"
                  clearable
                >
                  <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="tableQuery.queryParam.status"
                  placeholder="请选择处理状态"
                  clearable
                >
                  <el-option label="待处理" :value="1" />
                  <el-option label="处理中" :value="2" />
                  <el-option label="已处理" :value="3" />
                  <el-option label="已驳回" :value="4" />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>上报日期：</span>
                <el-date-picker
                  v-model="reportDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</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>
                {{
                  scope.row.status === 1
                    ? '待处理'
                    : scope.row.status === 2
                      ? '处理中'
                      : scope.row.status === 3
                        ? '已处理'
                        : scope.row.status === 4
                          ? '已驳回'
                          : '-'
                }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton text="编辑" @click="handleEdit(scope.row.id)" />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '确定要删除?',
                  }"
                  @confirm="handleDelete(scope.row.id)"
                />
                <ActionButton text="查看" @click="handleView(scope.row.id)" />
              </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,
    type QueryHiddenDangerReq,
    type HiddenDanger,
  } 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[]>([]);

  const tableQuery = reactive<QueryPageRequest<QueryHiddenDangerReq>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      keyword: '',
      dangerType: undefined,
      dangerLevel: undefined,
      status: undefined,
      startDate: '',
      endDate: '',
    },
  });

  // 上报日期范围（用于双向绑定日期组件）
  const reportDateRange = ref<[string, string] | []>([]);

  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 {
      // 将日期范围同步到查询参数
      if (reportDateRange.value && reportDateRange.value.length === 2) {
        tableQuery.queryParam.startDate = reportDateRange.value[0];
        tableQuery.queryParam.endDate = reportDateRange.value[1];
      } else {
        tableQuery.queryParam.startDate = '';
        tableQuery.queryParam.endDate = '';
      }

      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.dangerType = undefined;
    tableQuery.queryParam.dangerLevel = undefined;
    tableQuery.queryParam.status = undefined;
    tableQuery.queryParam.startDate = '';
    tableQuery.queryParam.endDate = '';
    reportDateRange.value = [];
    handleSearch();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/admin/prod/hiddenDanger/importHiddenDanger'));
  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,
        dangerType: tableQuery.queryParam.dangerType,
        dangerLevel: tableQuery.queryParam.dangerLevel,
        status: tableQuery.queryParam.status,
        startDate: tableQuery.queryParam.startDate || undefined,
        endDate: tableQuery.queryParam.endDate || 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('导出失败，请重试');
    }
  };

  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',
      },
    });
  };

  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>