<template>
  <el-dialog v-model="visible" :title="t('document.document.dialog.addDocument')" width="700px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
      <el-form-item
        :label="form.type === 1 ? t('document.document.documentForm.planName') : t('document.document.documentForm.name')"
        prop="name">
        <div style="display: flex; align-items: center; gap: 8px; width: 100%;">
          <span v-if="namePrefix" style="white-space: nowrap; color: #606266;">{{ namePrefix }}</span>
          <el-input v-model="nameInput" :placeholder="t('document.document.documentForm.namePlaceholder')"
            clearable style="flex: 1;" @input="handleNameInputChange" />
          <span v-if="namePrefix" style="white-space: nowrap; color: #606266;">-</span>
          <el-date-picker v-model="form.documentDate" type="date" value-format="YYYYMMDD" format="YYYYMMDD"
            :placeholder="t('document.document.documentForm.datePlaceholder')" style="width: 180px;" @change="handleDateChange" />
        </div>
      </el-form-item>

      <el-form-item :label="t('document.document.documentForm.type')" prop="type" v-if="hasAddPlanPermission">
        <el-radio-group v-model="form.type" @change="handleTypeChange">
          <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="form.type === 1" :label="t('document.document.documentForm.planSubmitter')"
        prop="planSubmitter">
        <el-select v-model="form.planSubmitter" filterable remote reserve-keyword
          :placeholder="t('document.document.documentForm.planSubmitterPlaceholder')"
          :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="form.type === 1" :label="t('document.document.documentForm.submitDeadline')"
        prop="submitDeadline">
        <el-date-picker v-model="form.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="form.type === 1" :label="t('document.document.documentForm.planType')"
        prop="planType">
        <el-select v-model="form.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 v-if="form.type === 0" :label="t('document.document.documentForm.actualFile')"
        prop="actualDocument">
        <fileUpload v-model="uploadedFileId" :limit="1" :file-type="['pdf']" :is-show-tip="false" />
        <div style="color: #909399; font-size: 12px; margin-top: 5px;">{{ t('document.document.documentForm.fileTip') }}</div>
      </el-form-item>

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

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

      <el-form-item :label="t('document.document.documentForm.sendFlag')" prop="sendFlag">
        <el-switch v-model="form.sendFlag" :active-value="true" :inactive-value="false" />
      </el-form-item>

      <el-form-item :label="t('document.document.documentForm.note')" prop="note">
        <el-input v-model="form.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="buttonLoading" :disabled="hasInvalidChar" type="primary" @click="submitForm">{{
          t('document.document.button.confirm')
        }}</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, watch, computed, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { addDocument, getMemberByNameAndFolder } from '@/api/document/document';
import { DocumentForm } from '@/api/document/document/types';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { checkPermi } from '@/utils/permission';
import { parseI18nName } from '@/utils/i18n';
import fileUpload from '@/components/FileUpload/index.vue';
import { getNameByProjectId } from '@/api/document/folder';

interface Props {
  projectId?: number | string;
  folderId?: number;
  documentInfo?: {
    projectCode: string;
    countryName: string;
    centerId: number | string;
  };
}

const props = defineProps<Props>();

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

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

const visible = ref(false);
const buttonLoading = ref(false);
const formRef = ref<FormInstance>();

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

// 名称前缀（用于显示，隐藏NA）
const namePrefix = ref<string>('');
// 完整前缀（用于提交，保留NA）
const fullNamePrefix = ref<string>('');
const nameInput = ref<string>('');

// 文档信息（用于构建完整名称）
const documentInfoData = ref<{
  projectCode: string;
  countryName: string;
  centerId: string;
}>();

// 文档表单初始数据
const initFormData: DocumentForm & { documentDate?: string } = {
  id: undefined,
  name: '',
  type: 0,
  planSubmitter: undefined,
  folderId: undefined,
  submitDeadline: undefined,
  planType: undefined,
  actualDocument: undefined,
  submitTime: undefined,
  projectId: undefined,
  note: '',
  sendFlag: false,
  effectiveDate: undefined,
  documentDate: undefined
};

const form = ref<DocumentForm & { documentDate?: string }>({ ...initFormData });

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

// 递交人搜索相关
const submitterSearchLoading = ref(false);
const submitterOptions = ref<Array<{
  id: number;
  name: string;
  dept: string;
  phoneNumber: string;
}>>([]);
let submitterSearchTimer: NodeJS.Timeout | null = null;

