<template>
  <div v-if="selectedFolder" class="document-list-container">
    <!-- 搜索栏 -->
    <el-form :model="documentQueryParams" :inline="true" class="search-form">
      <el-form-item :label="t('document.document.documentList.name')">
        <el-input
          v-model="documentQueryParams.name"
          :placeholder="t('document.document.documentList.fileNamePlaceholder')"
          clearable
          style="width: 240px"
          @keyup.enter="handleDocumentQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleDocumentQuery">
          {{ t('document.document.button.search') }}
        </el-button>
        <el-button icon="Refresh" @click="handleDocumentReset">{{ t('document.document.button.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 文档列表 -->
    <el-table v-loading="documentLoading" :data="documentList" border style="margin-top: 10px; width: 100%">
      <el-table-column prop="id" width="55" align="center" :label="t('document.document.documentList.index')">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        :label="t('document.document.documentList.name')"
        min-width="350"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ formatDocumentName(scope.row.name) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="specification"
        :label="t('document.document.documentList.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="planType"
        :label="t('document.document.documentList.planDocumentType')"
        min-width="120"
        align="center"
        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('document.document.documentList.status')" width="120" align="center">
        <template #default="scope">
          <DocumentStatusTag :status="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        prop="planSubmitterName"
        :label="t('document.document.documentList.planSubmitter')"
        width="120"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="submitterName"
        :label="t('document.document.documentList.submitter')"
        width="120"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="submitDeadline"
        :label="t('document.document.documentList.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('document.document.documentList.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="url" :label="t('document.document.documentList.url')" min-width="200">
        <template #default="scope">
          <div v-if="scope.row.actualDocumentName" class="file-name-cell">
            <svg-icon :icon-class="getFileIconClass(scope.row.actualDocumentName)" class="file-icon" :size="18" />
            <span class="file-name-text show-overflow-tooltip">{{ scope.row.actualDocumentName }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="note"
        :label="t('document.document.documentList.note')"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="createTime"
        :label="t('document.document.documentList.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('document.document.documentList.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('document.document.documentList.action')" width="480" align="center" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.folderId === 0">
            <!-- 临时文件夹只显示删除按钮 -->
            <el-button
              v-hasPermi="['document:document:specify']"
              type="primary"
              icon="Position"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleSpecify(scope.row)"
            >
              {{ t('document.document.button.specify') }}
            </el-button>
            <el-button
              v-hasPermi="['document:document:removeTemp']"
              type="danger"
              icon="Delete"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleDeleteTemp(scope.row)"
            >
              {{ t('document.document.menu.delete') }}
            </el-button>
          </template>
          <template v-else>
            <el-button
              v-if="scope.row.actualDocument && scope.row.status === 1"
              v-hasPermi="['document:document:audit']"
              type="primary"
              :icon="Select"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleAuditClick(scope.row)"
            >
              {{ t('document.document.button.audit') }}
            </el-button>
            <el-button
              v-if="(scope.row.status === 0 || scope.row.status === 2) && scope.row.planSubmitter === userStore.userId"
              v-hasPermi="['document:document:submit']"
              type="success"
              :icon="Upload"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleSubmit(scope.row)"
            >
              {{ t('document.document.button.submit') }}
            </el-button>
            <el-button
              v-if="scope.row.status === 0 || scope.row.status === 2"
              v-hasPermi="['document:document:confirmSubmit']"
              type="danger"
              icon="Delete"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleConfirmSubmit(scope.row)"
            >
              {{ t('document.document.button.confirmSubmit') }}
            </el-button>
            <el-button
              v-if="!scope.row.specification"
              v-hasPermi="['document:document:mark']"
              type="warning"
              icon="Flag"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleMark(scope.row)"
            >
              {{ t('document.document.button.mark') }}
            </el-button>
            <el-button
              v-if="scope.row.actualDocument"
              type="info"
              icon="Download"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleDownload(scope.row)"
            >
              {{ t('document.document.button.download') }}
            </el-button>
            <el-button
              v-hasPermi="['document:document:logAudit']"
              type="primary"
              icon="DocumentCopy"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleViewAuditLog(scope.row)"
            >
              {{ t('document.document.button.viewAuditLog') }}
            </el-button>
            <el-button
              v-if="scope.row.status === 3"
              v-hasPermi="['document:document:filing']"
              type="success"
              icon="UploadFilled"
              style="padding: 0 5px; font-size: 10px; height: 24px; --el-button-icon-span-gap: 2px"
              @click="handleArchive(scope.row)"
            >
              {{ t('document.document.button.archive') }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="documentTotal > 0"
      v-model:page="documentQueryParams.pageNum"
      v-model:limit="documentQueryParams.pageSize"
      :total="documentTotal"
      @pagination="getDocumentList"
    />

    <!-- 标识文档对话框 -->
    <MarkDialog
      v-model="markDialog.visible"
      :document="currentDocument"
      :specification-dict="getSpecificationDict(currentDocument?.specificationType)"
      @success="handleDialogSuccess"
    />

    <!-- 递交文档对话框 -->
    <SubmitDialog v-model="submitDialog.visible" :document="currentDocument" @success="handleDialogSuccess" />

    <!-- 审核文档对话框 -->
    <DocumentAuditDialog v-model="auditDialog.visible" :document="currentDocument" @submit="handleAuditSubmit" />

    <!-- 指定文档对话框 -->
    <SpecifyDialog
      v-model="specifyDialog.visible"
      :document="currentDocument"
      :tree-data="treeData"
      :project-id="projectId"
      @success="handleSpecifySuccess"
    />

    <!-- 文档审核记录对话框 -->
    <AuditLogDialog
      v-model:visible="auditLogDialog.visible"
      :document-id="auditLogDialog.documentId"
      :api-function="listDocumentAuditLog"
    />
  </div>
  <el-empty v-else :description="t('document.document.empty.description')"> </el-empty>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, watch, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { listDocument, confirmSubmit, filingDocument, downloadDocumentFile, removeTempDocument, auditDocument } from '@/api/document/document';
import { DocumentQuery, DocumentVO } from '@/api/document/document/types';
import { FolderListVO } from '@/api/document/folder/types';
import { Select, Upload } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { parseTime, formatDocumentName } from '@/utils/ruoyi';
import AuditLogDialog from '@/components/AuditLogDialog/index.vue';
import { listDocumentAuditLog } from '@/api/document/document';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';
import MarkDialog from './components/MarkDialog.vue';
import SubmitDialog from './components/SubmitDialog.vue';
import DocumentAuditDialog from '@/components/DocumentAuditDialog/index.vue';
import SpecifyDialog from './components/SpecifyDialog.vue';

interface Props {
  selectedFolder: FolderListVO | null;
  treeData: FolderListVO[];
  projectId?: number | string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  refreshTree: [];
}>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { t } = useI18n();
const userStore = useUserStore();
const { plan_document_type, center_file_specification, project_file_specification } = toRefs<any>(
  proxy?.useDict('plan_document_type', 'center_file_specification', 'project_file_specification')
);

// 文档列表数据
const documentList = ref<DocumentVO[]>([]);
const documentLoading = ref(false);
const documentTotal = ref(0);

// 文档查询参数
const documentQueryParams = reactive<DocumentQuery>({
  pageNum: 1,
  pageSize: 10,
  name: '',
  folderId: undefined
});

// 当前操作的文档
const currentDocument = ref<DocumentVO | null>(null);

// 标识文档对话框
const markDialog = reactive({
  visible: false
});

// 递交文档对话框
const submitDialog = reactive({
  visible: false
});

// 审核对话框
const auditDialog = reactive({
  visible: false
});

// 指定文档对话框
const specifyDialog = reactive({
  visible: false
});

// 审核记录对话框
const auditLogDialog = reactive({
  visible: false,
  documentId: ''
});

/**
 * 根据 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 getDocumentList = async () => {
  if (!props.selectedFolder) return;

  documentLoading.value = true;
  documentQueryParams.folderId = props.selectedFolder.id;

  try {
    const res = await listDocument(documentQueryParams);
    documentList.value = res.rows || [];
    documentTotal.value = res.total || 0;
  } catch (error) {
    console.error('Failed to get document list:', error);
    ElMessage.error(t('document.document.message.getDocumentListFailed'));
  } finally {
    documentLoading.value = false;
  }
};

// 搜索按钮
const handleDocumentQuery = () => {
  documentQueryParams.pageNum = 1;
  getDocumentList();
};

// 重置按钮
const handleDocumentReset = () => {
  documentQueryParams.name = '';
  documentQueryParams.pageNum = 1;
  getDocumentList();
};

// 查看审核记录
const handleViewAuditLog = (row: DocumentVO) => {
  auditLogDialog.documentId = row.id;
  auditLogDialog.visible = true;
};

// 审核按钮点击事件
const handleAuditClick = (row: DocumentVO) => {
  currentDocument.value = row;
  auditDialog.visible = true;
};

// 处理审核提交
const handleAuditSubmit = async (data: any) => {
  try {
    await auditDocument(data);
    ElMessage.success(t('document.document.message.auditSuccess'));
    auditDialog.visible = false;
    await getDocumentList();
  } catch (error) {
    console.error('审核失败:', error);
    ElMessage.error(t('document.document.message.auditFailed'));
  }
};

// 下载文档
const handleDownload = async (row: DocumentVO) => {
  if (!row.actualDocument) {
    ElMessage.warning(t('document.document.message.noFileToDownload'));
    return;
  }

  await downloadDocumentFile(row.actualDocument, row.actualDocumentName || row.name);
};

// 递交文档
const handleSubmit = (row: DocumentVO) => {
  currentDocument.value = row;
  submitDialog.visible = true;
};

// 确认递交文档
const handleConfirmSubmit = async (row: DocumentVO) => {
  try {
    await ElMessageBox.confirm(
      t('document.document.message.confirmSubmitMessage'),
      t('document.document.message.confirmSubmitTitle'),
      {
        confirmButtonText: t('document.document.message.confirmButton'),
        cancelButtonText: t('document.document.message.cancelButton'),
        type: 'warning'
      }
    );

    await confirmSubmit(row.id);
    ElMessage.success(t('document.document.message.confirmSubmitSuccess'));
    await getDocumentList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认递交失败:', error);
      ElMessage.error(t('document.document.message.confirmSubmitFailed'));
    }
  }
};

// 归档文档
const handleArchive = async (row: DocumentVO) => {
  try {
    await proxy?.$modal.confirm(t('document.document.message.archiveConfirm'));
    await filingDocument(row.id as number);
    ElMessage.success(t('document.document.message.archiveSuccess'));
    await getDocumentList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error(t('document.document.message.archiveFailed'), error);
      ElMessage.error(t('document.document.message.archiveFailed'));
    }
  }
};

// 删除临时文件夹中的文档
const handleDeleteTemp = async (row: DocumentVO) => {
  try {
    await proxy?.$modal.confirm(t('document.document.message.deleteTempConfirm'));
    await removeTempDocument(row.id);
    ElMessage.success(t('document.document.message.deleteTempSuccess'));
    await getDocumentList();
    emit('refreshTree');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除临时文档失败:', error);
      ElMessage.error(t('document.document.message.deleteTempFailed'));
    }
  }
};

// 指定文档
const handleSpecify = (row: DocumentVO) => {
  currentDocument.value = row;
  specifyDialog.visible = true;
};

// 标识文档
const handleMark = (row: DocumentVO) => {
  currentDocument.value = row;
  markDialog.visible = true;
};

// 对话框成功回调
const handleDialogSuccess = async () => {
  await getDocumentList();
};

// 指定成功回调
const handleSpecifySuccess = async () => {
  await getDocumentList();
  emit('refreshTree');
};

// 文件类型判断函数
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';
  }
};

// 监听选中文件夹变化
watch(
  () => props.selectedFolder,
  (newFolder) => {
    if (newFolder) {
      documentQueryParams.name = '';
      documentQueryParams.pageNum = 1;
      getDocumentList();
    } else {
      documentList.value = [];
    }
  }
);

// 暴露方法给父组件
defineExpose({
  getDocumentList
});
</script>

<style scoped lang="scss">
.document-list-container {
  width: 100%;

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

  .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;
    }

    .download-btn {
      flex-shrink: 0;
      font-size: 16px;

      &:hover {
        transform: scale(1.1);
      }
    }
  }

  // 确保表格单元格内容不换行
  :deep(.el-table__cell) {
    .cell {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.show-overflow-tooltip {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  cursor: help;
}

.show-overflow-tooltip:hover {
  overflow: visible;
  white-space: normal;
  word-break: break-all;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  z-index: 1000;
  max-width: 300px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}
</style>
