<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.evaluationTableName"
                  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 EVALUATION_SYSTEM_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div>
                <span>计划日期范围：</span>
                <el-date-picker
                  v-model="tableQuery.queryParam.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"
            @update:selection="handleSelectionChange"
          >
            <template #status="scope">
              <span>
                {{ EVALUATION_SYSTEM_STATUS_LABEL[String(scope.row.status)] || scope.row.statusName || '-' }}
              </span>
            </template>
            <template #evaluationDocument="scope">
              <div
                class="file-container--div"
                v-for="item in parseAttachments(scope.row.evaluationDocument)"
                :key="item.fileUrl"
              >
                <img
                  class="file-container--div__icon"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  :src="FILE_TYPE_ICON[item.fileType]"
                />
                <span
                  class="file-container--div__name"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  >{{ item.fileName }}</span
                >
                <img
                  class="file-container--div__download"
                  :src="DownloadIcon"
                  @click="downloadFile(item.fileUrl, item.fileName)"
                />
              </div>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 待反馈(2)：显示反馈 -->
                <template v-if="Number(scope.row.status) === 2">
                  <ActionButton text="反馈" @click="handleFeedback(scope.row.id)" />
                </template>
                <!-- 已完成(1)：显示反馈和先进个人申报 -->
                <template v-else-if="Number(scope.row.status) === 1">
                  <!-- <ActionButton text="反馈" @click="handleFeedback(scope.row.id)" /> -->
                  <ActionButton text="先进个人申报" @click="handleAdvancedPerson(scope.row)" />
                </template>
                <!-- 已作废(5)：显示反馈 -->
                <template v-else-if="Number(scope.row.status) === 5">
                  <ActionButton text="反馈" @click="handleFeedback(scope.row.id)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script lang="ts" setup>
  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, EVALUATION_DEPARTMENT_TABLE_COLUMNS } from './configs/tables';
  import { EVALUATION_SYSTEM_STATUS_OPTIONS, EVALUATION_SYSTEM_STATUS_LABEL } from '../evaluationSystem/configs/status';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import { downloadFile } from '@/views/disaster/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import { querySecurityExamineDept } from '@/api/evaluationSystem';
  import type { QuerySecurityExamineDeptParams } from '@/api/evaluationSystem';

  const router = useRouter();

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

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

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

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      evaluationTableName: '',
      status: undefined as number | undefined,
      dateRange: null,
      startTime: '',
      endTime: '',
    },
  });

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

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

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

  const handleSelectionChange = (selection: any[]) => {
    selectionItems.value = selection;
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const params: QuerySecurityExamineDeptParams = {
        pageNumber: tableQuery.pageNumber,
        pageSize: tableQuery.pageSize,
        queryParam: {
          exName: tableQuery.queryParam.evaluationTableName || undefined,
          status: tableQuery.queryParam.status !== undefined && tableQuery.queryParam.status !== null
            ? tableQuery.queryParam.status
            : undefined,
          deptName: undefined, // 部门名称（如果需要可以添加搜索条件）
          planStartTime: tableQuery.queryParam.startTime || undefined,
          planEndTime: tableQuery.queryParam.endTime || undefined,
        },
      };

      const res = await querySecurityExamineDept(params);
      if (res) {
        // 映射返回数据字段到表格字段
        tableData.value = res.records.map((item) => ({
          id: item.id,
          evaluationTableName: item.exName, // 考核表名称
          status: item.status, // 状态（使用数字状态码）
          statusName: item.statusName, // 状态名称
          evaluationDocument: item.attachments, // 考核文档
          plannedCompletionTime: item.planEndTime || '-', // 计划完成时间（使用计划结束时间）
          // 保留原始数据，供其他操作使用
          psemId: item.psemId,
          deptId: item.deptId,
          deptName: item.deptName,
          scores: item.scores,
          scoreRank: item.scoreRank,
          isAdvancedGroup: item.isAdvancedGroup,
        }));
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取部门考核列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

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

  const handleReset = () => {
    tableQuery.queryParam.evaluationTableName = '';
    tableQuery.queryParam.status = undefined;
    tableQuery.queryParam.dateRange = null;
    handleSearch();
  };

  const handleFeedback = (id: number) => {
    router.push({
      name: 'EvaluationDepartmentItem',
      query: {
        id,
        operate: 'evaluationDepartment-feedback',
      },
    });
  };

  const handleAdvancedPerson = (row: any) => {
    router.push({
      name: 'EvaluationDepartmentItem',
      query: {
        id: row.id,
        operate: 'evaluationDepartment-advanced-person',
        isAdvancedGroup: row.isAdvancedGroup,
      },
    });
  };

  // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type: keyof typeof FILE_TYPE_ICON) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  // 解析逗号分隔的URL字符串为文件列表
  const parseAttachments = (attachmentsStr: string | undefined): Array<{
    fileUrl: string;
    fileName: string;
    fileType: string;
  }> => {
    if (!attachmentsStr || !attachmentsStr.trim()) {
      return [];
    }

    // 按逗号分割URL
    const urls = attachmentsStr.split(',').map(url => url.trim()).filter(url => url);

    return urls.map((url) => {
      // 从URL中提取文件名
      const urlParts = url.split('/');
      const fileName = urlParts[urlParts.length - 1] || '未知文件';

      // 根据文件扩展名判断文件类型
      const extension = fileName.split('.').pop()?.toLowerCase() || '';
      let fileType = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }

      return {
        fileUrl: url,
        fileName,
        fileType,
      };
    });
  };

  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 '@/styles/basic-table-file.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;
</style>
