<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ t('document.document.header.title') }}</span>
          <el-button type="primary" @click="handleBack">{{ t('document.document.header.backToList') }}</el-button>
        </div>
      </template>

      <div class="content-wrapper">
        <!-- 文件夹树组件 -->
        <FolderTree
          ref="folderTreeRef"
          :project-id="projectId"
          @folder-click="handleFolderClick"
          @add-document="handleAddDocument"
          @refresh="handleTreeRefresh"
        />

        <!-- 文档列表组件 -->
        <div class="content-container">
          <DocumentList ref="documentListRef" :selected-folder="selectedFolder" :tree-data="treeData" />
        </div>
      </div>
    </el-card>

    <!-- 添加文档对话框 -->
    <el-dialog v-model="documentDialog.visible" :title="documentDialog.title" width="700px" append-to-body>
      <el-form ref="documentFormRef" :model="documentForm" :rules="documentRules" label-width="140px">
        <el-form-item
          :label="documentForm.type === 1 ? t('document.document.documentForm.planName') : t('document.document.documentForm.name')"
          prop="name"
        >
          <el-input v-model="documentForm.name" :placeholder="t('document.document.documentForm.namePlaceholder')" clearable />
        </el-form-item>

        <el-form-item :label="t('document.document.documentForm.type')" prop="type" v-if="hasAddPlanPermission">
          <el-radio-group v-model="documentForm.type" @change="handleDocumentTypeChange">
            <el-radio :label="0">{{ t('document.document.documentForm.normalDocument') }}</el-radio>
            <el-radio :label="1">{{ t('document.document.documentForm.planDocument') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="documentForm.type === 1" :label="t('document.document.documentForm.submitter')" prop="submitterId">
          <el-select
            v-model="documentForm.submitterId"
            filterable
            remote
            reserve-keyword
            :placeholder="t('document.document.documentForm.submitterPlaceholder')"
            :remote-method="searchSubmitters"
            :loading="submitterSearchLoading"
            style="width: 100%"
          >
            <el-option
              v-for="submitter in submitterOptions"
              :key="submitter.id"
              :label="`${submitter.name} / ${submitter.dept} --- ${submitter.phoneNumber}`"
              :value="submitter.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="documentForm.type === 1" :label="t('document.document.documentForm.submitDeadline')" prop="submitDeadline">
          <el-date-picker
            v-model="documentForm.submitDeadline"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="t('document.document.documentForm.submitDeadlinePlaceholder')"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item v-if="documentForm.type === 1" :label="t('document.document.documentForm.planType')" prop="planType">
          <el-select
            v-model="documentForm.planType"
            :placeholder="t('document.document.documentForm.planTypePlaceholder')"
            clearable
            style="width: 100%"
          >
            <el-option v-for="dict in plan_document_type" :key="dict.value" :label="parseI18nName(dict.label)" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('document.document.documentForm.file')" :prop="documentForm.type === 0 ? 'ossId' : ''">
          <fileUpload v-model="uploadedFileId" :limit="1" />
        </el-form-item>

        <el-form-item v-if="documentForm.submitTime" :label="t('document.document.documentForm.submitTime')">
          <el-input v-model="documentForm.submitTime" disabled />
        </el-form-item>

        <el-form-item :label="t('document.document.documentForm.note')" prop="note">
          <el-input v-model="documentForm.note" type="textarea" :rows="4" :placeholder="t('document.document.documentForm.notePlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="documentButtonLoading" type="primary" @click="submitDocumentForm">{{
            t('document.document.button.submit')
          }}</el-button>
          <el-button @click="cancelDocument">{{ t('document.document.button.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, watch, computed, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { addDocument } from '@/api/document/document';
import { DocumentForm } from '@/api/document/document/types';
import { FolderListVO } from '@/api/document/folder/types';
import { queryMemberNotInCenter } from '@/api/project/management';
import { MemberNotInCenterVO, MemberNotInCenterQuery } from '@/api/project/management/types';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { checkPermi } from '@/utils/permission';
import { parseI18nName } from '@/utils/i18n';
import fileUpload from '@/components/FileUpload/index.vue';
import FolderTree from './FolderTree.vue';
import DocumentList from './DocumentList.vue';

interface Props {
  projectId?: number | string;
}

const props = defineProps<Props>();

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

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

// 组件引用
const folderTreeRef = ref<InstanceType<typeof FolderTree>>();
const documentListRef = ref<InstanceType<typeof DocumentList>>();
const documentFormRef = ref<FormInstance>();

// 当前选中的文件夹
const selectedFolder = ref<FolderListVO | null>(null);

// 树数据（用于传递给DocumentList）
const treeData = ref<FolderListVO[]>([]);

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

const documentButtonLoading = ref(false);

// 检查是否有计划文档添加权限
const hasAddPlanPermission = computed(() => checkPermi(['document:document:addPlan']));

// 文档表单初始数据
const initDocumentFormData: DocumentForm = {
  id: undefined,
  name: '',
  type: 0,
  submitterId: undefined,
  folderId: undefined,
  submitDeadline: undefined,
  planType: undefined,
  ossId: undefined,
  submitTime: undefined,
  projectId: props.projectId,
  note: ''
};

// 文件上传的ossId
const uploadedFileId = ref<string>('');

// 文档表单数据
const documentForm = ref<DocumentForm>({ ...initDocumentFormData });

// 递交人搜索相关
const submitterSearchLoading = ref(false);
const submitterOptions = ref<MemberNotInCenterVO[]>([]);
let submitterSearchTimer: NodeJS.Timeout | null = null;

// 文档表单验证规则
const documentRules = {
  name: [{ required: true, message: t('document.document.documentRule.nameRequired'), trigger: 'blur' }],
  submitterId: [{ required: true, message: t('document.document.documentRule.submitterRequired'), trigger: 'change' }],
  ossId: [{ required: true, message: t('document.document.documentRule.fileRequired'), trigger: 'change' }]
};

// 返回项目列表
const handleBack = () => {
  emit('back');
};

// 处理文件夹点击
const handleFolderClick = (folder: FolderListVO) => {
  // 只有文件夹类型(type=0)才显示文档列表
  if (folder.type === 0) {
    selectedFolder.value = folder;
  } else {
    selectedFolder.value = null;
  }
};

// 处理添加文档
const handleAddDocument = (folder: FolderListVO) => {
  resetDocumentForm();
  documentForm.value.folderId = folder.id;
  documentDialog.visible = true;
  documentDialog.title = t('document.document.dialog.addDocument');
};

// 处理树刷新
const handleTreeRefresh = () => {
  // 刷新树数据以传递给DocumentList
  if (folderTreeRef.value) {
    // 可以通过ref访问子组件的数据
    treeData.value = (folderTreeRef.value as any).treeData || [];
  }
};

// 重置文档表单
const resetDocumentForm = () => {
  documentForm.value = { ...initDocumentFormData };
  uploadedFileId.value = '';
  if (!hasAddPlanPermission.value) {
    documentForm.value.type = 0;
  }
  documentForm.value.submitterId = userStore.userId;
  documentForm.value.projectId = props.projectId;
  submitterOptions.value = [];
  documentFormRef.value?.resetFields();
};

// 处理文档类型变化
const handleDocumentTypeChange = (value: number) => {
  if (value === 0) {
    documentForm.value.submitterId = userStore.userId;
    documentForm.value.submitDeadline = undefined;
    documentForm.value.planType = undefined;
  } else {
    documentForm.value.submitterId = undefined;
  }
};

// 搜索递交人
const searchSubmitters = async (query: string) => {
  if (!query || query.trim() === '') {
    submitterOptions.value = [];
    return;
  }

  if (submitterSearchTimer) {
    clearTimeout(submitterSearchTimer);
  }

  submitterSearchTimer = setTimeout(async () => {
    submitterSearchLoading.value = true;
    try {
      const queryParams: MemberNotInCenterQuery = {
        pageNum: 1,
        pageSize: 10,
        projectId: props.projectId || 0,
        folderId: 0,
        name: query
      };
      const res = await queryMemberNotInCenter(queryParams);
      submitterOptions.value = res.rows || [];
    } catch (error) {
      console.error('Failed to search submitters:', error);
      ElMessage.error(t('document.document.message.searchSubmitterFailed'));
    } finally {
      submitterSearchLoading.value = false;
    }
  }, 300);
};

// 监听文件上传变化
watch(uploadedFileId, (newVal) => {
  if (newVal) {
    const ids = newVal.split(',').filter((id) => id.trim());
    if (ids.length > 0) {
      documentForm.value.ossId = parseInt(ids[0]);
      const now = new Date();
      documentForm.value.submitTime = proxy?.parseTime(now, '{y}-{m}-{d} {h}:{i}:{s}');

      if (documentForm.value.type === 0) {
        documentForm.value.submitterId = userStore.userId;
      }
    }
  } else {
    documentForm.value.ossId = undefined;
    documentForm.value.submitTime = undefined;
    documentForm.value.submitterId = undefined;
  }
});

// 取消文档对话框
const cancelDocument = () => {
  resetDocumentForm();
  documentDialog.visible = false;
};

// 提交文档表单
const submitDocumentForm = () => {
  documentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      documentButtonLoading.value = true;
      try {
        const hasUploadedFile = !!uploadedFileId.value;

        const submitData: DocumentForm = {
          id: documentForm.value.id || 0,
          name: documentForm.value.name || '',
          type: documentForm.value.type !== undefined ? documentForm.value.type : 0,
          submitterId: documentForm.value.submitterId || (documentForm.value.type === 0 ? userStore.userId : 0),
          folderId: documentForm.value.folderId || 0,
          submitDeadline: documentForm.value.submitDeadline || '',
          planType: documentForm.value.planType || '',
          ossId: hasUploadedFile ? uploadedFileId.value : null,
          submitTime: documentForm.value.submitTime || (hasUploadedFile ? new Date().toISOString() : ''),
          projectId: documentForm.value.projectId || props.projectId,
          status: hasUploadedFile ? 1 : 0,
          note: documentForm.value.note || ''
        };

        await addDocument(submitData);
        proxy?.$modal.msgSuccess(t('document.document.message.addDocumentSuccess'));
        documentDialog.visible = false;
        // 刷新文档列表
        documentListRef.value?.getDocumentList();
      } catch (error) {
        console.error(t('document.document.message.addDocumentFailed'), error);
      } finally {
        documentButtonLoading.value = false;
      }
    }
  });
};
</script>

<style scoped lang="scss">
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.text-lg {
  font-size: 1.125rem;
}

.font-bold {
  font-weight: 700;
}

.content-wrapper {
  display: flex;
  height: calc(100vh - 250px);
  min-height: 500px;
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}
</style>
