LifeInsuranceTemplate.vue 10.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
<template>
  <div v-if="config">
    <template v-for="field in baseFields" :key="field.id || field.key">
      <component
        v-if="isFieldVisible(field.key) && field.type !== 'percentage'"
        :is="getFieldComponent(field)"
        v-model="form[field.key]"
        v-bind="getFieldProps(field)"
        class="mb-5"
      />
      <div v-else-if="isFieldVisible(field.key) && field.type === 'percentage'" class="mb-5">
        <div class="text-sm text-gray-700 mb-2 flex items-center">
          <span v-if="field.required" class="text-red-500 mr-1">*</span>
          <span>{{ field.label }}</span>
        </div>
        <nut-input
          v-model="form[field.key]"
          type="digit"
          :placeholder="field.placeholder"
          @input="(value) => onPercentageInput(value, field.key)"
          class="w-full"
        />
      </div>
    </template>
  </div>

  <!-- 配置缺失提示 -->
  <div v-else class="text-center text-gray-500 py-10">
    <p>⚠️ 模板配置未找到</p>
    <p class="text-sm mt-2">请检查产品配置或联系开发人员</p>
  </div>
</template>

<script setup>
/**
 * 人寿保险计划书模板
 *
 * @description WIOP3E/WIOP3 等人寿保险产品的计划书录入表单
 *              - 表单字段:性别、出生年月日、是否吸烟、保额、缴费年期
 * @author Claude Code
 * @example
 * <LifeInsuranceTemplate
 *   v-model="formData"
 *   :config="templateConfig"
 * />
 */
import { reactive, watch, computed } from 'vue'
import Taro from '@tarojs/taro'
import PlanFieldName from '../PlanFields/NameInput.vue'
import PlanFieldAmount from '../PlanFields/AmountKeyboard.vue'
import PlanFieldDatePicker from '../PlanFields/DatePickerGlobal.vue'
import PlanFieldAgePicker from '../PlanFields/AgePickerGlobal.vue'
import PlanFieldRadio from '../PlanFields/RadioGroup.vue'
import PaymentPeriodRadio from '../PlanFields/PaymentPeriodRadio.vue'
import { useFieldDependencies } from '@/composables/useFieldDependencies'

/**
 * 组件属性
 */
const props = defineProps({
  /**
   * 表单数据对象
   * @type {Object}
   */
  modelValue: {
    type: Object,
    default: () => ({})
  },

  /**
   * 模板配置
   * @type {Object}
   * @property {string} currency - 币种代码
   * @property {Array<string>} payment_periods - 缴费年期选项
   * @property {Object} age_range - 年龄范围 { min, max }
   * @property {string} insurance_period - 保险期间
   * @property {Object} form_schema - 表单 Schema
   */
  config: {
    type: Object,
    required: true
  }
})

/**
 * 组件事件
 */
const emit = defineEmits([
  /**
   * 更新表单数据事件
   * @event update:modelValue
   * @param {Object} value - 表单数据
   */
  'update:modelValue'
])

/**
 * 表单数据
 * @type {Object}
 *
 * ⚠️ 重要:处理父组件重置表单的情况
 * 问题:reactive() 只在初始化时赋值,父组件重置时子组件不会自动更新
 *
 * 解决方案:使用 watch 监听,但只在重置时(空对象)才清空
 * - 判断重置的标准:从有数据变为空对象
 * - 用户输入时的更新:只合并新字段,不删除已有字段
 */
const form = reactive({})

let previousModelValue = null

// 字段类型与组件的对应关系
const fieldComponentMap = {
  name: PlanFieldName,
  radio: PlanFieldRadio,
  date: PlanFieldDatePicker,
  age: PlanFieldAgePicker,
  amount: PlanFieldAmount,
  payment_period: PaymentPeriodRadio
}

// Schema 配置入口
const baseFields = computed(() => props.config?.form_schema?.base_fields || [])

const fieldDefinitions = computed(() => {
  return baseFields.value.reduce((result, field) => {
    result[field.key] = field
    return result
  }, {})
})

/**
 * 获取字段对应的渲染组件
 * @param {Object} field - 字段配置
 * @returns {Object|null} Vue 组件
 */
const getFieldComponent = (field) => {
  return fieldComponentMap[field.type] || null
}

/**
 * 组装字段渲染所需的 props
 * @param {Object} field - 字段配置
 * @returns {Object} 传入字段组件的 props
 */
const getFieldProps = (field) => {
  const fieldProps = {
    label: field.label,
    placeholder: field.placeholder,
    required: !!field.required
  }

  if (field.options) {
    fieldProps.options = field.options
  }

  // 缴费年期选项由模板配置提供
  if (field.options_from === 'payment_periods') {
    fieldProps.options = fieldProps.options || props.config?.payment_periods
  }

  // 基础币种来自模板配置
  if (field.currency_from === 'currency') {
    fieldProps.currency = props.config?.currency
  }

  // 金额键盘的弹窗提示文本
  if (field.input_label) {
    fieldProps.inputLabel = field.input_label
  }

  return fieldProps
}

const { isFieldVisible } = useFieldDependencies(form, fieldDefinitions)

/**
 * 获取 Schema 默认值
 * @param {Object} value - 当前表单数据
 * @returns {Object} 默认值集合
 */
const getSchemaDefaults = (value) => {
  const defaults = {}
  const fields = [...baseFields.value]
  fields.forEach(field => {
    if (field.default !== undefined && (value?.[field.key] === undefined || value?.[field.key] === null)) {
      defaults[field.key] = field.default
    }
  })
  return defaults
}

/**
 * 初始化表单数据
 * @param {Object} value - 初始数据
 */
