SavingsTemplate.vue 35.9 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 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
<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)"
          @custom-select="handleCustomSelect(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>

          <!-- 由几岁开始 -->
          <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="dynamicPeriodOptions"
            :allow-custom="isCustomPeriodEnabled"
            @custom-select="openPeriodInput(index)"
            class="mb-3"
          />

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

  <!-- 自定义提取期输入弹窗 -->
  <PeriodInput
    v-model:visible="showPeriodInput"
    v-model="currentPeriodValue"
    inputLabel="请输入提取期"
    inputPlaceholder="请输入年数"
    :validation-rules="periodValidationRules"
    @confirm="onPeriodInputConfirm"
    @cancel="onPeriodInputCancel"
  />
</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 PeriodInput from '../PlanFields/PeriodInput.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.key === 'withdrawal_period_specified' || field.key === 'withdrawal_period_fixed') {
      fieldProps.allowCustom = isCustomPeriodEnabled.value
    }
  }

  // 基础币种来自模板配置
  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
})

/**
 * 有效年龄(用于阶段判断)
 * @description 优先使用填写的 age,否则从 birthday 推算年龄
 */
const effectiveAge = computed(() => {
  // 1. 优先使用填写的年龄
  if (form.age && form.age !== '') {
    const parsedAge = parseInt(form.age)
    if (!Number.isNaN(parsedAge)) {
      return parsedAge
    }
  }

  // 2. 从生日推算年龄
  if (form.birthday && form.birthday !== '') {
    const birthDate = new Date(form.birthday)
    if (!Number.isNaN(birthDate.getTime())) {
      const today = new Date()
      let age = today.getFullYear() - birthDate.getFullYear()
      const monthDiff = today.getMonth() - birthDate.getMonth()

      // 如果还没到生日,年龄减1
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--
      }

      return age
    }
  }

  // 3. 都没有,返回0
  return 0
})

/**
 * 多阶段配置对象(便捷访问)
 */
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 = effectiveAge.value
  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 = effectiveAge.value
  const threshold = multiStageConfig.value.age_threshold || 12
  return age >= threshold && stages.value.length > 1
})

/**
 * 自定义提取期输入状态
 */
const showPeriodInput = ref(false)          // 自定义输入弹窗显示状态
const currentPeriodValue = ref('')          // 当前输入的提取期值
const currentStageIndex = ref(-1)           // 当前正在编辑的阶段索引(多阶段模式)
const currentSingleStageFieldKey = ref('')  // 当前正在编辑的单阶段字段key(单阶段模式)
const customPeriodValues = ref([])          // 用户自定义的提取期值列表(临时保存)

/**
 * 自定义提取期是否启用
 * @description 多阶段模式检查 multi_stage_withdrawal 配置,单阶段模式始终启用
 */
const isCustomPeriodEnabled = computed(() => {
  // 多阶段模式:检查配置开关
  if (isMultiStageMode.value) {
    return multiStageConfig.value.custom_period?.enabled || false
  }
  // 单阶段模式:始终启用自定义输入
  return true
})

/**
 * 自定义提取期验证规则
 */
const periodValidationRules = computed(() => {
  const config = multiStageConfig.value.custom_period?.validation || {}
  return {
    min: config.min_years ?? 1,
    max: config.max_years ?? 100,
    allowed_formats: config.allowed_formats || ['终身', '一笔过'],
    custom_validators: config.custom_validators || []
  }
})

/**
 * 动态提取期选项(预设选项 + 用户自定义选项)
 */
const dynamicPeriodOptions = computed(() => {
  const baseOptions = multiStageConfig.value.withdrawal_periods ||
                      props.config?.withdrawal_plan?.withdrawal_periods ||
                      []
  // 合并预设选项和用户自定义选项
  return [...baseOptions, ...customPeriodValues.value]
})

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

/**
 * 初始化阶段数据
 * @description 根据有效年龄初始化阶段数量:
 *              - 年龄 < 12岁:固定 3 组
 *              - 年龄 ≥ 12岁:初始 1 组
 *              - 有效年龄优先使用 age,否则从 birthday 推算
 */
const initializeStages = () => {
  console.log('=== initializeStages() 调用 ===')
  console.log('form.age:', form.age, 'form.birthday:', form.birthday)
  const age = effectiveAge.value
  const threshold = multiStageConfig.value.age_threshold || 12
  console.log('effectiveAge:', age, 'threshold:', threshold)

  if (age < threshold) {
    // 固定 3 组
    stages.value = [createStage(), createStage(), createStage()]
    console.log('初始化 3 组阶段(年龄 < 12)')
  } else {
    // 初始 1 组
    stages.value = [createStage()]
    console.log('初始化 1 组阶段(年龄  12)')
  }
  console.log('stages.value:', stages.value)
}

