<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>
            </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 #needInspectedSign="scope">
              <span>{{ scope.row.needInspectedSign === true ? '是' : scope.row.needInspectedSign === false ? '否' : '-' }}</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';

  const router = useRouter();

  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(AREA_CHECK_PLAN_TABLE_COLUMNS, TABLE_OPTIONS);
  const allData = ref<AreaCheckPlanRecord[]>([]);
  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();
  };

  /** 主列表假数据（本页面不调用接口，全部使用示例数据） */
  const MOCK_LIST: AreaCheckPlanRecord[] = [
    {
      id: 1,
      checkVenue: '18号楼、油库、液氮罐',
      status: 1,
      venueCategoryName: '各级风险点',
      planName: '2025年度生产安全检查计划',
      mainDeptName: '试验验证中心、质量管理部',
      selfCheckFrequency: '每日',
      mainDeptExecutorGroupName: '自查小分队分组',
      mainDeptResponsiblePerson: '孙菲、周萍',
      safetyEmergencyDeptName: '安全应急部',
      safetyEmergencyCheckFrequency: '每周',
      safetyEmergencyExecutorGroupName: '安全应急部小分队分组',
      safetyEmergencyResponsiblePerson: '李雪峰',
      hospitalLeaderDeptName: '院领导',
      hospitalLeaderCheckFrequency: '每季度',
      hospitalLeaderExecutorGroupName: '领导小分队执行组',
      hospitalLeaderResponsiblePerson: '孙菲亚',
      checklistCategoryName: '安全管理检查单',
      checklistTemplateName: '上飞院安全检查表',
      needOverallDesc: true,
      needInspectedSign: true,
      planStartTime: '2019-03-28',
      planEndTime: '2019-03-28',
    },
  ];

  function getTableData() {
    tableConfig.loading = true;
    try {
      let list = allData.value.slice();
      const { keyword, status, venueCategory, planStartTime, planEndTime } = tableQuery.queryParam;

      if (keyword && keyword.trim()) {
        const kw = keyword.trim().toLowerCase();
        list = list.filter(
          (row) =>
            (row.checkVenue || '').toLowerCase().includes(kw) ||
            (row.planName || '').toLowerCase().includes(kw),
        );
      }
      if (status !== '' && status !== undefined && status !== null) {
        list = list.filter((row) => String(row.status) === String(status));
      }
      if (venueCategory && venueCategory.trim()) {
        const vc = venueCategory.trim().toLowerCase();
        list = list.filter((row) => (row.venueCategoryName || '').toLowerCase().includes(vc));
      }
      if (planStartTime) {
        list = list.filter((row) => !row.planStartTime || row.planStartTime >= planStartTime);
      }
      if (planEndTime) {
        list = list.filter((row) => !row.planEndTime || row.planEndTime <= planEndTime);
      }

      pagination.total = list.length;
      const start = (tableQuery.pageNumber - 1) * tableQuery.pageSize;
      tableData.value = list.slice(start, start + tableQuery.pageSize);
    } 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',
      },
    });
  };

  onMounted(() => {
    allData.value = [...MOCK_LIST];
    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>

