<template>
  <div>
    <div v-if="processedProductData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <!-- v-if="props.idsObj.appointmentBizId" -->
            <el-button
              v-if="props.showSubmitBtn"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus(!editStatus)"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="productFormRef" :model="form" :rules="rules">
        <el-row v-for="father in processedProductData" style="margin-bottom: 10px">
          <div class="formBox formFna">
            <div class="fatherLable">
              <span>{{ father.fatherTitle }}</span>
              <el-button
                style="margin-left: 10px"
                v-if="father.addBtn"
                type="primary"
                icon="Plus"
                @click="addChildren(father)"
                size="small"
                :disabled="editStatus"
                >新增</el-button
              >
            </div>
            <div class="subTitle" v-if="father.subTitle">{{ father.subTitle }}</div>

            <el-row v-if="father.child == 'no'" :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="child.disabled"
                        :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="child.disabled"
                      >
                        <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="child.disabled"
                      />
                      <el-checkbox-group
                        v-if="child.domType === 'Checkbox'"
                        v-model="form[father.key][child.key]"
                        :disabled="child.disabled"
                      >
                        <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="child.disabled"
                        @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>
            <!-- 有子孙的dom -->
            <el-row v-if="father.child == 'yes' && father.data.length > 0" :gutter="20">
              <template v-for="(child, childIndex) in father.data" :key="child.id">
                <el-col :span="child.span">
                  <div
                    class="childLabel"
                    v-if="father.key == 'apiProductPlanAdditionalInfoDtoList'"
                    @click="deleteChildren(father, childIndex)"
                  >
                    <span>{{ `${child.childTitle}-${childIndex + 1}` }}</span>
                    <el-icon
                      v-if="child.deleteBtn"
                      style="color: red; font-size: 18px; margin-left: 10px"
                      ><Delete
                    /></el-icon>
                  </div>
                </el-col>
                <template v-for="grandchildren in child.children" :key="grandchildren.key">
                  <el-col
                    :sm="grandchildren.sm"
                    :lg="grandchildren.lg"
                    class="formItem"
                    v-if="grandchildren.show && form[father.key] && form[father.key][childIndex]"
                  >
                    <el-form-item
                      :label="grandchildren.label"
                      :prop="grandchildren.key"
                      :key="grandchildren.key"
                      :label-width="grandchildren.labelWidth"
                      :label-position="grandchildren.labelPosition"
                    >
                      <el-input
                        v-if="grandchildren.domType === 'Input'"
                        :type="grandchildren.inputType"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        :placeholder="grandchildren.placeholder"
                        maxlength="30"
                        :disabled="grandchildren.disabled"
                      />
                      <!-- 下拉框 -->
                      <el-select
                        v-if="grandchildren.domType === 'Select'"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        :placeholder="grandchildren.placeholder"
                        :disabled="grandchildren.disabled"
                      >
                        <el-option
                          v-for="item in grandchildren.options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-date-picker
                        style="width: 100%"
                        v-if="grandchildren.domType === 'DatePicker'"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        type="date"
                        :placeholder="grandchildren.placeholder"
                        :disabled="grandchildren.disabled"
                      />
                      <!-- 搜索下拉框 -->
                      <el-select
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        v-if="grandchildren.domType === 'SearchSelect'"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词搜索"
                        :remote-method="query => searchSelectList(query, grandchildren.key)"
                        :loading="searchLoadingStates[grandchildren.key]"
                        :disabled="grandchildren.disabled"
                      >
                        <el-option
                          v-for="item in searchOptions[grandchildren.key] || []"
                          :key="item.id"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </template>
              </template>
            </el-row>
          </div>
        </el-row>

        <el-row v-if="props.showSubmitBtn">
          <el-col>
            <div class="tabButton">
              <el-button
                type="success"
                icon="Check"
                @click="submitForm()"
                size="large"
                :disabled="editStatus"
                >保存</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script setup name="customer">
import useDictStore from '@/store/modules/dict'
import productDomData from '@/formJson/productPlan'
import { watch } from 'vue'

import { getInsuranceProductList, getAdditionalProductList } 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 } //父组件传递过来的预约的状态
})
const emit = defineEmits(['handleSuccessEdit', 'policyEditSuccess'])
const { proxy } = getCurrentInstance()
// const { sys_no_yes } = proxy.useDict('sys_no_yes')
const saveKey = ref({}) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const currencyType = ref([]) // 是否列表
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
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)
const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      form.value = { ...oldObjInfo.value }
      editStatus.value = true
      processedProductData.value = JSON.parse(JSON.stringify(oldProductDomData.value))
      proxy.$refs['productFormRef'].resetFields()
    })

    .catch(() => {})
}
const handleSearchSelectChange = (father, child) => {
  let productItem = dictStore.insureProductList.filter(item => {
    return item.value == form.value[father.key][child.key]
  })
  let options = productItem[0].paymentTerm.split(',').map(item => {
    return {
      label: item,
      value: item
    }
  })

  const processedData = JSON.parse(JSON.stringify(processedProductData.value))
  for (const section of processedData) {
    if (section.key == father.key) {
      if (section.data) {
        for (const field of section.data) {
          if (field.dictType && field.dictType == 'paymentTerm') {
            field.options = options
          }
        }
      }
    }
  }
  if (options.length > 0) {
    form.value[father.key]['paymentTerm'] = options[0].value
  }
  processedProductData.value = processedData
}
// 下拉框搜索方法
// 搜索方法
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 === 'addProductName') {
      const params = {
        productName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }

      const response = await getAdditionalProductList(params)
      if (response.code == 200) {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.productName,
            value: item.additionalProductBizId
          }
        })
        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) {
    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.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 && section.child == 'no') {
              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
    //在流程和预约的时候要调用这个方法回显修改数据
    console.log('====================================')
    console.log('props.apiProductPlanInfoDto', props.apiProductPlanInfoDto)
    console.log('====================================')
    setFormValue(props.apiProductPlanInfoDto, processedData)
  } else {
    editStatus.value = false
    processedProductData.value = processedData
  }
}
// 添加表单子级dom
const addChildren = father => {
  if (editStatus.value) {
    proxy.$message.warning('请先点击编辑')
    return
  }
  const processedData = JSON.parse(JSON.stringify(processedProductData.value))
  let obj = {
    // 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 //栅格布局份数
      }
    ]
  }
  for (const section of processedData) {
    if (father.key == 'apiProductPlanAdditionalInfoDtoList' && section.key == father.key) {
      section.data.push(obj)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  form.value[father.key].push(obj)
  processedProductData.value = processedData
}
const deleteChildren = (father, childIndex) => {
  if (editStatus.value) {
    proxy.$message.warning('编辑状态下才能删除')
    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 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)
      }
    }
  })
}

watch(
  () => props.activeName,
  newVal => {
    tempForm.value = { ...form.value }
    if (newVal === 'productPlan') {
      openList.value = false
      setTimeout(() => {
        processFormData()
      }, 500)
    }
  }
)

// 暴露给父组件
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>