// 表单验证规则
const rules = {
  name: [
    { required: true, message: t('document.document.documentRule.nameRequired'), trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 检查用户输入部分是否包含"-"
        if (nameInput.value && nameInput.value.includes('-')) {
          callback(new Error(t('document.document.documentForm.nameInvalidChar')));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  planSubmitter: [{ required: true, message: t('document.document.documentRule.planSubmitterRequired'), trigger: 'change' }],
  actualDocument: [{ required: true, message: t('document.document.documentRule.fileRequired'), trigger: 'change' }]
};

// 检查名称是否包含"-"
const hasInvalidChar = ref(false);

// 处理名称输入变化
const handleNameInputChange = (value: string) => {
  nameInput.value = value;
  // 实时检测是否包含"-"
  hasInvalidChar.value = value ? value.includes('-') : false;
  updateDocumentName();
  // 实时触发表单验证
  if (formRef.value) {
    formRef.value.validateField('name', () => {});
  }
};

// 处理日期变化
const handleDateChange = (value: string) => {
  updateDocumentName();
};

// 更新文档名称
const updateDocumentName = () => {
  if (!documentInfoData.value) {
    form.value.name = nameInput.value;
    return;
  }

  // 构建完整名称（用于提交，包含NA）
  // 格式：{projectCode}-{countryName/NA}-{centerId/NA}-{用户输入}-{日期}
  let fullName = `${documentInfoData.value.projectCode}-${documentInfoData.value.countryName}-${documentInfoData.value.centerId}`;

  if (nameInput.value) {
    fullName += `-${nameInput.value}`;
  }

  if (form.value.documentDate) {
    fullName += `-${form.value.documentDate}`;
  }

  form.value.name = fullName;
};

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

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

  // 检查是否有 folderId
  if (!props.folderId) {
    ElMessage.warning(t('document.document.documentForm.noFolderId'));
    return;
  }

  // 检查是否有 projectId
  if (!props.projectId) {
    ElMessage.warning(t('document.document.documentForm.noProjectId'));
    return;
  }

  if (submitterSearchTimer) {
    clearTimeout(submitterSearchTimer);
  }

  submitterSearchTimer = setTimeout(async () => {
    submitterSearchLoading.value = true;
    try {
      const res = await getMemberByNameAndFolder({
        name: query,
        folder: props.folderId!,
        project: props.projectId!,
        pageNum: 1,
        pageSize: 10
      });
      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) {
      form.value.actualDocument = parseInt(ids[0]);
      const now = new Date();
      form.value.submitTime = proxy?.parseTime(now, '{y}-{m}-{d} {h}:{i}:{s}');
      form.value.submitter = userStore.userId;
    }
  } else {
    form.value.actualDocument = undefined;
    form.value.submitTime = undefined;
    form.value.submitter = undefined;
  }
});

// 重置表单
const resetForm = () => {
  form.value = { ...initFormData };
  uploadedFileId.value = '';
  namePrefix.value = '';
  fullNamePrefix.value = '';
  nameInput.value = '';
  hasInvalidChar.value = false;
  documentInfoData.value = undefined;
  submitterOptions.value = [];
  formRef.value?.resetFields();

  if (!hasAddPlanPermission.value) {
    form.value.type = 0;
  }

  if (form.value.type === 0) {
    form.value.planSubmitter = undefined;
    form.value.submitter = userStore.userId;
  } else {
    form.value.planSubmitter = undefined;
    form.value.submitter = undefined;
  }

  form.value.projectId = props.projectId;
  form.value.folderId = props.folderId;
};

// 打开对话框
const open = async () => {
  resetForm();

  // 设置名称前缀
  if (props.documentInfo) {
    let projectCode = '';
    const countryName = props.documentInfo.countryName;
    const centerId = props.documentInfo.centerId;

    // 如果有centerId且不是'NA'，调用接口获取projectCode
    try {
      const res = await getNameByProjectId(props.projectId);
      projectCode = res.data.projectCode;
    } catch (error) {
      console.error('AddDocumentDialog - 获取projectCode失败:', error);
      ElMessage.error(t('document.document.documentForm.projectCodeFailed'));
    }

    // 保存文档信息（用于构建完整名称）
    documentInfoData.value = {
      projectCode: projectCode,
      countryName: countryName,
      centerId: String(centerId)
    };

    // 构建显示前缀（隐藏NA）
    // 格式：{projectCode}-{countryName}-{centerId}-
    // 如果countryName或centerId为NA，则不显示该部分
    let displayPrefix = projectCode;

    if (countryName && countryName !== 'NA') {
      displayPrefix += `-${countryName}`;
    }

    if (centerId && centerId !== 'NA') {
      displayPrefix += `-${centerId}`;
    }

    displayPrefix += '-';

    namePrefix.value = displayPrefix;

    updateDocumentName();
  }

  visible.value = true;
};

// 关闭对话框
const handleClose = () => {
  visible.value = false;
  resetForm();
  emit('close');
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const hasUploadedFile = !!uploadedFileId.value;

        const submitData: DocumentForm = {
          id: form.value.id || 0,
          name: form.value.name || '',
          type: form.value.type !== undefined ? form.value.type : 0,
          planSubmitter: form.value.type === 0 ? undefined : form.value.planSubmitter,
          submitter: form.value.type === 0 ? userStore.userId : form.value.submitter,
          folderId: form.value.folderId || 0,
          submitDeadline: form.value.submitDeadline || '',
          planType: form.value.planType || '',
          actualDocument: hasUploadedFile ? uploadedFileId.value : null,
          submitTime: form.value.submitTime || (hasUploadedFile ? new Date().toISOString() : ''),
          projectId: form.value.projectId || props.projectId,
          status: hasUploadedFile ? 1 : 0,
          note: form.value.note || '',
          sendFlag: form.value.sendFlag !== undefined ? form.value.sendFlag : false,
          effectiveDate: form.value.effectiveDate || ''
        };

        await addDocument(submitData);
        proxy?.$modal.msgSuccess(t('document.document.message.addDocumentSuccess'));
        visible.value = false;
        emit('success');
      } catch (error) {
        console.error(t('document.document.message.addDocumentFailed'), error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

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