SavingsTemplate.vue 25.2 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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
<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">
      <!-- 1. 渲染 withdrawal_fields(包含 withdrawal_enabledwithdrawal_modewithdrawal_method 等) -->
      <!-- 注意:多阶段模式 + 选择"指定提取金额"时,跳过单组字段渲染 -->
      <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="shouldRenderField(field) && field.type !== 'percentage'"
          :is="getFieldComponent(field)"
          v-model="form[field.key]"
          v-bind="getFieldProps(field)"
          class="mb-5"
        />
        <div v-else-if="shouldRenderField(field) && 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>

      <!-- 2. 多阶段模式 + 选择"指定提取金额":显示多组阶段卡片 -->
      <div v-if="isMultiStageMode && form.withdrawal_mode === '指定提取金额'" class="multi-stage-withdrawal-section">
        <!-- 阶段卡片列表 -->
        <div
          v-for="(stage, index) in stages"
          :key="index"
          class="stage-card bg-white border border-gray-200 rounded-lg p-4 mb-4"
        >
          <!-- 阶段标题 -->
          <div class="flex items-center justify-between mb-3">
            <h4 class="text-sm font-medium text-gray-900">阶段{{ index + 1 }}</h4>
            <!-- 删除按钮(≥12岁且至少有2个阶段时显示) -->
            <nut-button
              v-if="canRemoveStage && index > 0"
              size="small"
              type="danger"
              @click="removeStage(index)"
            >
              删除
            </nut-button>
          </div>

          <!-- 每年提取金额 -->
          <PlanFieldAmount
            v-model="stage.annual_withdrawal_amount"
            label="每年提取金额"
            placeholder="请输入每年提取金额"
            inputLabel="请输入每年提取金额"
            :required="true"
            :currency="config.withdrawal_plan?.default_currency || config.currency"
            class="mb-3"
          />

          <!-- 由几岁开始 -->
          <PlanFieldAgePicker
            v-model="stage.withdrawal_start_age"
            label="由几岁开始"
            placeholder="请输入开始提取年龄"
            :required="true"
            class="mb-3"
          />

          <!-- 提取期 -->
          <PlanFieldSelect
            v-model="stage.withdrawal_period"
            label="提取期"
            placeholder="请选择提取期"
            :required="true"
            :options="multiStagePeriodOptions"
            class="mb-3"
          />

          <!-- 每年递增提取之百分比(可选) -->
          <div class="percentage-field">
            <div class="text-sm text-gray-700 mb-2 flex items-center">
              <span>每年递增提取之百分比(%</span>
              <span class="text-gray-400 text-xs ml-2">(可选)</span>
            </div>
            <nut-input
              v-model="stage.annual_increase_percentage"
              type="digit"
              placeholder="请输入递增百分比"
              @input="(value) => onPercentageInput(value, `stages.${index}.annual_increase_percentage`)"
              class="w-full"
            />
          </div>
        </div>

        <!-- 添加阶段按钮(≥12岁且未达上限时显示) -->
        <nut-button
          v-if="canAddStage"
          type="primary"
          block
          @click="addStage"
          class="add-stage-btn"
        >
          + 添加阶段
        </nut-button>
      </div>
    </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, ref } 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)

/**
 * 判断字段是否应该渲染
 * @description 多阶段模式 + 选择"指定提取金额"时,跳过单组字段渲染
 * @param {Object} field - 字段配置
 * @returns {boolean} 是否应该渲染
 */
const shouldRenderField = (field) => {
  // 基础可见性检查
  if (!isFieldVisible(field.key)) return false

  // 多阶段模式 + 选择"指定提取金额"时,跳过部分单组字段
  // 注意:withdrawal_method(提取方式)需要保留
  if (isMultiStageMode.value && form.withdrawal_mode === '指定提取金额') {
    // 需要跳过的字段:单阶段"指定提取金额"的金额和期数相关字段
    const skipFields = [
      'annual_withdrawal_amount',
      'withdrawal_start_age_specified',
      'withdrawal_period_specified',
      'annual_increase_percentage'
    ]
    if (skipFields.includes(field.key)) return false
  }

  return true
}

// ====== 多阶段提取计划逻辑 ======

