<template>
  <div class="dynamic-form">
    <el-form
      ref="globalFormRef"
      :rules="rules"
      :model="model"
      label-position="top"
      class="business-edit-form"
    >
      <el-row :gutter="20">
        <slot></slot>
        <!-- 遍历每个分组 -->
        <template v-for="(group, groupKey) in groupedFields" :key="groupKey">
          <!-- 分组标题 -->
          <el-col :span="24"
            ><h3 class="group-title">{{ getGroupTitle(groupKey) }}</h3></el-col
          >
          <el-col v-for="field in group" :key="field.id || field.fieldName" :span="12">
            <el-form-item
              :label="t('global.fieldName.' + field.fieldName + '.fieldTitle')"
              :prop="field.fieldName"
              :rules="getRules(field)"
              :class="field.hidden ? 'div-hidden' : ''"
            >
              <!-- 输入框 -->
              <el-input
                v-if="field.fieldType === 'input'"
                v-model="model[field.fieldName]"
                :disabled="field.disabled || !!field.fixedValue"
                :placeholder="t('global.fieldName.' + field.fieldName + '.fieldDescription')"
                @change="() => clearFieldValidate(field)"
              />
              <!-- 下拉框 -->
              <el-select
                v-else-if="field.fieldType === 'select'"
                v-model="model[field.fieldName]"
                :disabled="field.disabled || !!field.fixedValue"
                :placeholder="t('global.fieldName.' + field.fieldName + '.fieldDescription')"
                @change="(val) => clearFieldValidate(field, val, true)"
              >
                <el-option
                  v-for="opt in field.availableDtos || []"
                  :key="opt.valueId"
                  :label="t('global.available')[opt.value] || opt.value"
                  :value="opt.valueId"
                />
              </el-select>
              <!-- 日期 -->
              <el-date-picker
                v-else-if="field.fieldType === 'date'"
                v-model="model[field.fieldName]"
                :disabled="field.disabled || !!field.fixedValue"
                type="date"
                style="width: 100% !important"
                value-format="YYYY-MM-DD"
                :start-placeholder="t('Placeholder.Start')"
                :end-placeholder="t('Placeholder.End')"
                @change="() => clearFieldValidate(field)"
              />
              <!-- 数字 -->
              <el-input-number
                v-else-if="field.fieldType === 'number'"
                v-model="model[field.fieldName]"
                :min="field.min"
                :max="field.max"
                :disabled="field.disabled || !!field.fixedValue"
                :placeholder="t('global.fieldName.' + field.fieldName + '.fieldDescription')"
              />
              <!-- 其他类型 -->
              <span v-else>未支持类型：{{ field.fieldType }}</span>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
  import { ref, computed, watch, nextTick, toRef } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { useVModel } from '@vueuse/core'

  const { t } = useI18n()

  // 定义props
  const props = defineProps({
    fields: {
      type: Array,
      required: true,
      default: () => [],
    },
    globalForm: {
      type: Object,
      required: true,
    },
  })
  // 定义emits
  const emit = defineEmits(['update:globalForm'])

  // 使用useVModel实现v-model双向绑定
  const model = useVModel(props, 'globalForm', emit)

  // 响应式数据
  const globalFormRef = ref(null)
  const rules = ref({
    cId: [
      {
        required: true,
        message: t('global.placeholder.p1'),
        trigger: 'change',
      },
    ],
    deductionAccount: [
      {
        required: true,
        message: t('global.placeholder.p2'),
        trigger: 'change',
      },
    ],
  })

  // 计算属性
  const groupedFields = computed(() => {
    const order = { common: 1, receiver: 3, sender: 2 }

    // 先排序
    const sorted = [...(props.fields || [])].sort((a, b) => {
      const typeA = order[a.fieldUserType] || 99
      const typeB = order[b.fieldUserType] || 99
      if (typeA !== typeB) return typeA - typeB
      return (a.sorting || 0) - (b.sorting || 0)
    })

    // 再分组
    const groups = {}
    sorted.forEach((field) => {
      const type = field.fieldUserType || 'other'
      if (!groups[type]) groups[type] = []
      groups[type].push(field)
    })
    return groups
  })

  // 方法
  const getRules = (field) => {
    const rules = []
    if (field.required) {
      rules.push({
        required: true,
        message: `${field.fieldTitle} ${t('Ucard.GlobalOrder.RulesRequire')}`,
        trigger: 'blur',
      })
    }
    if (field.regex) {
      try {
        const reg = new RegExp(field.regex)
        rules.push({
          pattern: reg,
          message: `${field.fieldTitle} ${t('Ucard.GlobalOrder.RulesReg')}`,
          trigger: 'blur',
        })
      } catch (e) {
        console.warn('Invalid regex:', field.regex)
      }
    }
    return rules
  }

  const getGroupTitle = (type) => {
    const map = {
      common: 'Ucard.GlobalOrder.common',
      receiver: 'Ucard.GlobalOrder.receiver',
      sender: 'Ucard.GlobalOrder.sender',
      other: 'Ucard.GlobalOrder.other',
    }
    return t(map[type] || type)
  }

  const clearFieldValidate = (field, val, isSelect = false) => {
    nextTick(() => {
      const fieldName = field.fieldName
      if (globalFormRef.value) {
        globalFormRef.value.clearValidate(fieldName)
      }
      if (isSelect) {
        const label = field.availableDtos?.find((item) => item.valueId == val)?.value ?? null

        // 更新表单中的value字段
        model.value[fieldName + 'Value'] = label
      }
    })
  }

  watch(
    () => props.globalForm,
    (newval) => {
      console.log(newval, 'global ')
    }
  )
  // 监听fields变化
  watch(
    () => props.fields,
    (newFields) => {
      if (!newFields || !Array.isArray(newFields)) return

      const updatedForm = { ...model.value }
      let hasChanges = false

      newFields.forEach((field) => {
        // 调试信息
        if ('receiverBankCity' === field.fieldName) {
          console.log('receiverBankCity field:', field)
        }

        // 有 fixedValue 时回显
        if (field.fixedValue !== undefined && field.fixedValue !== null) {
          if (updatedForm[field.fieldName] !== field.fixedValue) {
            updatedForm[field.fieldName] = field.fixedValue
            hasChanges = true
          }
        } else if (!(field.fieldName in updatedForm)) {
          // 没有则初始化为空
          updatedForm[field.fieldName] = null
          hasChanges = true
        }
      })

      // 如果有变化，则更新model
      if (hasChanges) {
        model.value = updatedForm
      }

      nextTick(() => {
        if (globalFormRef.value) {
          globalFormRef.value.clearValidate()
        }
      })
    },
    {
      immediate: true,
      deep: true,
    }
  )
  // 第二部：暴露方法
  defineExpose({
    globalFormRef: globalFormRef,
  })
</script>

<style scoped lang="scss">
  .group-title {
    font-weight: bold;
    font-size: 16px;
    color: #333;
    margin: 20px 0 10px;
    border-left: 4px solid #409eff;
    padding-left: 8px;
    text-align: left;
  }

  .form-group + .form-group {
    margin-top: 30px;
  }
</style>
