<template>
  <!-- v-if="processedProductData.length > 0" -->
  <div>
    <div ref="productRef">
      <CommonForm
        :anchorList="anchorList"
        :affixOffset="affixOffset"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
        :scrollOffset="10"
        :domIndex="tabIndex"
        :activeName="activeName"
        v-if="productRef"
      >
        <template #form-right>
          <el-form ref="productFormRef" :model="form" :rules="rules">
            <el-row
              v-for="father in processedProductData"
              style="margin-bottom: 10px"
              :id="father.anchorKey"
            >
              <div class="formBox formFna">
                <CardOne :title="father.fatherTitle">
                  <template #content>
                    <el-row v-if="!father.showTable" :gutter="20">
                      <template v-for="child in father.data" :key="child.key">
                        <el-col :sm="child.sm" :lg="child.lg" class="formItem" v-if="child.show">
                          <div>
                            <el-form-item
                              :label="child.label"
                              :prop="father.key + '.' + child.key"
                              :key="child.key"
                              :label-width="child.labelWidth"
                              :label-position="child.labelPosition"
                            >
                              <el-input
                                v-if="child.domType === 'Input'"
                                :type="child.inputType"
                                v-model="form[father.key][child.key]"
                                :placeholder="child.placeholder"
                                maxlength="30"
                                :disabled="editStatus"
                                :style="{ width: child.inputWidth ? child.inputWidth : '100%' }"
                              />
                              <el-select
                                v-if="child.domType === 'Select'"
                                v-model="form[father.key][child.key]"
                                :placeholder="child.placeholder"
                                @change="handleSelectChange(father, child)"
                                :disabled="editStatus"
                              >
                                <el-option
                                  v-for="item in child.options"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </el-select>
                              <el-date-picker
                                style="width: 100%"
                                v-if="child.domType === 'DatePicker'"
                                v-model="form[father.key][child.key]"
                                type="date"
                                :placeholder="child.placeholder"
                                :disabled="editStatus"
                              />
                              <el-checkbox-group
                                v-if="child.domType === 'Checkbox'"
                                v-model="form[father.key][child.key]"
                                :disabled="editStatus"
                              >
                                <el-checkbox
                                  v-for="item in child.options"
                                  :key="item.value"
                                  :label="item.value"
                                >
                                  {{ item.label }}
                                </el-checkbox>
                              </el-checkbox-group>
                              <el-select
                                v-model="form[father.key][child.key]"
                                v-if="child.domType === 'SearchSelect'"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入关键词搜索"
                                :remote-method="query => searchSelectList(query, child.key)"
                                :loading="searchLoadingStates[child.key]"
                                :disabled="editStatus"
                                @change="handleSearchSelectChange(father, child.key)"
                              >
                                <el-option
                                  v-for="item in searchOptions[child.key] || []"
                                  :key="item.id"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </template>
                    </el-row>
                    <!-- 是表格数据 -->
                    <el-row v-if="father.showTable">
                      <el-col :span="24" v-if="father.addChildren">
                        <el-button
                          :disabled="editStatus"
                          type="primary"
                          icon="Plus"
                          size="small"
                          style="margin-bottom: 10px"
                          @click="addChildren(father)"
                          >{{ father.addChildrenTxt }}</el-button
                        >
                      </el-col>
                      <el-table :data="father.data" border v-if="father.data.length > 0">
                        <!-- 动态渲染列 -->
                        <el-table-column
                          v-for="column in father.columns"
                          :key="column.prop"
                          :label="column.label"
                          :prop="column.prop"
                          align="center"
                        >
                          <template #default="scope">
                            <span v-if="column.type === 'text'">{{ scope.row[column.prop] }}</span>
                          </template>
                        </el-table-column>

                        <!-- 操作列（固定） -->
                        <el-table-column align="center" label="操作" width="150" fixed="right">
                          <template #default="scope">
                            <el-button
                              type="primary"
                              size="small"
                              @click="updateChildren(father, scope.row)"
                              :disabled="props.editStatus"
                            >
                              修改
                            </el-button>
                            <el-button
                              type="danger"
                              size="small"
                              @click="deleteChildren(father, scope.$index)"
                              :disabled="props.editStatus"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-row>
                  </template>
                </CardOne>
              </div>
            </el-row>
          </el-form>
        </template>
      </CommonForm>
    </div>
    <CommonDialog
      :dialogTitle="dialogTitle"
      confirmText="确定"
      cancleText="关闭"
      dialogWidth="70%"
      :showClose="true"
      :openDialog="dialogVisible"
      @close="dialogVisible = false"
      @confirm="dialogProductConfirm"
    >
      <div class="dialogBox">
        <el-form :model="dialogForm" ref="dialogFormRef">
          <el-row :gutter="20">
            <template v-for="(child, dIndex) in additionalProductForm">
              <el-col :sm="child.sm" :lg="child.lg" class="formItem">
                <el-form-item
                  :label="child.label"
                  :prop="child.key"
                  :key="child.key"
                  :label-width="child.labelWidth"
                  :label-position="child.labelPosition"
                >
                  <el-input
                    v-if="child.domType === 'Input'"
                    :type="child.inputType"
                    v-model="dialogForm[child.key]"
                    :placeholder="child.placeholder"
                    maxlength="30"
                  />

                  <el-select
                    v-if="child.domType === 'Select'"
                    v-model="dialogForm[child.key]"
                    :placeholder="child.placeholder"
                  >
                    <el-option
                      v-for="item in child.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-date-picker
                    style="width: 100%"
                    v-if="child.domType === 'DatePicker'"
                    v-model="dialogForm[child.key]"
                    type="date"
                    :placeholder="child.placeholder"
                  />
                  <el-select
                    v-model="dialogForm[child.key]"
                    v-if="child.domType === 'SearchSelect'"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索"
                    @change="handleSearchSelectChange('', child.key)"
                    :remote-method="query => searchSelectList(query, child.key)"
                    :loading="searchLoadingStates[child.key]"
                  >
                    <el-option
                      v-for="item in searchOptions[child.key] || []"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>
    </CommonDialog>
  </div>