const initializeForm = (value) => {
  if (!value) {
    Object.keys(form).forEach(key => delete form[key])
    return
  }

  const defaults = getSchemaDefaults(value)

  Object.assign(form, {
    ...value,
    ...defaults
  })
}

// 监听父组件的数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (!newVal) {
      // null 或 undefined:清空
      Object.keys(form).forEach(key => delete form[key])
      previousModelValue = null
      return
    }

    // 判断是否是重置(从有数据变为空对象)
    const isReset = previousModelValue &&
                      Object.keys(previousModelValue).length > 0 &&
                      Object.keys(newVal).length === 0

    if (isReset) {
      // 父组件重置了:清空表单
      initializeForm(newVal)
      previousModelValue = newVal
    } else {
      // 正常更新:合并新字段,保留默认值逻辑
      const defaults = getSchemaDefaults(newVal)
      Object.assign(form, {
        ...newVal,
        ...defaults
      })
      previousModelValue = newVal
    }
  },
  { immediate: true, deep: true }
)

/**
 * 监听表单数据变化,同步到父组件
 */
// 监听表单数据变化,同步到父组件
watch(
  form,
  (newVal) => emit('update:modelValue', { ...newVal }),
  { deep: true }
)

/**
 * 年龄与出生年月日自动计算逻辑
 * - 填年龄 → 推算生日(默认当年1月1日)
 * - 填生日 → 计算年龄
 */
watch(
  () => form.age,
  (newAge) => {
    if (!isEmptyValue(newAge) && isEmptyValue(form.birthday)) {
      // 填了年龄,推算生日(默认当年1月1日)
      const currentYear = new Date().getFullYear()
      const birthYear = currentYear - parseInt(newAge)
      form.birthday = `${birthYear}-01-01`
    }
  }
)

watch(
  () => form.birthday,
  (newBirthday) => {
    if (!isEmptyValue(newBirthday)) {
      // 填了生日,计算年龄
      const birthYear = new Date(newBirthday).getFullYear()
      const currentYear = new Date().getFullYear()
      form.age = currentYear - birthYear
    }
  }
)

/**
 * 百分比输入清洗,避免非法字符
 * @param {string|number} value - 输入值
 * @param {string} key - 目标字段 key
 */
const onPercentageInput = (value, key) => {
  // 转换为字符串(处理 value 为 null 或其他类型的情况)
  let strValue = String(value ?? '')

  // 只保留数字和小数点
  let cleaned = strValue.replace(/[^\d.]/g, '')

  // 只保留一个小数点
  const parts = cleaned.split('.')
  if (parts.length > 2) {
    cleaned = parts[0] + '.' + parts.slice(1).join('')
  }

  // 限制小数点后最多 2 位
  if (parts.length === 2 && parts[1].length > 2) {
    cleaned = parts[0] + '.' + parts[1].slice(0, 2)
  }

  // 限制范围:0-100
  const numValue = parseFloat(cleaned)
  if (!Number.isNaN(numValue)) {
    if (numValue > 100) {
      cleaned = '100'
    } else if (numValue < 0) {
      cleaned = '0'
    }
  }

  form[key] = cleaned
}

const isEmptyValue = (value) => {
  if (value === null || value === undefined) return true
  if (typeof value === 'string' && value.trim() === '') return true
  if (Array.isArray(value) && value.length === 0) return true
  return false
}

const getRequiredMessage = (field) => {
  if (field?.placeholder) return field.placeholder
  const label = field?.label || '必填信息'
  const selectTypes = ['radio', 'select', 'date', 'payment_period', 'age']
  if (selectTypes.includes(field?.type)) {
    return `请选择${label}`
  }
  return `请输入${label}`
}

const isFieldRequired = (field) => {
  return field?.required === true || field?.required === undefined
}

/**
 * 表单校验(基于 Schema)
 * @returns {boolean} 校验是否通过
 */
const validate = () => {
  const fields = [...baseFields.value]

  // 年龄与出生年月日二选一校验
  const hasAge = !isEmptyValue(form.age)
  const hasBirthday = !isEmptyValue(form.birthday)

  if (!hasAge && !hasBirthday) {
    Taro.showToast({ title: '年龄与出生年月日至少填写一项', icon: 'none' })
    return false
  }

  // 如果都填写了,以生日为准,重新计算年龄
  if (hasAge && hasBirthday) {
    // 使用生日重新计算年龄
    const birthYear = new Date(form.birthday).getFullYear()
    const currentYear = new Date().getFullYear()
    form.age = String(currentYear - birthYear)
  }

  for (const field of fields) {
    if (!isFieldVisible(field.key)) {
      continue
    }

    // 跳过年龄字段的单独校验(已和生日一起校验)
    if (field.key === 'age') continue

    if (isFieldRequired(field)) {
      const value = form[field.key]
      if (isEmptyValue(value)) {
        Taro.showToast({ title: getRequiredMessage(field), icon: 'none' })
        return false
      }
    }

    if (field.type === 'percentage' && isFieldVisible(field.key)) {
      const value = form[field.key]
      if (!isEmptyValue(value)) {
        const percentage = parseFloat(value)
        if (Number.isNaN(percentage) || percentage < 0 || percentage > 100) {
          Taro.showToast({ title: '请输入0-100之间的百分比', icon: 'none' })
          return false
        }
      }
    }
  }

  return true
}

/**
 * 清除验证错误
 * @description 由于使用 Toast 显示错误,无需清除状态
 *              保留此方法以保持接口一致性
 */
const clearErrors = () => {
  // 当前使用 Toast 显示错误,无需清除错误状态
  // 如果将来改用内联错误提示,可以在这里清除错误状态
}

defineExpose({
  validate,
  clearErrors
})
</script>

<style lang="less" scoped>
/* 模板样式 */
</style>