PlanFormContainer.vue 12.5 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
<template>
  <!-- 使用 PlanPopupNew 容器组件(支持全局弹窗管理器) -->
  <PlanPopupNew
    :visible="props.visible"
    :title="templateConfig?.name || '计划书'"
    :has-template="hasTemplate"
    @close="close"
    @submit="submit"
  >
    <!-- 动态加载模版组件 -->
    <component
      :is="currentTemplateComponent"
      ref="templateRef"
      v-model="formData"
      :config="templateConfig?.config"
      v-if="currentTemplateComponent && templateConfig?.config"
    />

    <!-- 错误提示 -->
    <div v-else class="text-center text-gray-500 py-10">
      <p>⚠️ 未找到对应的计划书模版</p>
      <p class="text-sm mt-2">form_sn: {{ product?.form_sn }}</p>
    </div>
  </PlanPopupNew>
</template>

<script setup>
/**
 * 计划书表单容器
 *
 * @description 根据产品的 form_sn 动态加载对应的计划书模版组件
 *              - 自动识别产品并加载模版
 *              - 支持后端 plan_config 动态配置
 *              - 统一的表单提交处理
 * @author Claude Code
 * @example
 * <PlanFormContainer
 *   v-model:visible="showPlanPopup"
 *   :product="selectedProduct"
 *   @close="handleClose"
 *   @submit="handleSubmit"
 * />
 */
import { ref, computed, watch, nextTick } from 'vue'
import Taro from '@tarojs/taro'
import PlanPopupNew from './PlanPopupNew.vue'
import LifeInsuranceTemplate from './PlanTemplates/LifeInsuranceTemplate.vue'
import CriticalIllnessTemplate from './PlanTemplates/CriticalIllnessTemplate.vue'
import SavingsTemplate from './PlanTemplates/SavingsTemplate.vue'
import { PLAN_TEMPLATES } from '@/config/plan-templates'
import { addAPI } from '@/api/plan'
import { useFieldValueTransform } from '@/composables/useFieldValueTransform'

/**
 * 组件属性
 */
const props = defineProps({
  /**
   * 是否显示弹窗
   * @type {boolean}
   */
  visible: {
    type: Boolean,
    default: false
  },

  /**
   * 产品对象
   * @type {Object}
   * @property {number} id - 产品 ID
   * @property {string} product_name - 产品名称
   * @property {string} form_sn - 模版标识(必需)
   * @property {Object} plan_config - 模版配置(可选,后端返回)
   */
  product: {
    type: Object,
    required: false,
    default: null
  }
})

/**
 * 组件事件
 */
const emit = defineEmits([
  /**
   * 更新显示状态事件
   * @event update:visible
   * @param {boolean} value - 显示状态
   */
  'update:visible',

  /**
   * 关闭事件
   * @event close
   */
  'close',

  /**
   * 提交事件
   * @event submit
   * @param {Object} formData - 表单数据
   */
  'submit'
])

/**
 * 当前模版配置
 * @description 根据 form_sn 从配置文件中查找,并合并后端 plan_config
 *
 * @example
 * // product.form_sn = 'life-insurance-wiop3e'
 * // templateConfig() 返回: {
 * //   name: 'WIOP3E...',
 * //   component: 'LifeInsuranceTemplate',
 * //   config: { currency: 'USD', ... }
 * // }
 */
const templateConfig = computed(() => {
  if (!props.product) {
    return null
  }

  if (!props.product.form_sn) {
    console.warn('[PlanFormContainer] 产品缺少 form_sn 字段', props.product)
    return null
  }

  // 从配置文件中查找模版
  const config = PLAN_TEMPLATES[props.product.form_sn]
  if (!config) {
    console.error(`[PlanFormContainer] 未找到模版配置: ${props.product.form_sn}`)
    return null
  }

  // 合并配置:优先使用后端返回的 plan_config,否则使用配置文件中的默认配置
  return {
    ...config.config,  // 只展开 config.config
    ...config,  // 展开其他顶层属性(name, component, category, form_schema, submit_mapping)
    ...(props.product.plan_config || {})
  }
})

/**
 * 当前模版组件
 * @description 根据 component 名称动态加载对应的组件
 */
const currentTemplateComponent = computed(() => {
  if (!templateConfig.value) {
    return null
  }

  const componentMap = {
    'LifeInsuranceTemplate': LifeInsuranceTemplate,
    'CriticalIllnessTemplate': CriticalIllnessTemplate,
    'SavingsTemplate': SavingsTemplate
  }

  const componentName = templateConfig.value.component
  return componentMap[componentName] || null
})

