<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"></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"
                  clearable
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.status"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option
                    v-for="item in AREA_CHECK_PLAN_STATUS_OPTIONS"
                    :key="String(item.value)"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>场所所属类别：</span>
                <el-select
                  v-model="tableQuery.queryParam.venueCategory"
                  placeholder="请选择场所所属类别"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in venueCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <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="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</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 #status="scope">
              <span>{{ AREA_CHECK_PLAN_STATUS_LABEL[String(scope.row.status)] ?? '-' }}</span>
            </template>
            <template #needOverallDesc="scope">
              <span>{{ scope.row.needOverallDesc === true ? '是' : scope.row.needOverallDesc === false ? '否' : '-' }}</span>
            </template>
            <template #needSigneeSign="scope">
              <span>{{ scope.row.needSigneeSign === true ? '是' : scope.row.needSigneeSign === false ? '否' : '-' }}</span>
            </template>
            <template #planEndTime="scope">
              <span>{{ scope.row.planEndTime ? scope.row.planEndTime : '-' }}</span>
            </template>
            <template #planStartTime="scope">
              <span>{{ scope.row.planStartTime ? scope.row.planStartTime : '-' }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton text="查看" @click="handleView(scope.row.id)" />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import {
    TABLE_OPTIONS,
    AREA_CHECK_PLAN_TABLE_COLUMNS,
    AREA_CHECK_PLAN_STATUS_OPTIONS,
    AREA_CHECK_PLAN_STATUS_LABEL,
  } from '../areaCheckPlanManagement/configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { AreaCheckPlanQuery, AreaCheckPlanRecord } from '../areaCheckPlanManagement/configs/types';
  import {
    queryAreaCheckPlanManageDeptPage,
    exportAreaCheckPlanList,
    mapAreaCheckPlanApiRecordToUi,
  } from '@/api/production-safety-system';
  import { downloadByData } from '@/utils/file/download';
  import { ElMessage } from 'element-plus';

  const router = useRouter();

  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(AREA_CHECK_PLAN_TABLE_COLUMNS, TABLE_OPTIONS);
  const tableData = ref<AreaCheckPlanRecord[]>([]);
  const dateRange = ref<[string, string] | null>(null);

  // 场所所属类别选项（可从接口或字典获取，此处预留）
  const venueCategoryOptions = ref<Array<{ label: string; value: string }>>([]);

  const tableQuery = reactive<QueryPageRequest<AreaCheckPlanQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      keyword: '',
      status: '' as AreaCheckPlanQuery['status'],
      venueCategory: '',
      planStartTime: '',
      planEndTime: '',
    },
  });

  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 queryAreaCheckPlanManageDeptPage({
        pageNumber: tableQuery.pageNumber,
        pageSize: tableQuery.pageSize,
        queryParam: tableQuery.queryParam,
      });
      const raw = (res as { data?: { records?: unknown[]; totalRow?: number } })?.data ?? res;
      const list = raw?.records ?? [];
      tableData.value = list.map((r: unknown) => mapAreaCheckPlanApiRecordToUi(r));
      pagination.total = raw?.totalRow ?? 0;
    } catch (e) {
      console.error('查询区域检查计划列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    if (dateRange.value && dateRange.value.length === 2) {
      tableQuery.queryParam.planStartTime = dateRange.value[0];
      tableQuery.queryParam.planEndTime = dateRange.value[1];
    } else {
      tableQuery.queryParam.planStartTime = '';
      tableQuery.queryParam.planEndTime = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.keyword = '';
    tableQuery.queryParam.status = '';
    tableQuery.queryParam.venueCategory = '';
    tableQuery.queryParam.planStartTime = '';
    tableQuery.queryParam.planEndTime = '';
    dateRange.value = null;
    handleSearch();
  };

  const handleView = (id: number) => {
    router.push({
      name: 'areaCheckPlanManagementDeptItem',
      query: {
        id,
        operate: 'area-check-plan-dept-view',
      },
    });
  };

  const handleDownload = async () => {
    try {
      const response = await exportAreaCheckPlanList(tableQuery.queryParam);
      if (response) {
        const fileName = `区域检查计划管理_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出院级文件失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  onMounted(() => {
    venueCategoryOptions.value = [
      { label: '各级风险点', value: '各级风险点' },
      { label: '关键业务活动', value: '关键业务活动' },
      { label: '日常安全', value: '日常安全' },
    ];
    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>