/**
 * 是否为多阶段模式
 * @description 检查产品配置是否启用了 multi_stage_withdrawal
 */
const isMultiStageMode = computed(() => {
  return props.config?.multi_stage_withdrawal?.enabled === true
})

/**
 * 多阶段配置对象(便捷访问)
 */
const multiStageConfig = computed(() => {
  return props.config?.multi_stage_withdrawal || {}
})

/**
 * 多阶段提取期选项(包含"一笔过")
 */
const multiStagePeriodOptions = computed(() => {
  return multiStageConfig.value.withdrawal_periods ||
         props.config?.withdrawal_plan?.withdrawal_periods ||
         []
})

/**
 * 阶段数据数组
 * @description 每个阶段包含:annual_withdrawal_amount, withdrawal_start_age, withdrawal_period, annual_increase_percentage
 */
const stages = ref([])

/**
 * 是否可添加阶段
 * @description 年龄 ≥ 阈值且未达上限
 */
const canAddStage = computed(() => {
  const age = parseInt(form.age) || 0
  const threshold = multiStageConfig.value.age_threshold || 12
  const limit = multiStageConfig.value.stage_limit || 4
  return age >= threshold && stages.value.length < limit
})

/**
 * 是否可删除阶段
 * @description 年龄 ≥ 阈值且至少有2个阶段
 */
const canRemoveStage = computed(() => {
  const age = parseInt(form.age) || 0
  const threshold = multiStageConfig.value.age_threshold || 12
  return age >= threshold && stages.value.length > 1
})

/**
 * 创建空的阶段数据
 * @returns {Object} 空阶段对象
 */
const createStage = () => ({
  annual_withdrawal_amount: null,
  withdrawal_start_age: null,
  withdrawal_period: null,
  annual_increase_percentage: null
})

/**
 * 初始化阶段数据
 * @description 根据年龄初始化阶段数量:
 *              - 年龄 < 12岁:固定 3 组
 *              - 年龄 ≥ 12岁:初始 1 组
 */
const initializeStages = () => {
  const age = parseInt(form.age) || 0
  const threshold = multiStageConfig.value.age_threshold || 12

  if (age < threshold) {
    // 固定 3 组
    stages.value = [createStage(), createStage(), createStage()]
  } else {
    // 初始 1 组
    stages.value = [createStage()]
  }
}

/**
 * 添加新阶段
 * @description 在当前阶段列表末尾添加一个空阶段
 */
const addStage = () => {
  if (!canAddStage.value) return
  stages.value.push(createStage())
}

/**
 * 删除指定阶段
 * @param {number} index - 要删除的阶段索引
 */
const removeStage = (index) => {
  if (!canRemoveStage.value) return
  stages.value.splice(index, 1)
}

/**
 * 同步阶段数据到表单
 * @description 将 stages 数组同步到 form.withdrawal_stages,以便父组件获取
 *              同时清理 undefined 值为 null,确保提交数据格式正确
 */
watch(
  stages,
  (newStages) => {
    // 清理每个阶段的 undefined 值为 null
    const cleanedStages = newStages.map(stage => ({
      annual_withdrawal_amount: stage.annual_withdrawal_amount ?? null,
      withdrawal_start_age: stage.withdrawal_start_age ?? null,
      withdrawal_period: stage.withdrawal_period ?? null,
      annual_increase_percentage: stage.annual_increase_percentage ?? null
    }))
    form.withdrawal_stages = cleanedStages
  },
  { deep: true }
)

// 监听年龄变化,重新初始化阶段(仅在多阶段模式下)
watch(
  () => form.age,
  (newAge, oldAge) => {
    if (isMultiStageMode.value && newAge !== oldAge && newAge !== undefined) {
      const threshold = multiStageConfig.value.age_threshold || 12
      const newAgeInt = parseInt(newAge) || 0
      const oldAgeInt = parseInt(oldAge) || 0

      // 跨越阈值时重新初始化
      if ((newAgeInt < threshold && oldAgeInt >= threshold) ||
          (newAgeInt >= threshold && oldAgeInt < threshold)) {
        initializeStages()
      }
    }
  }
)

// 组件挂载时初始化阶段(多阶段模式)
watch(
  isMultiStageMode,
  (enabled) => {
    if (enabled && stages.value.length === 0) {
      initializeStages()
    }
  },
  { immediate: true }
)

