<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.fileName')">
        <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">
      <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="150" show-overflow-tooltip />
      <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')" width="120" align="center">
        <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="submitter" :label="t('document.document.documentList.submitter')" width="120" align="center" />
      <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.fileName" class="file-name-cell">
            <svg-icon :icon-class="getFileIconClass(scope.row.fileName)" class="file-icon" :size="18" />
            <span class="file-name-text show-overflow-tooltip">{{ scope.row.fileName }}</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="200" align="center" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.url && scope.row.status === 1"
            v-hasPermi="['document:document:audit']"
            type="primary"
            link
            :icon="Select"
            @click="handleAuditClick(scope.row)"
            :title="t('document.document.button.audit')"
          />
          <el-button
            v-if="(scope.row.status === 0 || scope.row.status === 2) && scope.row.submitterId === userStore.userId"
            v-hasPermi="['document:document:submit']"
            type="primary"
            link
            :icon="Upload"
            @click="handleSubmit(scope.row)"
            :title="t('document.document.button.submit')"
          />
          <el-button
            v-if="(scope.row.status === 0 || scope.row.status === 2) && scope.row.submitterId === userStore.userId"
            v-hasPermi="['document:document:confirmSubmit']"
            type="primary"
            link
            icon="Delete"
            @click="handleConfirmSubmit(scope.row)"
            :title="t('document.document.button.confirmSubmit')"
          />
          <el-button
            v-hasPermi="['document:document:mark']"
            type="primary"
            link
            icon="Flag"
            @click="handleMark(scope.row)"
            :title="t('document.document.button.mark')"
          />
          <el-button
            v-if="scope.row.ossId"
            type="primary"
            link
            icon="Download"
            @click="handleDownload(scope.row)"
            :title="t('document.document.button.download')"
          />
          <el-button
            v-hasPermi="['document:document:logAudit']"
            type="primary"
            link
            icon="DocumentCopy"
            @click="handleViewAuditLog(scope.row)"
            :title="t('document.document.button.viewAuditLog')"
          />
          <el-button
            v-if="scope.row.status === 3"
            v-hasPermi="['document:document:filing']"
            type="primary"
            link
            icon="UploadFilled"
            @click="handleArchive(scope.row)"
            :title="t('document.document.button.archive')"
          />
        </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"
    />

    <!-- 标识文档对话框 -->
    <el-dialog v-model="markDialog.visible" :title="markDialog.title" width="500px" append-to-body>
      <el-form ref="markFormRef" :model="markForm" :rules="markRules" label-width="120px">
        <el-form-item :label="t('document.document.markForm.specification')" prop="type">
          <el-select v-model="markForm.type" :placeholder="t('document.document.markForm.specificationPlaceholder')" clearable style="width: 100%">
            <el-option 
              v-for="dict in getSpecificationDict(currentDocument?.specificationType)" 
              :key="dict.value" 
              :label="parseI18nName(dict.label)" 
              :value="dict.value" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="markButtonLoading" type="primary" @click="submitMarkForm">{{ t('document.document.button.submit') }}</el-button>
          <el-button @click="cancelMark">{{ t('document.document.button.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 递交文档对话框 -->
    <el-dialog v-model="submitDialog.visible" :title="submitDialog.title" width="500px" append-to-body>
      <el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="120px">
        <el-form-item :label="t('document.document.submitForm.file')" prop="ossId">
          <fileUpload v-model="submitForm.ossId" :limit="1" :action="'/common/resource/oss/upload'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="submitButtonLoading" type="primary" @click="submitSubmitForm">{{ t('document.document.button.submit') }}</el-button>
          <el-button @click="cancelSubmit">{{ t('document.document.button.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文档审核记录对话框 -->
    <AuditLogDialog 
      v-model:visible="auditLogDialog.visible" 
      :document-id="auditLogDialog.documentId" 
      :api-function="listDocumentAuditLog"
      i18n-prefix="document.document"
    />

    <!-- 归档确认对话框 -->
    <ArchiveConfirmDialog v-model="archiveDialog.visible" :document="archiveDialog.currentDocument" @confirm="handleArchiveConfirm" />

    <!-- 审核文档对话框 -->
    <DocumentAuditDialog
      v-model="auditDialog.visible"
      :document="auditDialog.document"
      :title="t('document.document.dialog.auditDocument')"
      @success="getDocumentList"
    />
  </div>
  <el-empty v-else :description="t('document.document.empty.description')"> </el-empty>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, getCurrentInstance, computed, watch, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import {
  listDocument,
  markDocument,
  submitDocument,
  confirmSubmit,
  filingDocument,
  downloadDocumentFile
} from '@/api/document/document';
import { DocumentQuery, DocumentVO, DocumentMarkForm, DocumentSubmitForm } 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 { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { parseTime } from '@/utils/ruoyi';
import { parseI18nName } from '@/utils/i18n';
import fileUpload from '@/components/FileUpload/index.vue';
import AuditLogDialog from '@/components/AuditLogDialog/index.vue';
import { listDocumentAuditLog } from '@/api/document/document';
import ArchiveConfirmDialog from './components/ArchiveConfirmDialog.vue';
import DocumentAuditDialog from './components/DocumentAuditDialog.vue';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';

interface Props {
  selectedFolder: FolderListVO | null;
  treeData: FolderListVO[];
}

const props = defineProps<Props>();

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 markDialog = reactive({
  visible: false,
  title: ''
});

// 标识表单ref
const markFormRef = ref<FormInstance>();
const markButtonLoading = ref(false);

// 标识表单数据
const markForm = ref<DocumentMarkForm>({
  id: 0,
  type: ''
});

// 标识表单验证规则
const markRules = {
  type: [{ required: true, message: t('document.document.markRule.typeRequired'), trigger: 'change' }]
};

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

// 递交表单ref
const submitFormRef = ref<FormInstance>();
const submitButtonLoading = ref(false);

// 递交表单数据
interface SubmitForm {
  ossId: string;
}

const submitForm = ref<SubmitForm>({
  ossId: ''
});

// 递交表单验证规则
const submitRules = reactive({
  ossId: [
    {
      required: true,
      message: t('document.document.submitRule.fileRequired'),
      trigger: 'blur'
    }
  ]
});

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

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

// 归档对话框
const archiveDialog = reactive({
  visible: false,
  currentDocument: null as DocumentVO | null
});

// 审核对话框状态
const auditDialog = reactive({
  visible: false,
  document: null as DocumentVO | null
});

/**
 * 根据 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) => {
  auditDialog.document = row;
  auditDialog.visible = true;
};

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

  await downloadDocumentFile(row.ossId, row.fileName || row.name);
};

// 递交文档
const handleSubmit = (row: DocumentVO) => {
  currentDocument.value = row;
  submitForm.value = {
    ossId: ''
  };
  submitDialog.visible = true;
  submitDialog.title = t('document.document.dialog.submitDocument');
  nextTick(() => {
    submitFormRef.value?.clearValidate();
  });
};

// 取消递交
const cancelSubmit = () => {
  submitDialog.visible = false;
  submitForm.value = {
    ossId: ''
  };
  currentDocument.value = null;
};

// 提交递交表单
const submitSubmitForm = () => {
  submitFormRef.value?.validate(async (valid: boolean) => {
    if (valid && currentDocument.value) {
      submitButtonLoading.value = true;
      try {
        const submitData: DocumentSubmitForm = {
          documentId: currentDocument.value.id,
          ossId: submitForm.value.ossId
        };
        await submitDocument(submitData);
        proxy?.$modal.msgSuccess(t('document.document.message.submitSuccess'));
        submitDialog.visible = false;
        await getDocumentList();
      } catch (error) {
        console.error(t('document.document.message.submitFailed'), error);
      } finally {
        submitButtonLoading.value = false;
      }
    }
  });
};

// 确认递交文档
const handleConfirmSubmit = async (row: DocumentVO) => {
  try {
    await ElMessageBox.confirm('确认该文件已成功递交？', '操作确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });

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

// 归档文档
const handleArchive = (row: DocumentVO) => {
  archiveDialog.currentDocument = row;
  archiveDialog.visible = true;
};

// 处理归档确认
const handleArchiveConfirm = async (row: DocumentVO) => {
  try {
    await filingDocument(row.id);
    ElMessage.success(t('document.document.message.archiveSuccess'));
    archiveDialog.visible = false;
    await getDocumentList();
  } catch (error) {
    console.error(t('document.document.message.archiveFailed'), error);
    ElMessage.error(t('document.document.message.archiveFailed'));
  }
};

// 标识文档
const handleMark = (row: DocumentVO) => {
  currentDocument.value = row;
  markForm.value = {
    id: row.id,
    type: ''
  };
  markDialog.visible = true;
  markDialog.title = t('document.document.dialog.markDocument');
  nextTick(() => {
    markFormRef.value?.clearValidate();
  });
};

// 取消标识
const cancelMark = () => {
  markDialog.visible = false;
  markForm.value = {
    id: 0,
    type: ''
  };
  currentDocument.value = null;
};

// 提交标识表单
const submitMarkForm = () => {
  markFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      markButtonLoading.value = true;
      try {
        await markDocument(markForm.value);
        proxy?.$modal.msgSuccess(t('document.document.message.markSuccess'));
        markDialog.visible = false;
        await getDocumentList();
      } catch (error) {
        console.error(t('document.document.message.markFailed'), error);
      } finally {
        markButtonLoading.value = false;
      }
    }
  });
};

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

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