<script lang="ts" setup>
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { debounce } from 'lodash-es'
import { ref } from 'vue'
import api from '@/servers/finyx/api/index'

const formDataRef: any = ref(null)
const formData: any = ref({
  name: '',
  reminder: '',
  labels: []
})
const saveLoading = ref<boolean>(false)

const hoverIndex = ref<any>(null)

const hoverChangeIndex = (i: any) => {
  hoverIndex.value = i
}

const saveTag = debounce(async () => {
  await formDataRef.value.validate()
  try {
    saveLoading.value = true
    await api.weidu.editLabels(formData.value)
    ElMessage.success('保存成功')
    router.go(-1)
  } catch (e) {
    ElMessage.error('保存标签失败，请重试')
  } finally {
    saveLoading.value = false
  }
}, 500)

const handleCreateTag = async () => {
  try {
    saveLoading.value = true
    const model: any = {
      ...formData.value,
    }
    const data: any = await api.weidu.getLabels(model)
    data?.tags.map((v: any) => {
      formData.value.labels.push({ name: v })
    })
  } catch (e) {
    ElMessage.error('创建标签失败，请重试')
  } finally {
    saveLoading.value = false
  }
}

const handleAdd = () => {
  formData.value.labels.push({ name: '' })
}
const handleDelete = (i: any) => {
  formData.value.labels.splice(i, 1)
}

// 校验知识库名称是否存在（模拟异步请求）
const checkNameExists = async (name) => {
  try {
    return !await api.weidu.checkName2({ name })
  } catch (e) {
    if (e?.response?.data?.msg) {
      ElMessage.error(e?.response?.data?.msg)
      return true
    }
    ElMessage.error('检查维度名称失败，请重试')
    return true
  }
}

const nameRules = [
  { 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 checkNameExists(value)
          if (exists) {
            callback(new Error('维度名称已存在'))
          } else {
            callback()
          }
        } catch (err) {
          callback(err)
        }
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }
]
// 校验标签名称是否存在 本地数据查找
const checkLabelNameExists = (name: string) => {
  return formData.value.labels.filter((v: any) => v.name === name)?.length > 1
}
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 = checkLabelNameExists(value)
          if (exists) {
            callback(new Error('标签名称已存在'))
          } else {
            callback()
          }
        } catch (err) {
          callback(err)
        }
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }
]
</script>

<template>
  <div class="tag-form">
    <div class="flex tag-form-header">
      <el-space>
        <el-icon class="pointer" @click="router.go(-1)">
          <ArrowLeftBold />
        </el-icon>
        新建维度及标签
      </el-space>
    </div>
    <el-form ref="formDataRef" :model="formData" label-position="top">
      <div class="tag-form-container flex">
        <div class="tag-form-container-left">
          <div class="tag-form-container-left-content">
            <p style="font-weight: 500; font-size: 16px; color: #191919; margin-bottom: 20px">
              标签生成
            </p>
            <el-form-item :rules="nameRules" label="维度名称" prop="name">
              <el-input
                v-model="formData.name"
                maxlength="15"
                placeholder="请输入维度名称"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="生成提示">
              <el-input
                v-model="formData.reminder"
                :rows="12"
                placeholder="请输入生成提示"
                type="textarea"
              />
            </el-form-item>
          </div>
          <div class="tag-form-container-right-footer">
            <el-button type="primary" :disabled="!formData.name || !formData.reminder" @click="handleCreateTag">生成标签</el-button>
          </div>
        </div>
        <div class="tag-form-container-right" v-loading="saveLoading">
          <div class="tag-form-container-right-content">
            <el-row justify="space-between">
              <el-col :span="12" style="font-weight: 500; font-size: 16px; color: #191919; margin-bottom: 20px">
                标签预览
              </el-col>
              <el-col :span="12" style="text-align: right">
                <el-button type="primary" @click="handleAdd" :icon="CirclePlus">手动添加标签</el-button>
              </el-col>
            </el-row>
            <el-form-item v-for="(item, i) in formData.labels" :prop="`labels.${i}.name`" :rules="labelNameRules" style="position: relative" @mouseenter="hoverChangeIndex(i)" @mouseleave="hoverChangeIndex(null)">
              <el-input v-model="item.name" placeholder="请输入标签名称" style="width: 100%"/>
              <lz-svg-icon v-if="hoverIndex === i" icon-class="delete" class-name="pointer" style="position: absolute; right: 10px; top: 10px" @click="handleDelete(i)"></lz-svg-icon>
            </el-form-item>
          </div>

          <div class="tag-form-container-right-footer">
            <el-button :loading="saveLoading" type="primary" @click="saveTag">保存</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.tag-form {
  height: 100%;

  .flex {
    display: flex;
  }

  &-header {
    margin-bottom: 30px;
  }

  .el-form {
    height: calc(100% - 50px);
  }

  &-container {
    height: 100%;

    &-left,
    &-right {
      flex: 1;
      display: flex;
      flex-direction: column;

      &-content {
        flex: 1;
      }

      &-footer {
        text-align: right;
      }
    }

    &-left {
      padding-right: 40px;
      border-right: 2px solid rgba(0, 0, 0, 0.08);
    }

    &-right {
      padding-left: 40px;
    }
  }
}
</style>
