<template>
  <el-dialog v-model="visible" :title="title" width="900px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
      <el-form-item :label="t('document.document.specifyForm.type')" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio label="missing">{{ t('document.document.specifyForm.specifyMissing') }}</el-radio>
          <el-radio label="folder">{{ t('document.document.specifyForm.specifyFolder') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('document.document.specifyForm.language')" prop="language">
        <el-input v-model="form.language" :placeholder="t('document.document.specifyForm.languagePlaceholder')" clearable style="width: 100%" />
      </el-form-item>
      <el-form-item :label="t('document.document.specifyForm.version')" prop="version">
        <el-input v-model="form.version" :placeholder="t('document.document.specifyForm.versionPlaceholder')" clearable style="width: 100%" />
      </el-form-item>
      <el-form-item :label="t('document.document.specifyForm.versionDate')" prop="versionDate">
        <el-date-picker
          v-model="form.versionDate"
          type="date"
          value-format="YYYY-MM-DD"
          :placeholder="t('document.document.specifyForm.versionDatePlaceholder')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="t('document.document.specifyForm.ethicsSubmissionDate')" prop="ethicsSubmissionDate">
        <el-date-picker
          v-model="form.ethicsSubmissionDate"
          type="date"
          value-format="YYYY-MM-DD"
          :placeholder="t('document.document.specifyForm.ethicsSubmissionDatePlaceholder')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="t('document.document.specifyForm.ethicsApprovalDate')" prop="ethicsApprovalDate">
        <el-date-picker
          v-model="form.ethicsApprovalDate"
          type="date"
          value-format="YYYY-MM-DD"
          :placeholder="t('document.document.specifyForm.ethicsApprovalDatePlaceholder')"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <!-- 指定递交缺失时显示文档列表 -->
    <div v-if="form.type === 'missing'" style="margin-top: 20px">
      <!-- 搜索栏 -->
      <el-form :inline="true" style="margin-bottom: 10px">
        <el-form-item>
          <el-input
            v-model="searchName"
            :placeholder="t('document.document.specifyForm.searchPlaceholder')"
            clearable
            style="width: 240px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">
            {{ t('document.document.button.search') }}
          </el-button>
          <el-button icon="Refresh" @click="handleReset">{{ t('document.document.button.reset') }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 文档列表 -->
      <el-table v-loading="documentLoading" :data="documentList" border style="width: 100%">
        <el-table-column
          prop="name"
          :label="t('document.document.specifyForm.documentName')"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="folder"
          :label="t('document.document.specifyForm.folder')"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column prop="status" :label="t('document.document.specifyForm.status')" width="100" align="center">
          <template #default="scope">
            <DocumentStatusTag :status="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column
          prop="deadline"
          :label="t('document.document.specifyForm.deadline')"
          width="160"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.deadline">{{ parseTime(scope.row.deadline) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="planSubmitter"
          :label="t('document.document.specifyForm.planSubmitter')"
          width="120"
          align="center"
        />
        <el-table-column
          prop="createBy"
          :label="t('document.document.specifyForm.createBy')"
          width="120"
          align="center"
        />
        <el-table-column
          prop="createTime"
          :label="t('document.document.specifyForm.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 :label="t('document.document.specifyForm.action')" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button v-if="selectedDocumentId !== scope.row.id" type="primary" size="small" @click="handleSelectDocument(scope.row.id)">
              {{ t('document.document.specifyForm.select') }}
            </el-button>
            <el-tag v-else type="success">{{ t('document.document.specifyForm.selected') }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 指定文件夹时显示文件夹树 -->
    <div v-else-if="form.type === 'folder'" style="margin-top: 20px">
      <div style="margin-bottom: 10px; color: #606266; font-size: 14px">{{ t('document.document.specifyForm.selectFolderTip') }}</div>
      <FolderSelector ref="folderSelectorRef" :tree-data="treeData" @change="handleFolderChange" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="loading" type="primary" @click="handleSubmit">
          {{ t('document.document.button.submit') }}
        </el-button>
        <el-button @click="handleClose">{{ t('document.document.button.cancel') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { listDocumentOnSpecify, specifyDocument } from '@/api/document/document';
import { DocumentVO, DocumentSpecifyVO, DocumentSpecifyForm } from '@/api/document/document/types';
import { FolderListVO } from '@/api/document/folder/types';
import { parseTime } from '@/utils/ruoyi';
import DocumentStatusTag from '@/components/DocumentStatusTag/index.vue';
import FolderSelector from '@/components/FolderSelector/index.vue';

interface Props {
  modelValue: boolean;
  document: DocumentVO | null;
  treeData: FolderListVO[];
  projectId?: number | string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  success: [];
}>();

const { t } = useI18n();
const formRef = ref<FormInstance>();
const folderSelectorRef = ref();
const loading = ref(false);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const title = computed(() => t('document.document.dialog.specifyDocument'));

const form = ref({
  type: 'missing',
  folderId: undefined as number | undefined,
  language: '',
  version: '',
  versionDate: '',
  ethicsSubmissionDate: '',
  ethicsApprovalDate: ''
});

const rules = reactive({
  type: [
    {
      required: true,
      message: t('document.document.specifyRule.typeRequired'),
      trigger: 'change'
    }
  ]
});

// 文档列表相关
const documentList = ref<DocumentSpecifyVO[]>([]);
const documentLoading = ref(false);
const documentTotal = ref(0);
const searchName = ref('');
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectId: props.projectId,
  name: ''
});

const selectedDocumentId = ref<string | number | null>(null);
const selectedFolderId = ref<number | string | undefined>(undefined);

// 获取可指定的文档列表
const getDocumentList = async () => {
  if (!props.projectId) return;

  documentLoading.value = true;
  try {
    const res = await listDocumentOnSpecify(queryParams);
    documentList.value = res.rows || [];
    documentTotal.value = res.total || 0;
  } catch (error) {
    console.error('获取可指定文档列表失败:', error);
    ElMessage.error(t('document.document.specifyForm.getDocumentListFailed'));
  } finally {
    documentLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.name = searchName.value;
  queryParams.pageNum = 1;
  getDocumentList();
};

// 重置
const handleReset = () => {
  searchName.value = '';
  queryParams.name = '';
  queryParams.pageNum = 1;
  getDocumentList();
};

// 选择文档
const handleSelectDocument = (id: string | number) => {
  selectedDocumentId.value = id;
};

// 文件夹选择变化
const handleFolderChange = (folderId: number | string | undefined) => {
  selectedFolderId.value = folderId;
};

// 监听类型变化
watch(
  () => form.value.type,
  (newType) => {
    selectedDocumentId.value = null;
    selectedFolderId.value = undefined;
    if (newType === 'missing' && visible.value) {
      getDocumentList();
    } else if (newType === 'folder' && folderSelectorRef.value) {
      folderSelectorRef.value.clearSelection();
    }
  }
);

// 监听 document 变化，初始化表单
watch(
  () => props.document,
  (newDoc) => {
    if (newDoc) {
      form.value = {
        type: 'missing',
        folderId: undefined,
        language: '',
        version: '',
        versionDate: '',
        ethicsSubmissionDate: '',
        ethicsApprovalDate: ''
      };
      selectedDocumentId.value = null;
      selectedFolderId.value = undefined;
      searchName.value = '';
      queryParams.pageNum = 1;
      queryParams.name = '';
      queryParams.projectId = props.projectId;

      nextTick(() => {
        formRef.value?.clearValidate();
        if (form.value.type === 'missing') {
          getDocumentList();
        }
      });
    }
  },
  { immediate: true }
);

const handleClose = () => {
  visible.value = false;
  form.value = {
    type: 'missing',
    folderId: undefined,
    language: '',
    version: '',
    versionDate: '',
    ethicsSubmissionDate: '',
    ethicsApprovalDate: ''
  };
  selectedDocumentId.value = null;
  selectedFolderId.value = undefined;
  documentList.value = [];
};

const handleSubmit = async () => {
  if (!formRef.value || !props.document) return;

  try {
    await formRef.value.validate();

    // 如果是指定递交缺失，需要选择一个文档
    if (form.value.type === 'missing' && !selectedDocumentId.value) {
      ElMessage.warning(t('document.document.specifyForm.selectDocumentWarning'));
      return;
    }

    // 如果是指定文件夹，需要选择一个文件夹
    if (form.value.type === 'folder' && !selectedFolderId.value) {
      ElMessage.warning(t('document.document.specifyForm.selectFolderWarning'));
      return;
    }

    loading.value = true;

    // 构建请求数据
    const specifyData: DocumentSpecifyForm = {
      documentId: props.document.id
    };

    if (form.value.type === 'missing') {
      specifyData.missingDocumentId = selectedDocumentId.value as number | string;
    } else if (form.value.type === 'folder') {
      specifyData.folderId = selectedFolderId.value;
    }

    await specifyDocument(specifyData);
    ElMessage.success(t('document.document.specifyForm.specifySuccess'));
    handleClose();
    emit('success');
  } catch (error) {
    if (error !== false) {
      console.error('指定失败:', error);
      ElMessage.error(t('document.document.specifyForm.specifyFailed'));
    }
  } finally {
    loading.value = false;
  }
};
</script>
