<script lang="ts" setup>
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, isEmpty } from 'lodash-es'
import { ref } from 'vue'
import DialogBox from '@/components/dialog-box/index.vue'
import api from '@/servers/finyx/api/index'
import { useRoute } from 'vue-router'

const { query } = useRoute()

const props = withDefaults(defineProps<{
  title: string
}>(), {
  title: '添加标签'
})

// 定义组件事件，允许触发 submitHandle 事件
const emit = defineEmits(['refresh'])

// 定义一个响应式变量 dialogVisible，用于控制对话框的显示和隐藏
const dialogVisible = ref<boolean>(false)
// 定义一个响应式变量 formData，用于存储表单数据
const formData = ref<any>([])
// 定义一个响应式变量 formDataRef，用于引用表单实例
const formDataRef = ref<any>(null)

// 定义一个响应式变量 loading，用于控制按钮的加载状态
const loading = ref<boolean>(false)

// 关闭对话框的方法
const close = () => {
  dialogVisible.value = false;
  formDataRef.value.resetFields()
  formData.value = [];
}

// 关闭对话框的方法
const open = (query?: any) => {
  dialogVisible.value = true
  if (!isEmpty(query)) {
    formData.value = cloneDeep(query);
  }
}
const handleAdd = async () => {
  await formDataRef.value.validate()
  formData.value.push({ name: '' })
}

// 提交表单的方法
const submitHandle = async () => {
  await formDataRef.value.validate()
  try {
    loading.value = true
    await api.weidu.editLabels({
      labels: formData.value,
      id: query?.id as string,
    })
    ElMessage.success(`${props.title}成功！`)
    close();
    emit('refresh')
  } catch (e) {
    ElMessage.error(`${props.title}失败！`)
  } finally {
    loading.value = false
  }
}

// 校验标签名称是否存在 本地数据查找
const checkLabelNameExists = async (name: string) => {
  try {
    return !await api.weidu.checkLabelName({ labelName: name, id: query?.id as string })
  } catch (e) {
    if (e?.response?.data?.msg) {
      ElMessage.error(e?.response?.data?.msg)
      return true
    }
    ElMessage.error('检查标签名称失败，请重试')
    return true
  }
}
const labelNameRules = [
  { required: true, message: '标签名称不能为空', trigger: 'blur' },
  {
    validator: async (rule, value, callback) => {
      // 检查特殊符号
      const invalidChars = /[*？"<>/]/
      // const invalidChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/.test(value)
      if (invalidChars.test(value)) {
        return callback(new Error('标签名称不能包含特殊符号：*？"<>/'))
      }
      if (value) {
        try {
          const exists = await checkLabelNameExists(value)
          if (exists) {
            callback(new Error('标签名称已存在'))
          } else {
            callback()
          }
        } catch (err) {
          callback(err)
        }
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }
]
// 暴露 open 和 closeDialog 方法给外部使用
defineExpose({ open, close })
</script>

<template>
  <dialog-box :dialogVisible="dialogVisible" :title="title" width="500" @close="close">
    <el-form ref="formDataRef" :model="formData" label-width="auto">
      <el-form-item :rules="labelNameRules" v-for="(item, i) in formData" :prop="`${i}.name`">
        <el-input  v-model="item.name" placeholder="请输入标签名称" style="width: 100%">
          <template #append v-if="title === '新建标签'">
            <el-icon class="pointer" v-if="i === formData.length - 1" @click="handleAdd"><CirclePlus /></el-icon>
            <el-icon class="pointer" v-else><Delete /></el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button :loading="loading" @click.prevent="close"> 取消 </el-button>
        <el-button :loading="loading" type="primary" @click="submitHandle()">
          确定
        </el-button>
      </span>
    </template>
  </dialog-box>
</template>

<style lang="scss" scoped></style>
