<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 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.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in WORK_PLAN_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>分类名称：</span>
                <el-select
                  v-model="tableQuery.queryParam.categoryName"
                  placeholder="请选择分类名称"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in classifyNameOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div>
                <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>
                {{ WORK_PLAN_STATUS_LABEL[String(scope.row.status)] || '-' }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <template v-if="Number(scope.row.status) === 2">
                  <ActionButton text="反馈" @click="handleIssue(scope.row)" />
                </template>

                <!-- 已完成(3)：删除、查看 -->
                <template v-else>
                  <ActionButton text="查看" @click="handleView(scope.row)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </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,
    WORK_PLAN_TABLE_COLUMNS,
    WORK_PLAN_STATUS_OPTIONS,
    WORK_PLAN_STATUS_LABEL,
  } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryWorkPlanDeptPage,
    deleteWorkPlanDept,
    issueWorkPlanDept,
  } from '@/api/safety-system-construction-work-plan';

  const router = useRouter();

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

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

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

  // 日期范围
  const dateRange = ref<[string, string] | null>(null);

  // 分类名称选项
  const classifyNameOptions = ref<Array<{ label: string; value: string }>>([
    { label: '全部', value: '全部' },
    { label: '安全综合工作', value: '安全综合工作' },
    { label: '生产安全工作', value: '生产安全工作' },
    { label: '安全文化活动', value: '安全文化活动' },
  ]);

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

  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 queryWorkPlanDeptPage(tableQuery);
      if (res) {
        tableData.value = res.records;
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取工作计划列表失败:', e);
      ElMessage.error('获取工作计划列表失败');
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      tableQuery.queryParam.startDate = dateRange.value[0];
      tableQuery.queryParam.endDate = dateRange.value[1];
    } else {
      tableQuery.queryParam.startDate = '';
      tableQuery.queryParam.endDate = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.pageNumber = 1;
    tableQuery.queryParam = {
      keyword: '',
      status: '',
      categoryName: '',
      startDate: '',
      endDate: '',
    };
    dateRange.value = null;
    handleSearch();
  };

  // 查看
  const handleView = (row: any) => {
    router.push({
      name: 'SafetySystemConstructionWorkPlanManagementDeptItem',
      query: {
        id: row.id,
        planId: row.planId,
        operate: 'work-plan-dept-view',
      },
    });
  };

  // 反馈
  const handleIssue = async (row: any) => {
    router.push({
      name: 'SafetySystemConstructionWorkPlanManagementDeptItem',
      query: {
        id: row.id,
        planId: row.planId,
        operate: 'work-plan-dept-issue',
      },
    });
  };

  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>
