<template>
  <template v-if="type">
    <s-dom
      :class="{'is-error':!!errorMessage}"
      v-model="modelData[code]"
      :prefix="prefix"
      :type="type"
      :keys="keys"
      :options="options"
      :props="props"
      :code="code"
      :getFormData="getFormData"
      :getItem="getItem"
      :getItemValue="getItemValue"
      @change="changeValue"
    >
    </s-dom>
  </template>
  <template v-else>
    <Component
      :class="{'is-error':!!errorMessage}"
      :is="component"
      :keys="keys"
      v-model="modelData[code]"
      :prefix="prefix"
      :type="type"
      :options="options"
      :props="props"
      :code="code"
      :getFormData="getFormData"
      :getItem="getItem"
      :getItemValue="getItemValue"
      @change="changeValue"
    ></Component>
  </template>
</template>
<script lang="ts" setup>
import { Op } from 'pkg/Form/form.type'
import { inject, onBeforeUnmount } from 'vue'

interface Props {
  modelValue: any
  prefix: string
  code: string
  keys: Array<string> | string
  type: string
  options?: Array<Op>
  props?: any
  component?: any
  errorMessage?: string
}

const cProps = withDefaults(defineProps<Props>(), {
  modelValue: '',
  prefix: '',
  code: '',
  keys: '',
  type: '',
  options: () => ([]),
  props: () => ({}),
  errorMessage: ''
})

/*
 * 获取注入的属性
 * */
const modelData: any = inject('modelData')
const configOptions: any = inject('options')
const changeEvent: any = inject('changeEvent')
const setFormData: any = inject('setFormData')
const getFormData: any = inject('getFormData')
const getItem: any = inject('getItem')
const getItemValue: any = inject('getItemValue')

const emits = defineEmits(['validateValue'])
onBeforeUnmount(() => {
  setFormData('__DELETE__', cProps.keys)
})

/*
 * 数值改变的触发函数
 * */
function changeValue (val: any, trigger: string = 'change') {
  const sValue = val?.target ? (val.target.valueAsNumber || val.target.value) : val
  if (cProps.props?.rules && cProps.props?.rules.length > 0) {
    emits('validateValue', sValue, trigger)
  }
  setFormData(sValue, cProps.keys)
  if (trigger === 'change') changeEvent(cProps.keys, sValue)
}
</script>