/**
 * 添加新阶段
 * @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)
}

/**
 * 打开自定义提取期输入弹窗
 * @param {number} stageIndex - 阶段索引(多阶段模式)
 */
const openPeriodInput = (stageIndex) => {
  currentStageIndex.value = stageIndex
  currentSingleStageFieldKey.value = ''
  const stage = stages.value[stageIndex]
  currentPeriodValue.value = stage?.withdrawal_period || ''
  showPeriodInput.value = true
}

/**
 * 处理自定义提取期输入事件
 * @param {Object} field - 字段配置对象
 * @description 根据字段类型调用相应的自定义输入处理函数
 */
const handleCustomSelect = (field) => {
  if (field.key === 'withdrawal_period_specified' || field.key === 'withdrawal_period_fixed') {
    openSingleStagePeriodInput(field.key)
  }
}

/**
 * 打开单阶段自定义提取期输入
 * @param {string} fieldKey - 字段key(withdrawal_period_specified 或 withdrawal_period_fixed)
 */
const openSingleStagePeriodInput = (fieldKey) => {
  currentSingleStageFieldKey.value = fieldKey
  currentStageIndex.value = -1
  currentPeriodValue.value = form[fieldKey] || ''
  showPeriodInput.value = true
}

/**
 * 自定义提取期输入确认
 * @param {string} value - 确认的提取期值
 */
const onPeriodInputConfirm = (value) => {
  // 添加到自定义值列表(去重:不在预设选项和已存在的自定义列表中)
  const baseOptions = multiStageConfig.value.withdrawal_periods ||
                      props.config?.withdrawal_plan?.withdrawal_periods ||
                      []
  if (!baseOptions.includes(value) && !customPeriodValues.value.includes(value)) {
    customPeriodValues.value.push(value)
  }

  // 多阶段模式:更新当前阶段的值
  if (currentStageIndex.value >= 0 && currentStageIndex.value < stages.value.length) {
    stages.value[currentStageIndex.value].withdrawal_period = value
  }

  // 单阶段模式:更新表单字段的值
  if (currentSingleStageFieldKey.value) {
    form[currentSingleStageFieldKey.value] = value
  }

  // 关闭弹窗并重置状态
  showPeriodInput.value = false
  currentStageIndex.value = -1
  currentSingleStageFieldKey.value = ''
  currentPeriodValue.value = ''
}

/**
 * 自定义提取期输入取消
 */
const onPeriodInputCancel = () => {
  showPeriodInput.value = false
  currentStageIndex.value = -1
  currentSingleStageFieldKey.value = ''
  currentPeriodValue.value = ''
}

/**
 * 同步阶段数据到表单
 * @description 将 stages 数组同步到 form.withdrawal_stages,以便父组件获取
 *              同时清理 undefined 值为 null,确保提交数据格式正确
 */
watch(
  stages,
  (newStages) => {
    console.log('=== stages watch 触发 ===')
    console.log('newStages:', JSON.parse(JSON.stringify(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
    }))
    console.log('cleanedStages:', cleanedStages)
    console.log('设置 form.withdrawal_stages')
    form.withdrawal_stages = cleanedStages
    console.log('form.withdrawal_stages 已更新:', form.withdrawal_stages)
  },
  { deep: true }
)

// 监听有效年龄变化,重新初始化阶段(仅在多阶段模式下)
// 有效年龄变化可能由 age 或 birthday 引起
watch(
  effectiveAge,
  (newAge, oldAge) => {
    if (isMultiStageMode.value && newAge !== oldAge) {
      const threshold = multiStageConfig.value.age_threshold || 12

      // 跨越阈值时重新初始化
      if ((newAge < threshold && oldAge >= threshold) ||
          (newAge >= threshold && oldAge < threshold)) {
        console.log('=== 有效年龄跨越阈值,重新初始化阶段 ===')
        console.log('oldAge:', oldAge, 'newAge:', newAge, 'threshold:', threshold)
        initializeStages()
      }
    }
  }
)