</template>
<script setup name="customer">
import CommonForm from '@/views/components/commonForm'
import CommonDialog from '@/components/commonDialog'

import CardOne from '@/components/formCard/cardOne'
import useDictStore from '@/store/modules/dict'
import productDomData from '@/formJson/productPlan'
import { watch } from 'vue'

import {
  getInsuranceProductList,
  getAdditionalProductList,
  secondAdditonalList,
  getInsuranceCategory,
  getInsuranceCompany
} from '@/api/common'
import { editProductPlanInfo, delAdditional } from '@/api/sign/appointment'
import { updatePolicyProduct, delPolicyAdditional } from '@/api/sign/underwritingMain'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  fnaFormBizId: { type: String, default: '' }, //提交状态，新增、修改
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  dictTypeLists: { type: Array, default: () => [] }, //多个字典值数据
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  showSubmitBtn: { type: Boolean, default: false }, //父组件状态，新增、修改
  pageSource: { type: String, default: '' }, //页面来源
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiProductPlanInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  affixOffset: { type: Number }, //父组件传递过来的预约的状态
  fatherTabName: { type: String, default: '' }, //一级tab名称
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  editStatus: { type: Boolean, default: true }, //编辑状态
  tabIndex: { type: [String, Number], default: '' } //tab索引
})
const emit = defineEmits(['handleSuccessEdit', 'policyEditSuccess'])
const { proxy } = getCurrentInstance()
// const { sys_no_yes } = proxy.useDict('sys_no_yes')
const dialogTitle = ref('新增')
const dialogKey = ref('')
const dialogVisible = ref(false)
const productRef = ref(null) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息

