<template>
  <div class="search-container">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ t('search.title') }}</span>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item :label="t('search.search.name')">
          <el-input v-model="queryParams.name" :placeholder="t('search.search.namePlaceholder')" clearable
            style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('search.search.projectCode')">
          <el-input v-model="queryParams.projectCode" :placeholder="t('search.search.projectCodePlaceholder')" clearable
            style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('search.search.projectName')">
          <el-input v-model="queryParams.projectName" :placeholder="t('search.search.projectNamePlaceholder')" clearable
            style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item :label="t('search.search.type')">
          <el-select v-model="queryParams.type" :placeholder="t('search.search.typePlaceholder')" clearable
            style="width: 150px">
            <el-option :label="t('search.type.normalDocument')" :value="0" />
            <el-option :label="t('search.type.planDocument')" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('search.search.status')">
          <el-select v-model="queryParams.status" :placeholder="t('search.search.statusPlaceholder')" clearable
            style="width: 150px">
            <el-option :label="t('search.status.unUpload')" :value="0" />
            <el-option :label="t('search.status.unAudit')" :value="1" />
            <el-option :label="t('search.status.auditReject')" :value="2" />
            <el-option :label="t('search.status.unFiling')" :value="3" />
            <el-option :label="t('search.status.filing')" :value="4" />
            <el-option :label="t('search.status.unQualityControl')" :value="5" />
            <el-option :label="t('search.status.qualityControlPass')" :value="6" />
            <el-option :label="t('search.status.qualityControlReject')" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('search.search.createTime')">
          <el-date-picker v-model="createTimeRange" type="daterange" range-separator="-"
            :start-placeholder="t('search.search.startTime')" :end-placeholder="t('search.search.endTime')"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 240px" />
        </el-form-item>
        <el-form-item :label="t('search.search.updateTime')">
          <el-date-picker v-model="updateTimeRange" type="daterange" range-separator="-"
            :start-placeholder="t('search.search.startTime')" :end-placeholder="t('search.search.endTime')"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ t('search.button.search') }}</el-button>
          <el-button icon="Refresh" @click="resetQuery">{{ t('search.button.reset') }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 文档列表 -->
      <el-table v-loading="loading" :data="documentList" border style="margin-top: 10px">
        <el-table-column prop="id" :label="t('search.table.id')" width="80" align="center" />
        <el-table-column prop="folderName" :label="t('search.table.folderName')" min-width="120"
          show-overflow-tooltip />
        <el-table-column prop="name" :label="t('search.table.name')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="type" :label="t('search.table.type')" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 0">{{ t('search.type.normalDocument') }}</span>
            <span v-else-if="scope.row.type === 1">{{ t('search.type.planDocument') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="specificationLabel" :label="t('search.table.specification')" min-width="120"
          show-overflow-tooltip>
          <template #default="scope">
            <dict-tag 
              v-if="scope.row.specification" 
              :options="getSpecificationDict(scope.row.specificationType)" 
              :value="scope.row.specification" 
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="planDocumentTypeLabel" :label="t('search.table.planDocumentType')" min-width="120"
          show-overflow-tooltip>
          <template #default="scope">
            <dict-tag v-if="scope.row.planType" :options="plan_document_type" :value="scope.row.planType" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="t('search.table.status')" width="120" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="submitter" :label="t('search.table.submitter')" width="120" align="center" />
        <el-table-column prop="submitDeadline" :label="t('search.table.submitDeadline')" width="110" align="center">
          <template #default="scope">
            <span v-if="scope.row.submitDeadline">{{ parseTime(scope.row.submitDeadline, '{y}-{m}-{d}') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" :label="t('search.table.submitTime')" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.submitTime">{{ parseTime(scope.row.submitTime) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileName" :label="t('search.table.fileName')" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div v-if="scope.row.fileName" class="file-name-cell">
              <svg-icon :icon-class="getFileIconClass(scope.row.fileName)" class="file-icon" :size="18" />
              <span class="file-name-text">{{ scope.row.fileName }}</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="note" :label="t('search.table.note')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" :label="t('search.table.createTime')" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.createTime">{{ parseTime(scope.row.createTime) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" :label="t('search.table.updateTime')" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.updateTime">{{ parseTime(scope.row.updateTime) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column :label="t('search.table.action')" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" type="primary" link icon="Download"
              @click="handleDownload(scope.row.ossId, scope.row.fileName)" :title="t('search.button.download')" />
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { listSearchDocuments } from '@/api/search';
import { downloadDocumentFile } from '@/api/document/document';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';
import { parseI18nName } from '@/utils/i18n';
import { parseTime } from '@/utils/ruoyi';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as any;

// 获取字典
const { plan_document_type, center_file_specification, project_file_specification } = toRefs<any>(
  proxy?.useDict('plan_document_type', 'center_file_specification', 'project_file_specification')
);

const loading = ref(false);

// 查询参数
const queryParams = reactive({
  name: '',
  projectCode: '',
  projectName: '',
  type: undefined as number | undefined,
  status: undefined as number | undefined,
  params: {},
  pageNum: 1,
  pageSize: 10
});

// 时间范围
const createTimeRange = ref<[string, string]>(['', '']);
const updateTimeRange = ref<[string, string]>(['', '']);

// 文档列表数据
const documentList = ref<any[]>([]);
const total = ref(0);

/**
 * 根据 specificationType 获取对应的字典
 * @param specificationType 规格类型 (0: 中心文件, 1: 项目文件)
 */
const getSpecificationDict = (specificationType: number | undefined) => {
  if (specificationType === 0) {
    return center_file_specification?.value || [];
  } else if (specificationType === 1) {
    return project_file_specification?.value || [];
  }
  // 默认返回空数组
  return [];
};

/**
 * 文件类型判断函数
 */
const isWordFile = (fileName: string): boolean => {
  if (!fileName) return false;
  const lowerFileName = fileName.toLowerCase();
  return lowerFileName.endsWith('.doc') || lowerFileName.endsWith('.docx');
};

const isExcelFile = (fileName: string): boolean => {
  if (!fileName) return false;
  const lowerFileName = fileName.toLowerCase();
  return lowerFileName.endsWith('.xls') || lowerFileName.endsWith('.xlsx') || lowerFileName.endsWith('.csv');
};

const isPPTFile = (fileName: string): boolean => {
  if (!fileName) return false;
  const lowerFileName = fileName.toLowerCase();
  return lowerFileName.endsWith('.ppt') || lowerFileName.endsWith('.pptx');
};

const isPDFFile = (fileName: string): boolean => {
  if (!fileName) return false;
  return fileName.toLowerCase().endsWith('.pdf');
};

/**
 * 获取文件图标类型
 */
const getFileIconClass = (fileName: string): string => {
  if (isWordFile(fileName)) {
    return 'document-word';
  } else if (isExcelFile(fileName)) {
    return 'document-excel';
  } else if (isPPTFile(fileName)) {
    return 'document-ppt';
  } else if (isPDFFile(fileName)) {
    return 'document-pdf';
  } else {
    return 'document-document';
  }
};

/**
 * 获取文档列表
 */
const getList = async () => {
  try {
    loading.value = true;
    // 处理时间范围
    queryParams.params = {};
    proxy?.addDateRange(queryParams, createTimeRange.value, 'CreateTime', 'createTimeEarliest', 'createTimeLatest');
    proxy?.addDateRange(queryParams, updateTimeRange.value, 'UpdateTime', 'updateTimeEarliest', 'updateTimeLatest');

    const res = await listSearchDocuments(queryParams);
    if (res.code === 200) {
      documentList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || t('search.message.fetchFailed'));
    }
  } catch (error) {
    console.error(t('search.message.fetchFailed'), error);
    ElMessage.error(t('search.message.fetchFailed'));
  } finally {
    loading.value = false;
  }
};

/**
 * 处理搜索
 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryParams.name = '';
  queryParams.projectCode = '';
  queryParams.projectName = '';
  queryParams.type = undefined;
  queryParams.status = undefined;
  createTimeRange.value = ['', ''];
  updateTimeRange.value = ['', ''];
  handleQuery();
};

/**
 * 下载文件
 */
const handleDownload = async (ossId: number, fileName: string) => {
  if (!ossId) return;
  await downloadDocumentFile(ossId, fileName);
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.search-container {
  padding: 20px;

  .search-form {
    margin-bottom: 15px;
  }

  :deep(.el-table) {
    .cell {
      white-space: nowrap;
    }
  }

  .file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 8px;

    .file-icon {
      flex-shrink: 0;
      width: 18px;
      height: 18px;
      vertical-align: middle;
    }

    .file-name-text {
      flex: 1;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