/**
 * 是否找到模板
 * @description 用于控制底部按钮显示(找到模板:取消/生成计划书;未找到:关闭)
 */
const hasTemplate = computed(() => {
  return currentTemplateComponent.value !== null && templateConfig.value?.config !== undefined
})

/**
 * 表单数据
 */
const formData = ref({})

/**
 * 模版组件引用
 */
const templateRef = ref(null)
const isClosingFromChild = ref(false)

/**
 * 监听显示状态变化,弹窗打开时确保表单是干净的
 * @description 这是最后的安全网,确保弹窗打开时表单一定是空的
 */
watch(
  () => props.visible,
  async (newVal, oldVal) => {
    if (newVal && Object.keys(formData.value).length > 0) {
      // 弹窗打开且表单有数据时,强制重置
      console.log('[PlanFormContainer] 弹窗打开时检测到残留数据,强制重置')
      resetForm()
    }

    if (!newVal && oldVal && !isClosingFromChild.value) {
      await nextTick()
      resetForm()
    }
  }
)

/**
 * 关闭弹窗
 * @description 关闭时重置表单数据,避免下次打开时保留旧数据
 *
 * ⚠️ 重要:必须使用 nextTick 延迟重置
 * 原因:避免响应式更新时序问题,确保子组件完全卸载后再重置数据
 *
 * 时序问题示例:
 * 1. close() → resetForm() → emit('close')
 * 2. emit('close') → 父组件设置 visible = false
 * 3. 子组件开始卸载(异步)
 * 4. ⚠️ 如果在步骤3之前就重置,子组件可能还保留旧数据
 *
 * 解决方案:
 * 1. 先触发关闭事件(让父组件更新 visible)
 * 2. 等待 nextTick(确保 DOM 更新完成)
 * 3. 再重置表单数据
 */
const close = async () => {
  console.log('[PlanFormContainer] 关闭弹窗,准备重置表单')

  isClosingFromChild.value = true

  // ⚠️ 关键:先触发关闭事件,让父组件更新 visible
  emit('close')

  // 等待 Vue 的响应式更新完成(确保子组件开始卸载)
  await nextTick()

  // 现在重置表单,确保不会被子组件保留的引用覆盖
  resetForm()

  isClosingFromChild.value = false

  console.log('[PlanFormContainer] 弹窗已关闭,表单已重置')
}

/**
 * 提交表单
 * @description 将表单数据与产品信息组装后提交到后端
 * @returns {Promise<boolean>} 是否提交成功
 */