const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const currencyType = ref([]) // 是否列表
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const additionalProductForm = ref([]) // 附加险的表单
const data = reactive({
  form: { apiProductPlanMainInfoDto: {}, apiProductPlanAdditionalInfoDtoList: [] },
  tempForm: {}, //由于切换tab的时候，表单数据会重置，所以需要保存一份临时表单数据
  processedProductData: [], // 处理后的表单数据
  oldProductDomData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  dialogForm: {},
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedProductData, queryParams, oldProductDomData, tempForm, dialogForm } =
  toRefs(data)
const deleteChildren = (father, index) => {
  if (father.key == 'apiProductPlanAdditionalInfoDtoList') {
    father.data.splice(index, 1)
    proxy.$message.success('附加计划删除成功')
  }
}
const updateChildren = (father, row) => {
  dialogForm.value = JSON.parse(JSON.stringify(row))
  if (father.key == 'apiProductPlanAdditionalInfoDtoList') {
    dialogTitle.value = '修改附加计划'
    dialogKey.value = 'apiProductPlanAdditionalInfoDtoList'
    additionalProductForm.value = JSON.parse(JSON.stringify(father.formItem))
    searchOptions.value['productLaunchName'] = dictStore.productAdditionalList
    // 给弹窗里的供款年期赋值，否则下拉框没数据 有bug,有空再调试
    // additionalProductForm.value.forEach(item => {
    //   searchOptions.value['productLaunchName'].forEach(item1 => {
    //     if (item1.value == dialogForm.value['productLaunchName']) {
    //       item1.apiAttributeSettingDtoList.forEach(item2 => {
    //         if (
    //           item2.attributeSettingBizId == 'attribute_setting_okpcuc8tlXRfVIAy' &&
    //           item.key == 'issueNumber'
    //         ) {

    //           if (item2.value) {
    //             item.options = item2.value
    //               .split(/[，,;；\s]+/)
    //               .map(item => item.trim())
    //               .filter(item => item !== '')
    //               .map(item => {
    //                 return { label: item, value: item }
    //               })
    //           }
    //         }
    //       })
    //     }
    //   })
    // })
  }
  dialogVisible.value = true
}
const dialogProductConfirm = () => {
  proxy.$refs['dialogFormRef'].validate((valid, fields) => {
    if (valid) {
      let newDOM = JSON.parse(JSON.stringify(processedProductData.value))
      for (const section of newDOM) {
        if (section.key == dialogKey.value) {
          // 处理下拉值得显示
          for (const child of section.formItem) {
            if (child.domType == 'Select' && dialogForm.value[child.key]) {
              child.options.forEach(item => {
                if (item.value == dialogForm.value[child.key]) {
                  dialogForm.value[child.key + 'Value'] = item.label
                }
              })
            }
            if (child.domType == 'SearchSelect' && dialogForm.value[child.key]) {
              if (child.key == 'productLaunchName') {
                dictStore.productAdditionalList.forEach(item => {
                  if (item.value == dialogForm.value[child.key]) {
                    dialogForm.value[child.key + 'Value'] = item.label
                  }
                })
              }
            }
          }
          let index = section.data.findIndex(item => item.id == dialogForm.value.id)
          if (index == -1) {
            section.data.push(dialogForm.value)
          } else {
            section.data[index] = JSON.parse(JSON.stringify(dialogForm.value))
          }
        }
      }
      processedProductData.value = newDOM
      dialogVisible.value = false
      dialogForm.value = {}
    }
  })
}
// 添加表单子级dom
const addChildren = father => {
  if (props.editStatus) {
    proxy.$message.warning('请先点击编辑')
    return
  }
  dialogForm.value = { id: Date.now() + Math.floor(Math.random()) }
  if (father.key == 'apiProductPlanAdditionalInfoDtoList') {
    dialogTitle.value = '新增附加计划'
    dialogKey.value = father.key
    additionalProductForm.value = JSON.parse(JSON.stringify(father.formItem))
    dialogVisible.value = true
  }
}
const handleSearchSelectChange = (father, key) => {
  // 附加计划选择产品后，给供款期数下拉框赋值
  if (key == 'productLaunchName') {
    additionalProductForm.value.forEach(item => {
      searchOptions.value['productLaunchName'].forEach(item1 => {
        if (item1.value == dialogForm.value['productLaunchName']) {
          dialogForm.value['productLaunchName'] = item1.label
          dialogForm.value['productLaunchBizId'] = item1.value
        }
        item1.apiAttributeSettingDtoList.forEach(item2 => {
          if (
            item2.attributeSettingBizId == 'attribute_setting_okpcuc8tlXRfVIAy' &&
            item.key == 'issueNumber'
          ) {
            if (item2.value) {
              item.options = item2.value
                .split(/[，,;；\s]+/)
                .map(item => item.trim())
                .filter(item => item !== '')
                .map(item => {
                  return { label: item, value: item }
                })

              if (item.options.length > 0) dialogForm.value[item.key] = item.options[0].value
            }
          }
        })
      })
    })
  }
  if (key == 'productLaunchMainName') {
    father.data.forEach(item => {
      searchOptions.value['productLaunchMainName'].forEach(item1 => {
        if (item1.value == form.value[father.key][key]) {
          form.value[father.key][key] = item1.label
          form.value[father.key]['productLaunchBizId'] = item1.value
        }
        item1.apiAttributeSettingDtoList.forEach(item2 => {
          if (
            item2.attributeSettingBizId == 'attribute_setting_okpcuc8tlXRfVIAy' &&
            item.key == 'issueNumber'
          ) {
            if (item2.value) {
              item.options = item2.value
                .split(/[，,;；\s]+/)
                .map(item => item.trim())
                .filter(item => item !== '')
                .map(item => {
                  return { label: item, value: item }
                })

              if (item.options.length > 0)
                form.value[father.key]['issueNumber'] = item.options[0].value
            }
            console.log(item.options, item, '1111')
          }
        })
      })
    })
  }
  if (key == 'insuranceTypeName') {
    searchOptions.value['insuranceTypeName'].forEach(item => {
      if (item.value == form.value['apiProductPlanMainInfoDto']['insuranceTypeName']) {
        if (item.code == 'CI') {
          resetShow('sumInsured', true)
        } else {
          resetShow('sumInsured', false)
        }
        form.value['apiProductPlanMainInfoDto']['insuranceTypeName'] = item.label
        form.value['apiProductPlanMainInfoDto']['insuranceTypeId'] = item.value
      }
    })
  }
  if (key == 'companyName') {
    dictStore.allInsuranceCompanyList.forEach(item => {
      if (form.value[father.key][key] == item.value) {
        form.value[father.key][key] = item.label
        form.value[father.key].companyId = item.value
      }
    })
  }
}
// 下拉框搜索方法
// 搜索方法
const searchSelectList = async (query, fieldKey) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true

  try {
    // 根据不同的字段key调用不同的API
    if (fieldKey === 'productName') {
      const params = {
        loginTenantBizId: userStore.projectInfo.tenantBizId,
        productName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }

      const response = await getInsuranceProductList(params)
      if (response.code == 200) {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.productName,
            value: item.productBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      }
    }
    // 可以添加其他字段的处理,可以放其他的字段得请求，目前只有accountName，以后有了其他的在填充
    else if (fieldKey === 'productLaunchName' || fieldKey === 'productLaunchMainName') {
      const params = {
        productName: query.trim(),
        pageNo: 1,
        pageSize: 10,
        projectBizId: userStore.projectInfo.projectBizId,
        tenantBizId: userStore.projectInfo.tenantBizId,
        fieldBizId: 'field_olk1qZe81qHHKXbw',
        fieldValueBizId:
          fieldKey === 'productLaunchName'
            ? 'field_value_yXzTigvgUdRMFpoR'
            : 'field_value_uOfJH5ucA2YwJpbn'
      }

      const response = await secondAdditonalList(params)
      if (response.code == 200) {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.title,
            value: item.productLaunchBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      }
    } else if (fieldKey === 'companyName') {
      const params9 = {
        pageNo: 1,
        pageSize: 10,
        queryContent: query.trim()
      }
      const response9 = await getInsuranceCompany(params9)
      if (response9.code == 200) {
        response9.data.records = response9.data.records.map(item => {
          return {
            ...item,
            label: item.fullName,
            value: item.insuranceCompanyBizId
          }
        })
        searchOptions.value[fieldKey] = response9.data.records
      }
    } else if (fieldKey == 'insuranceTypeName') {
      if (!form.value['apiProductPlanMainInfoDto'].companyName) {
        proxy.$modal.confirm(`请先选择保险公司`, {
          showCancel: '0',
          title: '填写提示'
        })
        // row.insuranceType = ''
        return
      }
      const params1 = {
        pageNo: 1,
        pageSize: 10,
        name: query.trim()
      }
      const response1 = await getInsuranceCategory(params1)
      if (response1.code == 200) {
        response1.data.records = response1.data.records.map(item => {
          return {
            ...item,
            label: item.name,
            value: item.insuranceCategoryBizId
          }
        })
        searchOptions.value[fieldKey] = response1.data.records
      }
    }
  } catch (error) {
    console.error(`${fieldKey} 搜索失败`, error)
    searchOptions.value[fieldKey] = []
  } finally {
    searchLoadingStates.value[fieldKey] = false
  }
}

// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        if (dictType == 'sys_no_yes') {
          item.dictItemList.forEach(item1 => {
            item1.value = Number(item1.value)
          })
        }
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
// 处理表单配置，添加字典数据
const processFormData = async () => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(productDomData))

  for (const section of processedData) {
    if (section.fatherRequired) {
      rules.value[section.key] = {}
    }
    //给表单赋值各模块key,对应表单的father.key便于收集值
    if (section.keyType == 'Array') {
      form.value[section.key] = []
    } else if (section.keyType == 'Object') {
      form.value[section.key] = {}
    }
    if (section.formItem) {
      section.formItem.forEach(item => {
        if (item.dictType) {
          item.options = fetchDictData(item.dictType)
        }
      })
    }

    if (section.data) {
      for (const formKey in form.value) {
        if (section.key == formKey) {
          // if (section.dataLength) {
          //   for (let i = 1; i < section.dataLength; i++) {
          //     section.data.push(JSON.parse(JSON.stringify(section.data[0])))
          //   }
          // }
          for (const field of section.data) {
            // 为下拉搜索框加options
            if (field.domType == 'SearchSelect') {
              if (field.key == 'accountName') {
                searchOptions.value[field.key] = dictStore.tenantUserList
              }
            }
            if (section.key == formKey && field.children) {
              for (const child of field.children) {
                if (child.dictType) {
                  child.options = fetchDictData(child.dictType)
                  if (child.dictType == 'bx_currency_type') {
                    currencyType.value = child.options
                  }
                }
              }
            }
            if (field.dictType) {
              // 获取字典数据
              field.options = fetchDictData(field.dictType)
            }
            //
            /*
            1.没有嵌套子级的也就是没有children的数据加rules，根据data中的required字段判断是否必填
            */
            if (field.required) {
              rules.value[section.key][field.key] = [
                { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
              ]
            }
          }
        }
      }
    }
    // 新增的时候需要，修改的时候暂时不需要
    if (!props.idsObj.appointmentBizId) {
      // 切换tab的时侯当在切换回来的时候，依据tempForm.value的值来设置form.value的值
      for (const key in form.value) {
        for (const key2 in tempForm.value) {
          if (key == key2 && isObject(form.value[key])) {
            form.value[key] = tempForm.value[key2]
          }
          if (key == key2 && isArray(form.value[key])) {
            if (tempForm.value[key2].length > 0) {
              if (
                key2 == 'apiProductPlanAdditionalInfoDtoList' &&
                section.key == key2 &&
                key == key2
              ) {
                section.data = form.value[key] = tempForm.value[key2]
              }
            }
          }
        }
      }
    }
  }
  // idsObj.appointmentBizId
  // 证明是修改
  if (props.idsObj.appointmentBizId) {
    //在流程和预约的时候要调用这个方法回显修改数据
    setFormValue(props.apiProductPlanInfoDto, processedData)
  } else {
    if (oldProductDomData.value.length > 0) {
      processedProductData.value = JSON.parse(JSON.stringify(oldProductDomData.value))
    } else {
      processedProductData.value = processedData
    }
  }
}

