<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 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.problem"
                  placeholder="请输入隐患问题"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.statusId"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option label="待反馈" :value="3" />
                  <el-option label="待审核" :value="4" />
                  <el-option label="已完成" :value="5" />
                  <el-option label="已作废" :value="6" />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>计划日期范围：</span>
                <el-date-picker
                  v-model="planDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  clearable
                  class="act-search-input"
                />
              </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.statusName || '-' }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton
                  v-if="scope.row.statusId === 3"
                  text="反馈"
                  @click="handleFeedback(scope.row.associationOtId)"
                />
                <ActionButton
                  text="查看"
                  @click="handleView(scope.row.associationOtId)"
                />
              </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, DRAW_LESSONS_DEPT_TABLE_COLUMNS } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryDrawLessonsAdminDeptPage,
    type DrawLessonsQueryParam,
  } from '@/api/drawLessons';
  import { downloadByData } from '@/utils/file/download';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';

  const router = useRouter();

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

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

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

  const planDateRange = ref<[string, string] | null>(null);

  const tableQuery = reactive<QueryPageRequest<DrawLessonsQueryParam>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      problem: '',
      statusId: undefined,
      startTime: undefined,
      endTime: undefined,
    },
  });

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

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


  function applyPlanDateRange() {
    if (planDateRange.value && planDateRange.value.length === 2) {
      tableQuery.queryParam.startTime = planDateRange.value[0];
      tableQuery.queryParam.endTime = planDateRange.value[1];
    } else {
      tableQuery.queryParam.startTime = undefined;
      tableQuery.queryParam.endTime = undefined;
    }
  }

  async function getTableData() {
    applyPlanDateRange();
    tableConfig.loading = true;
    try {
      const res = await queryDrawLessonsAdminDeptPage(tableQuery);
      if (res) {
        // 这里暂时共用管理员侧分页接口，后端如有部门侧接口再调整
        tableData.value = res.records.map((item: any) => ({
          id: item.id,
          statusId: item.statusId,
          problem: item.problem,
          statusName: item.statusName,
          associationOtObligationDeptName: item.associationOtObligationDeptName,
          associationOneThree: item.associationOneThree,
          associationOtTimeLimit: item.associationOtTimeLimit,
          associationOtId: item.associationOtId,
          planCompleteTime: item.planCompleteTime ?? item.associationOtTimeLimit,
        }));
        pagination.total = (res as any).totalRow ?? (res as any).total ?? 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.problem = '';
    tableQuery.queryParam.statusId = undefined;
    tableQuery.queryParam.startTime = undefined;
    tableQuery.queryParam.endTime = undefined;
    planDateRange.value = null;
    handleSearch();
  };

  const { urlPrefix } = useGlobSetting();
  const exportApiUrl = ref(urlJoin(urlPrefix, '/api/production/drawLessons/admin/queryPage'));

  const handleDownload = async () => {
    try {
      // 后端如有专门导出接口，可在此替换
      await queryDrawLessonsAdminDeptPage(tableQuery);
      ElMessage.success('导出逻辑待实现');
    } catch (e) {
      console.error('导出举一反三失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

  const handleCreate = () => {
    router.push({
      name: 'oneByOneManagementDeptItem',
      query: {
        operate: 'one-by-one-dept-create',
      },
    });
  };

  /** 反馈：跳转反馈编辑页，操作仅反馈不根据状态显示 */
  const handleFeedback = (id: number) => {
    router.push({
      name: 'oneByOneManagementDeptItem',
      query: {
        id: String(id),
        operate: 'one-by-one-dept-edit',
      },
    });
  };

  /** 查看：跳转详情页，操作仅根据状态显示 */
  const handleView = (id: number) => {
    router.push({
      name: 'oneByOneManagementDeptItem',
      query: {
        id: String(id),
        operate: 'one-by-one-dept-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>