<template>
  <div class="dynamic-control">
    <template v-if="config.type == 'input'">
      <el-input
        style="width: 100%"
        :modelValue="getModelValue()"
        @update:modelValue="changeModelValue"
        :placeholder="config.componentProps?.placeholder"
        :clearable="true"
      />
    </template>

    <template v-if="config.type == 'inputNumber'">
      <el-input-number
        style="width: 100%"
        :modelValue="getModelValue()"
        @update:modelValue="changeModelValue"
        :placeholder="config.componentProps?.placeholder"
        :clearable="true"
      />
    </template>

    <template v-if="config.type == 'radio'">
      <el-radio-group
        style="width: 100%"
        :modelValue="getModelValue()"
        @update:modelValue="changeModelValue"
        :placeholder="config.componentProps?.placeholder"
      >
        <el-radio v-for="(option, i) in config.options" :value="option.value">{{
          option.label
        }}</el-radio>
      </el-radio-group>
    </template>

    <template v-if="config.type == 'select'">
      <el-select
        style="width: 100%"
        :modelValue="getModelValue()"
        @update:modelValue="changeModelValue"
        :placeholder="config.componentProps?.placeholder"
      >
        <el-option
          v-for="(option, i) in config.options"
          :key="i"
          :label="option.label"
          :value="option.value"
        ></el-option>
      </el-select>
    </template>

    <template v-if="config.type == 'date'">
      <el-date-picker
        style="width: 100%"
        :modelValue="getModelValue()"
        type="date"
        @update:modelValue="changeModelValue"
        :placeholder="config.componentProps?.placeholder"
      />
    </template>
  </div>
</template>
<script setup>
import { onMounted, ref, inject, toRaw } from 'vue'

const formData = inject('formData')

const props = defineProps({
  config: {
    type: Object,
    default: () => ({}),
  },
})

const getModelValue = () => {
  if(!props.config.prop) {
    console.error('请配置prop属性', toRaw(props.config))
    return null
  }
  const keys = props.config.prop?.split('.')
  let current = formData.value
  for (const key of keys) {
    if (typeof current != 'object' || !current[key]) return null
    current = current[key]
  }
  return current
}

const changeModelValue = (value) => {
  if(!props.config.prop) {
    return null
  }
  // 1. 将路径字符串 'event.name' 按 '.' 拆分成数组
  const keys = props.config.prop?.split('.')

  // 2. 一直遍历到倒数第一个属性，确保中间路径上的对象都存在
  let current = formData.value
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i]
    // 如果中间层不存在，就自动创建一个空对象
    if (!current[key] || typeof current[key] !== 'object') {
      current[key] = {}
    }
    current = current[key]
  }

  // 3. 在最后一层进行赋值
  current[keys[keys.length - 1]] = value
}
</script>
<style scoped lang="scss"></style>