// 根据联动重置表单项的显示与否
const resetShow = (childKey, status) => {
  console.log(childKey, status)

  for (const section of processedProductData.value) {
    // 暂时没考虑data里嵌套children的情况
    if (section.data && section.data.length > 0) {
      for (const field of section.data) {
        if (field.key == childKey) {
          // 获取字典数据
          field.show = status
        }
      }
    }
  }
}
const handleSelectChange = (father, child) => {
  switch (child.key) {
    case 'employment':
      // 选择吸烟，展示吸烟数量
      if (form.value[father.key][child.key] == 'OTHER') {
        resetShow('otherEmployment', true)
        form.value[father.key]['otherEmployment'] = ''
      } else {
        resetShow('otherEmployment', false)
      }

      break
    case 'isBacktrack':
      // 选是，展示日期
      if (form.value[father.key][child.key] == '1') {
        resetShow('policyEffectiveDate', true)
      } else {
        resetShow('policyEffectiveDate', false)
      }

      break

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = status => {
  editStatus.value = status
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedProductData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        // 改变data中字段得编辑状态
        if (editStatus.value) {
          field.disabled = true
        } else {
          field.disabled = false
        }
        // 改变data中的children字段得编辑状态
        if (field.children) {
          for (const child of field.children) {
            if (editStatus.value) {
              child.disabled = true
            } else {
              child.disabled = false
            }
          }
        }
      }
    }
  }
  processedProductData.value = processedData
}
//给表单赋值 方便表单回显 obj 为表单数据
const setFormValue = (obj, formData) => {
  let newForm = JSON.parse(JSON.stringify(obj))
  // 1.先正确的拿到表单的回显值
  for (const key in newForm) {
    for (const key2 in obj) {
      if (isObject(newForm[key]) && key == key2) {
        newForm[key] = obj[key2]
      }
      if (isArray(newForm[key]) && key == key2 && obj[key2] && obj[key2].length > 0) {
        newForm[key] = obj[key2]
      }
    }
  }
  // 2.根据最新的表单数据更新processedProductData的值,因为有些模块是多项的，所以表单数据要和dom对应上，防止dom有form表单里没有对应的数据会报错
  // 深拷贝原始表单dom数据
  const processedData = JSON.parse(JSON.stringify(formData))
  for (const section of processedData) {
    for (const key in newForm) {
      //回显的数据有的没填写就会是null,收集表单值得时候和dom对应不上，对于null值得项要根据section得keyType给form正确得数据类型
      if (!newForm[key]) {
        if (section.keyType == 'Array') {
          newForm[key] = []
        } else if (section.keyType == 'Object') {
          newForm[key] = {}
        }
      }
      if (section.data) {
        // 为附加险增加dom
        if (
          section.key == 'apiProductPlanAdditionalInfoDtoList' &&
          key == 'apiProductPlanAdditionalInfoDtoList' &&
          newForm[section.key].length > 0
        ) {
          newForm[section.key].forEach(item => {
            item.productLaunchNameValue = item.productLaunchName
          })
          section.data = newForm[section.key]
        }
      }
    }
  }

  form.value = newForm

  processedProductData.value = oldProductDomData.value = processedData
  // 保存一份就得表单数据便于做撤销操作
  oldObjInfo.value = JSON.parse(JSON.stringify(obj))
}

