<template>
  <!-- 只画好了样式具体的逻辑还没处理 -->
  <div v-if="processedProductData.length > 0">
    <div ref="productRef">
      <CommonForm
        :anchorList="anchorList"
        :affixOffset="360"
        :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)"
                              >
                                <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">
                        <template v-if="father.key == 'apiProductPlanAdditionalInfoDtoList'">
                          <el-table-column label="姓名" prop="realName" align="center" />
                          <el-table-column width="60px" align="center" label="操作">
                            <template #default="scope">
                              <el-icon
                                class="deleteIcon"
                                @click="deleteChildren(father, scope.$index)"
                                ><Delete
                              /></el-icon>
                            </template>
                          </el-table-column>
                        </template>
                      </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"
    >
      <div class="dialogBox">
        <el-form>
          <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="child.value"
                    :placeholder="child.placeholder"
                    maxlength="30"
                  />

                  <el-select
                    v-if="child.domType === 'Select'"
                    v-model="child.value"
                    :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="child.value"
                    type="date"
                    :placeholder="child.placeholder"
                  />
                  <el-select
                    v-model="child.value"
                    v-if="child.domType === 'SearchSelect'"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索"
                    @change="handleSearchSelectChange(child.key, dIndex)"
                    :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
} 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 }, //父组件传递过来的预约的状态
  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 dialogVisible = ref(false)
const productRef = ref(null) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息
// const anchorList = ref([]) // 存储校验失败的字段信息
// const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
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: {},
  tempForm: {}, //由于切换tab的时候，表单数据会重置，所以需要保存一份临时表单数据
  processedProductData: [], // 处理后的表单数据
  oldProductDomData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedProductData, queryParams, oldProductDomData, tempForm } = toRefs(data)