const submit = async () => {
  if (!props.product) {
    console.error('[PlanFormContainer] 无法提交: 产品数据为空')
    Taro.showToast({
      title: '产品数据为空',
      icon: 'none',
      duration: 3000
    })
    return false
  }

  // 调用模版组件的校验方法
  if (templateRef.value && templateRef.value.validate) {
    const isValid = templateRef.value.validate()
    if (!isValid) {
      return false
    }
  }

  // 显示加载提示
  Taro.showLoading({
    title: '提交中...',
    mask: true
  })

  try {
    // 默认字段映射:模板未提供 submit_mapping 时使用
    const defaultMapping = {
      customer_name: { api_field: 'customer_name' },
      gender: { api_field: 'customer_gender' },
      birthday: { api_field: 'customer_birthday' },
      smoker: { api_field: 'smoking_status' },
      coverage: { api_field: 'annual_premium', transform: 'fen_to_yuan' },
      payment_period: { api_field: 'payment_years' },
      withdrawal_enabled: { api_field: 'allow_reduce_amount' },
      withdrawal_mode: { api_field: 'withdrawal_option' },
      withdrawal_method: { api_field: 'withdrawal_method' },
      annual_withdrawal_amount: { api_field: 'annual_withdrawal_amount', transform: 'fen_to_yuan' },
      annual_increase_percentage: { api_field: 'annual_increase_percentage' },
      withdrawal_start_age_specified: { api_field: 'withdrawal_start_age' },
      withdrawal_period_specified: { api_field: 'withdrawal_period' },
      withdrawal_start_age_fixed: { api_field: 'withdrawal_start_age' },
      withdrawal_period_fixed: { api_field: 'withdrawal_period' },
      total_amount: { api_field: 'total_premium', transform: 'fen_to_yuan' }
    }

    // 构建请求数据
    const requestData = {
      product_id: props.product.id
    }

    // 映射表单字段到 API 字段
    const submitMapping = templateConfig.value?.config?.submit_mapping || defaultMapping
    const { toYuan } = useFieldValueTransform(formData, submitMapping)

    Object.keys(formData.value).forEach(key => {
      const mapping = submitMapping[key]
      if (mapping) {
        const apiField = typeof mapping === 'string' ? mapping : mapping.api_field
        let value = formData.value[key]
        // 金额字段从分转换为元
        if (typeof mapping === 'object' && mapping.transform === 'fen_to_yuan' && value !== null && value !== undefined && value !== '') {
          value = toYuan(key, value)
        }
        requestData[apiField] = value
      } else {
        requestData[key] = formData.value[key]
      }
    })

    if (formData.value?.withdrawal_mode === '指定提取金额') {
      const specifiedStart = formData.value.withdrawal_start_age_specified
      const specifiedPeriod = formData.value.withdrawal_period_specified
      if (specifiedStart !== undefined && specifiedStart !== null && specifiedStart !== '') {
        requestData.withdrawal_start_age = specifiedStart
      }
      if (specifiedPeriod !== undefined && specifiedPeriod !== null && specifiedPeriod !== '') {
        requestData.withdrawal_period = specifiedPeriod
      }
    }

    if (formData.value?.withdrawal_mode === '最高固定提取金额') {
      const fixedStart = formData.value.withdrawal_start_age_fixed
      const fixedPeriod = formData.value.withdrawal_period_fixed
      if (fixedStart !== undefined && fixedStart !== null && fixedStart !== '') {
        requestData.withdrawal_start_age = fixedStart
      }
      if (fixedPeriod !== undefined && fixedPeriod !== null && fixedPeriod !== '') {
        requestData.withdrawal_period = fixedPeriod
      }
    }

    // 添加币种类型(如果有配置)
    if (templateConfig.value?.config?.currency) {
      requestData.currency_type = templateConfig.value.config.currency
    }

    console.log('[PlanFormContainer] 提交计划书请求数据:', requestData)
    console.log('[PlanFormContainer] 字段映射:', submitMapping)

    // 调用 API
    const res = await addAPI(requestData)

    // 判断成功:既要 code === 1,也要有 order_id
    const isSuccess = res.code === 1 && res.data?.order_id

    if (isSuccess) {
      Taro.hideLoading()

      // ✅ 移除 toast,因为结果页已经显示了成功/失败状态
      // 避免用户从结果页返回时看到重复的 toast 提示

      // 发送提交成功事件(携带 order_id)
      emit('submit', {
        success: true,
        order_id: res.data.order_id,
        product_id: props.product.id,
        form_sn: props.product.form_sn
      })

      return true
    } else {
      Taro.hideLoading()

      // 🔍 调试:完整响应数据
      console.log('[PlanFormContainer] API 完整响应:', res)
      console.log('[PlanFormContainer] res.data:', res.data)
      console.log('[PlanFormContainer] res.msg:', res.msg)
      console.log('[PlanFormContainer] res.data?.msg:', res.data?.msg)

      // 失败时,尝试从 res.data 或 res.msg 中获取错误信息
      // 注意:fn() 函数会将 res.data 设置为 null,但 res.msg 保留了
      const errorMsg = res.data?.msg || res.msg || '提交失败,请稍后重试'

      console.log('[PlanFormContainer] 最终错误信息:', errorMsg)

      Taro.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000
      })

      // 返回失败结果,传递错误信息给父组件
      emit('submit', {
        success: false,
        message: errorMsg
      })

      return false
    }
  } catch (error) {
    Taro.hideLoading()

    console.error('[PlanFormContainer] 提交计划书失败:', error)

    Taro.showToast({
      title: '网络异常,请重试',
      icon: 'none',
      duration: 3000
    })

    return false
  }

  // ✅ 不在这里重置表单,让父组件先处理数据
  // 重置逻辑交给 close() 函数处理(关闭弹窗时自动清空)
}

/**
 * 重置表单数据
 * @description 清空表单数据和错误状态
 */
const resetForm = () => {
  console.log('[PlanFormContainer] 重置表单数据')

  // 重置表单数据
  formData.value = {}

  // 重置子组件的验证状态(如果有)
  if (templateRef.value && templateRef.value.clearErrors) {
    templateRef.value.clearErrors()
  }
}
</script>

<style lang="less">
/* 容器样式 */
</style>