<script setup lang="ts">
import { useAttrs, computed, getCurrentInstance } from 'vue'
import { usePropBind, LABEL_KEY } from './common'
import GdFormItem from './GdFormItem.vue';
const $t: any = getCurrentInstance()?.appContext.config.globalProperties.$t

const props = withDefaults(defineProps<{
  label: string,
  rules?: [],
  noPlaceholder?: boolean
}>(), { label: '', noPlaceholder: false })
const emit = defineEmits<{
  (e: 'change', val: any): void
}>();

const { propValue, handleChange } = usePropBind()
const attrs = <any>useAttrs()
let { type, pattern: patternType } = attrs



const rules = computed(() => {
  const validateConfig: any = {
    'key': { pattern: /^[a-z0-9]+(_[a-z0-9]+)*$/, message: `${$t('check_valid_column')?.replace(LABEL_KEY, props.label)}`, trigger: 'change' },
    'prefix': { pattern: /^[A-Z]*$/, message: `${$t('check_valid')?.replace(LABEL_KEY, props.label)}`, trigger: 'change' },
  }
  const res: any = props.rules || []
  if (validateConfig[patternType]) {
    res.push(validateConfig[patternType])
  }
  return res
})

const trimChange = (val: string) => {
  handleChange(val)
  emit('change', val)
}

</script>

<template>
  <GdFormItem :label="label" :rules="rules">
    <span class="viewer-content" v-if="attrs.viewerMode">{{ propValue }}</span>
    <el-input v-if="!attrs.viewerMode && !noPlaceholder" :model-value="propValue" @update:model-value="trimChange"
      :placeholder="`${$t('placeholder_prefix_input')?.replace(LABEL_KEY, label)}`"
      :maxlength="type === 'textarea' ? 100 : 20" clearable v-bind="attrs" />
    <el-input v-if="!attrs.viewerMode && noPlaceholder" :model-value="propValue" @update:model-value="trimChange"
      :maxlength="type === 'textarea' ? 100 : 20" clearable v-bind="attrs" />
  </GdFormItem>
</template>
