<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="evaluation-header">
        <h1 class="evaluation-title">{{ detailData?.problem || '通知对象' }}</h1>
        <div class="evaluation-meta">
          <span>创建人：{{ detailData?.creatorName || '-' }}</span>
          <span>创建时间：{{ detailData?.createdAt || '-' }}</span>
        </div>
      </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <div class="header-tabs-wrapper">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="ALL" />
            <el-tab-pane
              v-for="item in NOTIFY_TARGET_STATUS_OPTIONS"
              :key="item.value"
              :label="item.label"
              :name="item.value"
            />
          </el-tabs>
        </div>

        <header>
          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item" v-if="activeTab === 'ALL'">
                <span>状态：</span>
                <el-select
                  v-model="searchStatus"
                  placeholder="请选择状态"
                  clearable
                  style="width: 160px"
                >
                  <el-option
                    v-for="item in NOTIFY_TARGET_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>部门名称：</span>
                <el-input
                  v-model="searchDeptName"
                  placeholder="请输入部门名称"
                  clearable
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>时间范围：</span>
                <el-date-picker
                  v-model="searchDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  style="width: 240px"
                />
              </div>
              <div class="select-box--item">
                <span>关键词：</span>
                <el-input
                  v-model="searchKeyword"
                  placeholder="请输入关键词"
                  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>
              <el-button plain @click="handleExport">导出</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="rawTableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #status="scope">
              <span>{{ scope.row.statusName || '-' }}</span>
            </template>
            <template #feedbackRatio="scope">
              <span>{{ scope.row.feedbackRatio ?? (scope.row.issueCount ? `${scope.row.feedbackCount ?? 0}/${scope.row.issueCount}` : '-') }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton
                  v-if="scope.row.statusName === '待反馈'"
                  text="作废"
                  :popconfirm="{ title: '确定要作废?' }"
                  @confirm="handleCancel(scope.row)"
                />
                <ActionButton
                  v-else-if="scope.row.statusName === '待审核'"
                  text="审核"
                  @click="handleApprove(scope.row)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { 
    queryDrawLessonsAdminPage, 
    queryDrawLessonsAdminDetailPage,
    cancellationMessagePost,
    exportTheDocumentPost,
    type DrawLessonsQueryParam 
  } from '@/api/drawLessons';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { DRAW_LESSONS_TABLE_COLUMNS_TOW } from '../configs/tables';
  import { t } from '@wangeditor/editor';
  import { downloadByData } from '@/utils/file/download';

  const NOTIFY_TARGET_STATUS_OPTIONS = [
    // { label: '未下发', value: '未下发' },
    { label: '待反馈', value: '3' },
    { label: '待审核', value: '4' },
    { label: '已作废', value: '6' },
    { label: '已完成', value: '5' },
  ];

  const TABLE_OPTIONS = {
    emptyText: '暂无通知对象',
    loading: false,
    maxHeight: 'calc(70vh - 200px)',
  };

  const router = useRouter();
  const route = useRoute();
  const id = computed(() => Number(route.query.id));
  const tableData = ref<any[]>([]);

  const { tableConfig, pagination } = useTableConfig(DRAW_LESSONS_TABLE_COLUMNS_TOW, TABLE_OPTIONS, true);
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const rawTableData = ref<any[]>([]);
  const detailData = ref({
    problem: route.query.problem as string,
    creatorName: route.query.creatorName as string,
    createdAt: route.query.createdAt as string,
  });

  const activeTab = ref<string>(route.query.statusId as string || 'ALL');
  const searchStatus = ref<string>('');
  const searchDeptName = ref<string>('');
  const searchDateRange = ref<string[] | null>(null);
  const searchKeyword = ref<string>('');

  // const filteredTableData = computed(() => {
  //   let list = rawTableData.value;
  //   if (activeTab.value !== 'ALL') {
  //     list = list.filter((row) => (row.statusName || '') === activeTab.value);
  //   }
  //   if (searchStatus.value) {
  //     list = list.filter((row) => (row.statusName || '') === searchStatus.value);
  //   }
  //   if (searchDeptName.value?.trim()) {
  //     const kw = searchDeptName.value.trim().toLowerCase();
  //     list = list.filter(
  //       (row) => (row.associationOtObligationDeptName || '').toLowerCase().includes(kw),
  //     );
  //   }
  //   if (searchDateRange.value?.length === 2) {
  //     const [start, end] = searchDateRange.value;
  //     list = list.filter((row) => {
  //       const t = (row.createdAt || row.associationOtTimeLimit || '').toString().slice(0, 10);
  //       return t >= start && t <= end;
  //     });
  //   }
  //   return list;
  // });

  /** 分页后的列表（前端分页） */
  const paginatedTableData = computed(() => {
    const list = filteredTableData.value;
    const start = (pagination.pageNumber - 1) * pagination.pageSize;
    return list.slice(start, start + pagination.pageSize);
  });

  // watch(
  //   () => filteredTableData.value.length,
  //   (len) => {
  //     pagination.total = len;
  //   },
  //   { immediate: true },
  // );

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    pagination.pageNumber = 1;
  };

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

  /** 列表与顶部信息：直接使用外面的列表接口 queryDrawLessonsAdminPage，再按当前 id 筛出当前记录 */
  const loadList = async () => {
    try {
      tableConfig.loading = true;
      const query: QueryPageRequest<DrawLessonsQueryParam> = {
        pageNumber: 1,
        pageSize: 9999,
        queryParam: {
          associationOtId: id.value,
          obligationDeptName: searchDeptName.value,
          planStartDate: searchDateRange.value?.[0],
          planEndDate: searchDateRange.value?.[1],
          statusId: activeTab.value ? Number(activeTab.value) : undefined,
          problem: searchKeyword.value,
        },
      };
      const res = await queryDrawLessonsAdminDetailPage(query);
      const records = (res && (res as { records?: unknown[] }).records) ?? [];
      const list = Array.isArray(records) ? records : [];
      if (id.value) {
        const current = list;
        rawTableData.value = current;
        // if (current.length) {
        //   const row = current[0] as { problem?: string; creatorName?: string; createdAt?: string };
        //   detailData.value = {
        //     problem: row.problem,
        //     creatorName: row.creatorName,
        //     createdAt: row.createdAt,
        //   };
        // } else {
        //   detailData.value = null;
        // }
      } else {
        rawTableData.value = list;
        const first = list[0] as { problem?: string; creatorName?: string; createdAt?: string } | undefined;
        // detailData.value = first
        //   ? { problem: first.problem, creatorName: first.creatorName, createdAt: first.createdAt }
        //   : null;
      }
    } catch (e) {
      console.error('获取举一反三列表失败:', e);
      rawTableData.value = [];
      // detailData.value = null;
    } finally {
      tableConfig.loading = false;
    }
  };

  const getDetail = () => loadList();

  const handleTabChange = () => {
    loadList();
  };

  const handleSearch = () => {
    loadList();
  };

  const handleReset = () => {
    searchStatus.value = '';
    searchDeptName.value = '';
    searchDateRange.value = null;
    searchKeyword.value = '';
    loadList();
  };

  const handleExport = async () => {
    try {
      const response = await exportTheDocumentPost();
      if (response) {
        const fileName = `法律法规管理_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
      loadList();
    } catch (e) {
      console.error('导出举一反三记录失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

  const handleCancel = async (row: any) => {
    ElMessage.info('作废功能待对接接口');
    try {
      await cancellationMessagePost(row.id);
      ElMessage.success('作废成功');
      loadList();
    } catch (e) {
      console.error('作废举一反三记录失败:', e);
      ElMessage.error(e?.message || e?.data || '作废失败，请重试');
    }
  };

  const handleApprove = () => {
    if (!id.value) return;
    router.push({
      name: 'oneByOneManagementItem',
      query: {
        id: String(id.value),
        operate: 'one-by-one-audit-detail',
      },
    });
  };

  onMounted(() => {
    getDetail();
  });
</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 *;

  .safety-platform-container__header {
    padding-bottom: 0 !important;
  }

  .evaluation-header {
    width: 100%;
  }

  .evaluation-title {
    font-size: 20px;
    font-weight: bold;
    margin: 0 0 12px 0;
    color: #333;
  }

  .evaluation-meta {
    margin-bottom: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #666;

    span {
      white-space: nowrap;
    }
  }
</style>