// 添加表单子级dom
const addChildren = father => {
  if (props.editStatus) {
    proxy.$message.warning('请先点击编辑')
    return
  }
  if (father.key == 'apiProductPlanAdditionalInfoDtoList') {
    dialogTitle.value = '新增附加计划'
    additionalProductForm.value = JSON.parse(JSON.stringify(father.formItem))
    dialogVisible.value = true
  }
}
const deleteChildren = (father, childIndex) => {
  if (editStatus.value) {
    proxy.$message.warning('编辑状态下才能删除')
    return
  }
  return
  const processedData = JSON.parse(JSON.stringify(processedProductData.value))
  if (
    props.idsObj.appointmentBizId &&
    form.value[father.key][childIndex].additionalBizId &&
    (props.pageSource == 'appointmentList' || props.pageSource == 'fnaList')
  ) {
    delAdditional(form.value[father.key][childIndex].additionalBizId).then(res => {
      if (res.code == 200) {
        proxy.$message.success('附加险删除成功')
        for (const section of processedData) {
          if (father.key == 'apiProductPlanAdditionalInfoDtoList' && section.key == father.key) {
            section.data.splice(childIndex, 1)
          }
        }
        //更新form表单对应的数据，以便收集填写的值
        form.value[father.key].splice(childIndex, 1)
        emit('handleSuccessEdit')
      }
    })
  } else if (
    props.idsObj.policyBizId &&
    form.value[father.key][childIndex].id &&
    props.pageSource == 'policyList'
  ) {
    delPolicyAdditional(form.value[father.key][childIndex].id).then(res => {
      if (res.code == 200) {
        proxy.$message.success('附加险删除成功')
        for (const section of processedData) {
          if (father.key == 'apiProductPlanAdditionalInfoDtoList' && section.key == father.key) {
            section.data.splice(childIndex, 1)
          }
        }
        //更新form表单对应的数据，以便收集填写的值
        form.value[father.key].splice(childIndex, 1)
        emit('policyEditSuccess')
      }
    })
  } else {
    for (const section of processedData) {
      if (father.key == 'apiProductPlanAdditionalInfoDtoList' && section.key == father.key) {
        section.data.splice(childIndex, 1)
      }
    }
    //更新form表单对应的数据，以便收集填写的值
    form.value[father.key].splice(childIndex, 1)
  }

  processedProductData.value = processedData
}
const handleSearchSelectChange = (key, index) => {
  // 附加计划选择产品后，给供款期数下拉框赋值
  if (key == 'productLaunchName') {
    additionalProductForm.value.forEach(item => {
      searchOptions.value['productLaunchName'].forEach(item1 => {
        if (item1.value == additionalProductForm.value[index]['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) item.value = item.options[0].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') {
      const params = {
        productName: query.trim(),
        pageNo: 1,
        pageSize: 10,
        projectBizId: userStore.projectInfo.projectBizId,
        tenantBizId: userStore.projectInfo.tenantBizId,
        fieldBizId: 'field_olk1qZe81qHHKXbw',
        fieldValueBizId: 'field_value_yXzTigvgUdRMFpoR'
      }

      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
      }
    }
  } 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) {
        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) {
    // anchorList.value.push({ title: section.anchorKey, name: section.fatherTitle })
    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 (props.fnaFormBizId) {
                  child.disabled = true
                } else {
                  child.disabled = false
                }
              }
            }
            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.showSubmitBtn) {
              field.disabled = true
            } else {
              field.disabled = false
            }
          }
        }
      }
    }
    // 新增的时候需要，修改的时候暂时不需要
    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.showSubmitBtn) {
    // editStatus.value = true
    // processedProductData.value = processedData
    //在流程和预约的时候要调用这个方法回显修改数据
    setFormValue(props.apiProductPlanInfoDto, processedData)
  } else {
    // editStatus.value = false
    processedProductData.value = processedData
  }
}

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

  for (const section of processedProductData.value) {
    // 暂时没考虑data里嵌套children的情况
    if (section.data) {
      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表单里没有对应的数据会报错
  let newChildren = {
    //id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    childTitle: '附加险',
    deleteBtn: true,
    children: [
      {
        label: '产品名称',
        key: 'addProductName',
        domType: 'SearchSelect',
        required: true,
        maxLength: 30,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        labelPosition: 'top', //标签的位置
        lg: 8 //栅格布局份数
      },
      {
        label: '保额',
        key: 'sumInsured',
        domType: 'Input',
        inputType: 'number',
        required: true,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '保费',
        key: 'premium',
        domType: 'Input',
        inputType: 'number',
        required: true,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '保障地区',
        key: 'guaranteeRegion',
        domType: 'Input',
        inputType: 'text',
        required: false,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '货币',
        key: 'currency',
        domType: 'Select',
        inputType: 'text',
        required: false,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        dictType: 'bx_currency_type',
        options: fetchDictData('bx_currency_type'),
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },

      {
        label: '等级',
        key: 'insuranceType',
        domType: 'Input',
        inputType: 'text',
        required: false,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '自付额',
        key: 'deductibles',
        domType: 'Input',
        inputType: 'number',
        required: false,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 12, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '附加保障',
        key: 'additionalSafeguards',
        domType: 'Input',
        inputType: 'textarea',
        required: false,
        maxLength: 300,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelPosition: 'top', //标签的位置
        labelWidth: '120px', //标签宽度
        sm: 24, //栅格布局份数
        lg: 24 //栅格布局份数
      }
    ]
  }
  // 深拷贝原始表单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
        ) {
          for (let i = 0; i < newForm[section.key].length; i++) {
            section.data.push(newChildren)
          }
        }
        for (const field of section.data) {
          if (key == 'apiProductPlanMainInfoDto') {
            for (const key2 in newForm[key]) {
              if (field.key == 'policyEffectiveDate' && newForm[key]['isBacktrack'] == '1') {
                field.show = true
              }
            }
          }

          if (section.child == 'yes' && field.children && field.children.length > 0) {
            for (const child of field.children) {
              if (props.showSubmitBtn) {
                child.disabled = true
              } else {
                child.disabled = false
              }
            }
          }
        }
      }
    }
  }

  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 = () => {
  let result = {}
  if (props.activeName == 'productPlan') {
    result = JSON.parse(JSON.stringify(form.value))
  } else {
    result = JSON.parse(JSON.stringify(tempForm.value))
  }
  for (const key in result) {
    if (isObject(result[key])) {
      for (const key2 in result[key]) {
        if (key2 == 'isBacktrack' && result[key][key2] == '0') {
          result[key]['policyEffectiveDate'] = null
        }
        if (key2 == 'policyEffectiveDate' && result[key][key2]) {
          result[key][key2] = proxy.formatToDateTime(result[key][key2])
        }
        for (const section of dictStore.insureProductList) {
          if (key2 == 'productName' && section.productBizId == result[key][key2]) {
            result[key][key2] = section.productName
            result[key]['productBizId'] = section.productBizId
            result[key]['companyName'] = section.ssDeptName
          }
        }
      }
    }
    if (isArray(result[key])) {
      result[key] = result[key]
        .map(item => {
          // 删除指定字段
          delete item.childTitle
          delete item.children
          delete item.disabled
          delete item.id
          delete item.span
          delete item.deleteBtn
          return item
        })
        .filter(item => Object.keys(item).length > 0) // 过滤空对象
    }
    if (key == 'apiProductPlanAdditionalInfoDtoList') {
      if (result[key].length > 0) {
        result[key] = result[key].filter(item => {
          for (const key4 in item) {
            for (const section of dictStore.additionalProductList) {
              if (key4 == 'addProductName' && section.additionalProductBizId == item[key4]) {
                item[key4] = section.productName
                item['additionalProductBizId'] = section.additionalProductBizId
              }
            }
            if (item[key4]) return item
          }
        })
      }
    }
  }
  console.log('新单提交产品计划', result)

  return result
}

// 表单提交
const submitForm = saveType => {
  // return

  proxy.$refs['productFormRef'].validate((valid, fields) => {
    if (valid) {
      let result = handleSubmitForm()

      if (
        props.idsObj.appointmentBizId &&
        (props.pageSource == 'fnaList' || props.pageSource == 'appointmentList')
      ) {
        editProductPlanInfo(result).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('预约-产品计划修改成功')
            emit('handleSuccessEdit')
          }
        })
      }
      if (props.idsObj.policyBizId && props.pageSource == 'policyList') {
        result.policyBizId = props.idsObj.policyBizId
        updatePolicyProduct(result).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('新单跟进-产品计划修改成功')
            emit('policyEditSuccess')
          }
        })
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}
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 }
    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>