// ====== 原有表单逻辑 ======

/**
 * 获取 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 })
    }
  }
)

/**
 * 年龄与出生年月日自动计算逻辑
 * - 填年龄 → 推算生日(默认当年1月1日)
 * - 填生日 → 计算年龄
 */
watch(
  () => form.age,
  (newAge) => {
    if (!isEmptyValue(newAge) && isEmptyValue(form.birthday)) {
      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
    }
  }
)

/**
 * 提取年期选项(从配置读取)
 * @type {ComputedRef<Array<string>>}
 */
/**
 * 百分比输入限制(实时)
 * @description 限制百分比输入为有效数值,最多2位小数
 *              只允许输入数字和一个小数点
 * @param {string} value - 输入值
 */
/**
 * 百分比输入清洗,避免非法字符
 * @param {string|number} value - 输入值
 * @param {string} key - 目标字段 key(支持多阶段路径:stages.${index}.annual_increase_percentage)
 */
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'
    }
  }

  // 处理多阶段路径(如 stages.0.annual_increase_percentage)
  if (key.startsWith('stages.')) {
    const pathParts = key.split('.')
    const stageIndex = parseInt(pathParts[1])
    const fieldKey = pathParts[2]
    if (!Number.isNaN(stageIndex) && stages.value[stageIndex]) {
      stages.value[stageIndex][fieldKey] = cleaned
    }
  } else {
    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
}

/**
 * 表单校验
 * @returns {boolean} 是否通过校验
 */
/**
 * 表单校验(基于 Schema)
 * @returns {boolean} 校验是否通过
 */
const validate = () => {
  // 1. 基础字段校验(单阶段和多阶段通用)
  const fields = [...baseFields.value, ...(props.config.withdrawal_plan?.enabled ? withdrawalFields.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 = currentYear - birthYear
  }

  // 2. 校验基础字段和 withdrawal_fields 中可见的必填字段
  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
        }
      }
    }
  }

  // 3. 多阶段模式 + 选择"指定提取金额":额外校验多阶段卡片
  if (isMultiStageMode.value && form.withdrawal_mode === '指定提取金额') {
    return validateMultiStage()
  }

  return true
}

/**
 * 多阶段表单校验
 * @description 校验多阶段卡片的必填字段
 * @note 基础字段和 withdrawal_fields 已在 validate() 中校验
 * @returns {boolean} 校验是否通过
 */
const validateMultiStage = () => {
  // 多阶段字段校验
  for (let i = 0; i < stages.value.length; i++) {
    const stage = stages.value[i]
    const stageLabel = `阶段${i + 1}`

    // 每年提取金额(必填)
    if (isEmptyValue(stage.annual_withdrawal_amount)) {
      Taro.showToast({ title: `${stageLabel}:请输入每年提取金额`, icon: 'none' })
      return false
    }

    // 由几岁开始(必填)
    if (isEmptyValue(stage.withdrawal_start_age)) {
      Taro.showToast({ title: `${stageLabel}:请输入由几岁开始`, icon: 'none' })
      return false
    }

    // 提取期(必填)
    if (isEmptyValue(stage.withdrawal_period)) {
      Taro.showToast({ title: `${stageLabel}:请选择提取期`, icon: 'none' })
      return false
    }

    // 每年递增提取之百分比(可选,校验范围)
    if (!isEmptyValue(stage.annual_increase_percentage)) {
      const percentage = parseFloat(stage.annual_increase_percentage)
      if (Number.isNaN(percentage) || percentage < 0 || percentage > 100) {
        Taro.showToast({ title: `${stageLabel}:递增百分比请输入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;
  }
}

/* 多阶段提取计划样式 */
.multi-stage-withdrawal-section {
  .stage-card {
    background: #ffffff;
    border-radius: 12rpx;
    padding: 32rpx;
    margin-bottom: 32rpx;
    border: 1rpx solid #e5e7eb;
  }

  .stage-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #111827;
  }

  .percentage-field {
    margin-top: 24rpx;
  }

  .add-stage-btn {
    margin-top: 24rpx;
    border-radius: 12rpx;
  }
}
</style>