// 组件挂载时初始化阶段(多阶段模式)
watch(
  isMultiStageMode,
  (enabled) => {
    console.log('=== isMultiStageMode watch ===')
    console.log('enabled:', enabled)
    console.log('stages.value.length:', stages.value.length)
    if (enabled && stages.value.length === 0) {
      console.log('条件满足,调用 initializeStages()')
      initializeStages()
    } else {
      console.log('跳过初始化')
    }
  },
  { 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) => {
    console.log('=== modelValue watch 触发 ===')
    console.log('newVal:', newVal)
    console.log('isMultiStageMode:', isMultiStageMode.value)

    if (!newVal) {
      // null 或 undefined:清空
      console.log('newVal 为空,清空表单')
      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) {
      // 父组件重置了:清空表单
      console.log('检测到重置,清空表单')
      initializeForm(newVal)
      previousModelValue = newVal
    } else {
      // 正常更新:合并新字段,保留默认值逻辑
      console.log('正常更新表单数据')
      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

      // 恢复 stages 数据(多阶段模式)
      console.log('检查是否需要恢复 stages 数据...')
      console.log('  isMultiStageMode:', isMultiStageMode.value)
      console.log('  newVal.withdrawal_stages:', newVal.withdrawal_stages)

      if (isMultiStageMode.value && newVal.withdrawal_stages && Array.isArray(newVal.withdrawal_stages)) {
        console.log('✅ 开始恢复 stages 数据')
        console.log('  当前 stages.value:', stages.value)
        console.log('  新数据 withdrawal_stages:', newVal.withdrawal_stages)

        // 深度比较,避免覆盖用户正在编辑的数据
        const currentStagesStr = JSON.stringify(stages.value)
        const newStagesStr = JSON.stringify(newVal.withdrawal_stages)
        console.log('  深度比较:', currentStagesStr === newStagesStr ? '相同' : '不同')

        if (currentStagesStr !== newStagesStr) {
          stages.value = newVal.withdrawal_stages.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
          }))
          console.log('   stages 已恢复:', stages.value)
        } else {
          console.log('  跳过恢复(数据相同)')
        }
      } else {
        console.log('   不需要恢复 stages')
      }
    }
  },
  { 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 })
    }
  }
)

// TODO(human): 年龄与出生年月日已取消联动,客户要求二者独立填写
// 如需恢复联动,可取消以下代码的注释
//
// 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) => {
  const result = (() => {
    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
  })()
  // 只在调用栈包含 validate 时打印日志,避免过多输出
  const stack = new Error().stack || ''
  if (stack.includes('validate')) {
    console.log(`isEmptyValue(${value} [${typeof value}]) = ${result}`)
  }
  return result
}

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 = () => {
  console.log('=== validate() 开始 ===')
  console.log('form 数据:', form)
  console.log('form.withdrawal_mode:', form.withdrawal_mode)
  console.log('isMultiStageMode:', isMultiStageMode.value)

  // 1. 基础字段校验(单阶段和多阶段通用)
  const fields = [...baseFields.value, ...(props.config.withdrawal_plan?.enabled ? withdrawalFields.value : [])]
  console.log('需要校验的基础字段数:', fields.length)

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

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

  // 2. 校验基础字段和 withdrawal_fields 中可见的必填字段
  for (const field of fields) {
    if (!isFieldVisible(field.key)) {
      continue
    }

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

    // 多阶段模式 + 选择"指定提取金额"时,跳过单阶段字段的校验
    // 这些字段在多阶段模式下由 validateMultiStage() 校验
    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)) {
        console.log(`跳过单阶段字段校验: ${field.key}`)
        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 = () => {
  console.log('=== validateMultiStage 开始 ===')
  console.log('stages.value:', stages.value)
  console.log('stages.value.length:', stages.value.length)

  // 多阶段字段校验
  for (let i = 0; i < stages.value.length; i++) {
    const stage = stages.value[i]
    const stageLabel = `阶段${i + 1}`

    console.log(`--- 校验 ${stageLabel} ---`)
    console.log('stage 对象:', stage)
    console.log('  annual_withdrawal_amount:', stage.annual_withdrawal_amount, '类型:', typeof stage.annual_withdrawal_amount)
    console.log('  withdrawal_start_age:', stage.withdrawal_start_age, '类型:', typeof stage.withdrawal_start_age)
    console.log('  withdrawal_period:', stage.withdrawal_period, '类型:', typeof stage.withdrawal_period)
    console.log('  annual_increase_percentage:', stage.annual_increase_percentage, '类型:', typeof stage.annual_increase_percentage)

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

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

    // 提取期(必填)
    console.log('检查 withdrawal_period isEmptyValue:', isEmptyValue(stage.withdrawal_period))
    if (isEmptyValue(stage.withdrawal_period)) {
      console.log(`❌ ${stageLabel}: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) {
        console.log(`❌ ${stageLabel}:递增百分比超出范围`)
        Taro.showToast({ title: `${stageLabel}:递增百分比请输入0-100之间的数值`, icon: 'none' })
        return false
      }
    }
    console.log(`✅ ${stageLabel} 校验通过`)
  }

  console.log('=== validateMultiStage 全部通过 ===')
  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>