<template>
  <el-dialog v-model="visible" :title="title" width="600px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
      <el-form-item v-if="!isEdit && form.parentId === undefined" :label="t('document.document.form.type')" prop="type">
        <el-select v-model="form.type" :placeholder="t('document.document.form.typePlaceholder')" style="width: 100%">
          <el-option :label="t('document.document.type.country')" :value="1" />
          <el-option :label="t('document.document.type.center')" :value="2" />
          <el-option :label="t('document.document.type.folder')" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('document.document.form.name')" prop="name">
        <el-input v-model="form.name" :placeholder="t('document.document.form.namePlaceholder')" clearable />
      </el-form-item>
      <el-form-item :label="t('document.document.form.restrictionLevel')" prop="restrictionLevel">
        <el-radio-group v-model="isRestricted" @change="handleRestrictionChange">
          <el-radio :label="false">{{ t('document.document.form.noRestriction') }}</el-radio>
          <el-radio :label="true">{{ t('document.document.form.restricted') }}</el-radio>
        </el-radio-group>
        <el-input-number
          v-if="isRestricted"
          v-model="restrictionLevelValue"
          :min="0"
          :max="10000"
          style="width: 100%; margin-top: 10px"
          :placeholder="t('document.document.form.restrictionLevelPlaceholder')"
        />
      </el-form-item>
      <el-form-item :label="t('document.document.form.note')" prop="note">
        <el-input v-model="form.note" type="textarea" :rows="4" :placeholder="t('document.document.form.notePlaceholder')" />
      </el-form-item>
      <el-form-item v-if="form.type === 0" :label="t('document.document.form.keywords')" prop="keywords">
        <el-select
          v-loading="keywordLoading"
          v-model="form.keywords"
          multiple
          :placeholder="t('document.document.form.keywordsPlaceholder')"
          style="width: 100%"
        >
          <el-option v-for="keyword in keywordList" :key="keyword.id" :label="keyword.content" :value="keyword.id" />
        </el-select>
      </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, getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { addFolder, getFolder, updateFolder } from '@/api/document/folder';
import { FolderForm } from '@/api/document/folder/types';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import request from '@/utils/request';

interface KeywordVO {
  id: number;
  content: string;
  note?: string;
}

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { t } = useI18n();

const visible = ref(false);
const title = ref('');
const isEdit = ref(false);
const buttonLoading = ref(false);
const keywordLoading = ref(false);
const formRef = ref<FormInstance>();

const keywordList = ref<KeywordVO[]>([]);
const isRestricted = ref(false);
const restrictionLevelValue = ref(0);

const initFormData: FolderForm & { keywords?: number[] } = {
  id: undefined,
  projectId: undefined,
  parentId: undefined,
  type: 0,
  name: '',
  status: 0,
  note: '',
  restrictionLevel: -1,
  keywords: []
};

const form = ref<FolderForm & { keywords?: number[] }>({ ...initFormData });