// 获取校验失败的字段信息
const getInvalidFields = fields => {
  const errors = []
  for (const field in fields) {
    if (fields[field] && fields[field].length > 0) {
      errors.push({
        field: field,
        message: `产品计划模块-${fields[field][0].message}`
      })
    }
  }
  return errors
}
// 判断是否为数组
const isArray = value => {
  return Array.isArray(value)
}

// 判断是否为对象
const isObject = value => {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
}
const handleSubmitForm = () => {
  return new Promise(async resolve => {
    if (processedProductData.value.length > 0) {
      proxy.$refs['productFormRef'].validate((valid, fields) => {
        if (valid) {
          errorFields.value = [] // 清空错误信息
          let submitObj = {}
          if (props.activeName == 'productPlan') {
            submitObj = JSON.parse(JSON.stringify(form.value))
          } else {
            submitObj = JSON.parse(JSON.stringify(tempForm.value))
          }
          let resDom = JSON.parse(JSON.stringify(processedProductData.value))

          resDom.forEach(section => {
            if (section.keyType == 'Array' && section.data.length > 0) {
              submitObj[section.key] = JSON.parse(JSON.stringify(section.data))
            }
          })

          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
            return undefined
          }

          resolve(errorFields.value.length == 0 ? submitObj : null)
        } else {
          errorFields.value = getInvalidFields(fields)
          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
          }
          resolve(undefined)
        }
      })
    } else {
      if (props.idsObj.appointmentBizId) {
        resolve(props.apiProductPlanInfoDto)
      } else {
        resolve(undefined)
      }
    }
  })
}

