SavingsTemplate.vue 12.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 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
<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 class="border-t border-gray-200 my-6"></div>

    <div v-if="config.withdrawal_plan?.enabled" class="withdrawal-plan-section">
      <template v-for="field in withdrawalFields" :key="field.id || field.key">
        <h3 v-if="field.section_title" class="text-base font-semibold text-gray-900 mb-4">
          {{ field.section_title }}
        </h3>
        <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>

  <!-- 配置缺失提示 -->
  <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 GS/GC/FA/LV2 等储蓄型保险产品的计划书录入表单
 *              - 表单字段:性别、出生年月日、是否吸烟、保额、缴费年期
 *              - 提取计划:指定提取金额(按年岁/按保单年度)、最高固定提取金额
 * @author Claude Code
 * @example
 * <SavingsTemplate
 *   v-model="formData"
 *   :config="templateConfig"
 * />
 */
import { reactive, watch, computed } from 'vue'
import Taro from '@tarojs/taro'
import PlanFieldName from '../PlanFields/NameInput.vue'
import PlanFieldAgePicker from '../PlanFields/AgePickerGlobal.vue'
import PlanFieldAmount from '../PlanFields/AmountKeyboard.vue'
import PlanFieldDatePicker from '../PlanFields/DatePickerGlobal.vue'
import PlanFieldRadio from '../PlanFields/RadioGroup.vue'
import PlanFieldSelect from '../PlanFields/SelectPickerGlobal.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} withdrawal_plan - 提取计划配置
   * @property {boolean} withdrawal_plan.enabled - 是否启用提取计划
   * @property {Array<string>} withdrawal_plan.currencies - 支持的币种
   * @property {string} withdrawal_plan.default_currency - 默认币种
   * @property {Array<string>} withdrawal_plan.withdrawal_modes - 提取模式
   * @property {Array<string>} withdrawal_plan.withdrawal_periods - 提取年期
   */
  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,
  amount: PlanFieldAmount,
  age: PlanFieldAgePicker,
  select: PlanFieldSelect,
  payment_period: PaymentPeriodRadio
}

// Schema 配置入口
const baseFields = computed(() => props.config?.form_schema?.base_fields || [])
const withdrawalFields = computed(() => props.config?.form_schema?.withdrawal_fields || [])
const resetMap = computed(() => props.config?.form_schema?.reset_map || {})

const fieldDefinitions = computed(() => {
  return [...baseFields.value, ...withdrawalFields.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.options_from === 'withdrawal_plan.withdrawal_periods') {
    fieldProps.options = fieldProps.options || props.config?.withdrawal_plan?.withdrawal_periods
  }

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

  // 提取计划币种来自提取计划配置
  if (field.currency_from === 'withdrawal_plan.default_currency') {
    fieldProps.currency = props.config?.withdrawal_plan?.default_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, ...withdrawalFields.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,
    annual_withdrawal_amount: value.annual_withdrawal_amount ?? null,
    annual_increase_percentage: value.annual_increase_percentage ?? null,
    withdrawal_start_age_specified: value.withdrawal_start_age_specified ?? null,
    withdrawal_period_specified: value.withdrawal_period_specified ?? null,
    withdrawal_start_age_fixed: value.withdrawal_start_age_fixed ?? null,
    withdrawal_period_fixed: value.withdrawal_period_fixed ?? null
  })
}

// 监听父组件的数据变化
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,
        annual_withdrawal_amount: newVal.annual_withdrawal_amount ?? null,
        annual_increase_percentage: newVal.annual_increase_percentage ?? null,
        withdrawal_start_age_specified: newVal.withdrawal_start_age_specified ?? null,
        withdrawal_period_specified: newVal.withdrawal_period_specified ?? null,
        withdrawal_start_age_fixed: newVal.withdrawal_start_age_fixed ?? null,
        withdrawal_period_fixed: newVal.withdrawal_period_fixed ?? null
      })
      previousModelValue = newVal
    }
  },
  { immediate: true }
)

/**
 * 监听表单数据变化,同步到父组件
 */
// 监听提取模式切换,按配置清空脏数据
watch(
  () => form,
  (newVal) => {
    emit('update:modelValue', newVal)
  },
  { deep: true }
)

/**
 * 监听提取模式变化,清空对应字段
 */
watch(
  () => form.withdrawal_mode,
  (newMode) => {
    const resetFields = resetMap.value?.withdrawal_mode?.[newMode] || []
    if (resetFields.length > 0) {
      resetFields.forEach(key => {
        form[key] = null
      })
      emit('update:modelValue', { ...form })
    }
  }
)

/**
 * 提取年期选项(从配置读取)
 * @type {ComputedRef<Array<string>>}
 */
/**
 * 百分比输入限制(实时)
 * @description 限制百分比输入为有效数值,最多2位小数
 *              只允许输入数字和一个小数点
 * @param {string} value - 输入值
 */
/**
 * 百分比输入清洗,避免非法字符
 * @param {string|number} value - 输入值
 * @param {string} key - 目标字段 key
 */
const onPercentageInput = (value, key) => {
  // 转换为字符串(处理 value 为 null 或其他类型的情况)
  let strValue = String(value ?? '')

  // 移除所有非数字字符(保留小数点)
  let cleaned = strValue.replace(/[^0-9.]/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
}

/**
 * 表单校验
 * @returns {boolean} 是否通过校验
 */
/**
 * 表单校验(基于 Schema)
 * @returns {boolean} 校验是否通过
 */
const validate = () => {
  const fields = [...baseFields.value, ...(props.config.withdrawal_plan?.enabled ? withdrawalFields.value : [])]

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

    if (field.required) {
      const value = form[field.key]
      if (value === undefined || value === null || value === '') {
        Taro.showToast({ title: field.label || '请完善必填信息', icon: 'none' })
        return false
      }
    }

    if (field.type === 'percentage' && isFieldVisible(field.key)) {
      const percentage = parseFloat(form[field.key])
      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">
/* 提取计划区域样式 */
.withdrawal-plan-section {
  .nut-input {
    padding-left: 20rpx !important;
  }
}
</style>