const rules = {
  name: [
    { required: true, message: t('document.document.rule.nameRequired'), trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && value.includes('-')) {
          callback(new Error(t('document.document.form.nameInvalidChar')));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  type: [{ required: true, message: t('document.document.rule.typeRequired'), trigger: 'change' }]
};

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

// 监听名称变化，实时检测
watch(() => form.value.name, (newName) => {
  hasInvalidChar.value = newName ? newName.includes('-') : false;
  // 实时触发表单验证
  if (formRef.value) {
    formRef.value.validateField('name', () => {});
  }
});

// 获取关键词列表
const getKeywordList = async () => {
  keywordLoading.value = true;
  try {
    const res = await request({
      url: '/setting/keyword/listOnFolder',
      method: 'get'
    });
    keywordList.value = res.data || [];
  } catch (error) {
    ElMessage.error(t('document.document.form.getKeywordsFailed'));
    console.error('获取关键词列表失败:', error);
    keywordList.value = [];
  } finally {
    keywordLoading.value = false;
  }
};

// 处理限制状态变化
const handleRestrictionChange = (value: boolean) => {
  if (value) {
    form.value.restrictionLevel = restrictionLevelValue.value;
  } else {
    form.value.restrictionLevel = -1;
  }
};

// 监听restrictionLevelValue变化
watch(restrictionLevelValue, (newValue) => {
  if (isRestricted.value) {
    form.value.restrictionLevel = newValue;
  }
});

// 监听类型变化，动态加载关键词列表
watch(() => form.value.type, async (newType) => {
  if (newType === 0 && keywordList.value.length === 0) {
    // 类型切换为文件夹且关键词列表为空时，加载关键词列表
    await getKeywordList();
  }
});

// 重置表单
const reset = () => {
  form.value = { ...initFormData };
  isRestricted.value = false;
  restrictionLevelValue.value = 0;
  hasInvalidChar.value = false;
  formRef.value?.resetFields();
};

// 打开对话框 - 新增
const open = async (projectId: number | string, parentId?: number, type?: number) => {
  reset();
  form.value.projectId = projectId;
  form.value.parentId = parentId;
  if (type !== undefined) {
    form.value.type = type;
  } else {
    form.value.type = 1; // 默认选择国家类型
  }
  
  // 只有类型为文件夹时才获取关键词列表
  if (form.value.type === 0) {
    await getKeywordList();
  }
  
  const typeLabel =
    type === 0 ? t('document.document.type.folder') : type === 1 ? t('document.document.type.country') : t('document.document.type.center');
  title.value =
    type === 0
      ? t('document.document.dialog.addFolder')
      : type === 1
        ? t('document.document.dialog.addCountry')
        : type === 2
          ? t('document.document.dialog.addCenter')
          : t('document.document.dialog.addFolder');
  
  isEdit.value = false;
  visible.value = true;
};

// 打开对话框 - 编辑
const openEdit = async (folderId: number) => {
  reset();
  try {
    const res = await getFolder(folderId);
    Object.assign(form.value, res.data);

    if (form.value.restrictionLevel === -1) {
      isRestricted.value = false;
      restrictionLevelValue.value = 0;
    } else {
      isRestricted.value = true;
      restrictionLevelValue.value = form.value.restrictionLevel;
    }

    // 只有类型为文件夹时才获取关键词列表
    if (form.value.type === 0) {
      await getKeywordList();
    }

    title.value = t('document.document.dialog.editFolder');
    isEdit.value = true;
    visible.value = true;
  } catch (error) {
    ElMessage.error(t('document.document.message.getFolderInfoFailed'));
    console.error(error);
  }
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (isEdit.value) {
        try {
          const confirmMessage = `
            <div style="text-align: left;">
              <p><strong>${t('document.document.confirm.nameLabel')}</strong>${form.value.name}</p>
              <p><strong>${t('document.document.confirm.restrictionLevelLabel')}</strong>${form.value.restrictionLevel !== -1 ? form.value.restrictionLevel : t('document.document.confirm.noLimit')}</p>
              <p><strong>${t('document.document.confirm.noteLabel')}</strong>${form.value.note || t('document.document.confirm.noNote')}</p>
            </div>
          `;
          await ElMessageBox.confirm(confirmMessage, t('document.document.dialog.confirmEdit'), {
            confirmButtonText: t('document.document.message.confirmButton'),
            cancelButtonText: t('document.document.message.cancelButton'),
            type: 'warning',
            dangerouslyUseHTMLString: true
          });
        } catch {
          return;
        }
      }

      buttonLoading.value = true;
      try {
        if (isEdit.value) {
          await updateFolder(form.value);
          proxy?.$modal.msgSuccess(t('document.document.message.editSuccess'));
        } else {
          await addFolder(form.value);
          proxy?.$modal.msgSuccess(t('document.document.message.addSuccess'));
        }
        visible.value = false;
        emit('success');
      } catch (error) {
        console.error(isEdit.value ? t('document.document.message.editFailed') : t('document.document.message.addFailed'), error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 关闭对话框
const handleClose = () => {
  reset();
  visible.value = false;
};

defineExpose({
  open,
  openEdit
});
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