const anchorList = computed(() => {
  let data = []
  for (const section of processedProductData.value) {
    if (section.showMoudle) {
      data.push({ title: section.anchorKey, name: section.fatherTitle })
    }
  }
  return data
})
// 因为tab嵌套了两层，所以需要监听父组件的tab否则锚点的显示就会有bug
watch(
  () => props.fatherTabName,
  newVal => {
    if (newVal) {
      productRef.value = null
    }
  }
)
watch(
  () => props.activeName,
  newVal => {
    productRef.value = null
    tempForm.value = { ...form.value }
    oldProductDomData.value = JSON.parse(JSON.stringify(processedProductData.value))
    if (newVal === 'productPlan') {
      openList.value = false
      processFormData()
    }
  }
)

// 暴露给父组件
defineExpose({
  handleSubmitForm,
  handleEditStatus
})
</script>
<style lang="scss" scoped>
.topBtn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
  }
  .subTitle {
    font-size: 16px;
    padding-left: 8px;
    margin-bottom: 10px;
  }
  .childLabel {
    font-size: 14px;
    margin: 15px 0;
    display: flex;
    align-items: center;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
}
.tabButton {
  /* box-shadow: 0 -1px 14px #00000014; */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
  .sumbitBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 60px;
    background-color: #165dff;
    color: #fff;
    padding: 0 30px;
    .buttonIcon {
      font-size: 16px;
      color: #fff;
    }
  }
}
.customerBox {
  .customerItem {
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 20px;
    box-shadow: 0 -1px 14px #00000014;
    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      .infoItem {
        display: flex;
        align-items: center;
        margin: 5px 0;
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
/* 新增的样式：防止label换行并显示省略号 */
.formFna :deep(.el-checkbox) {
  margin-right: 10px;
}

/* 确保标签对齐方式正确 */
/* :deep(.el-form-item) {
  display: flex;
  align-items: center;
} */

/* :deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
} */
</style>
