<template>
  <div v-if="processedFanFormData.length > 0" style="padding-top: 10px">
    <div ref="fanContainerRef">
      <div class="editBtn">
        <el-button
          v-if="props.fnaFormBizId && props.tabSource == 'fnaform'"
          type="primary"
          icon="EditPen"
          @click="handleEditStatus"
          >编辑</el-button
        >
      </div>

      <CommonForm
        :anchorList="anchorList"
        :affixOffset="250"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
        :scrollOffset="10"
        :domIndex="tabIndex"
        :activeName="activeName"
        v-if="fanContainerRef"
      >
        <template #form-right>
          <el-form :model="form" :rules="rules" ref="fanFormRef">
            <el-row v-for="(father, fIndex) in processedFanFormData" :id="father.anchorKey">
              <div class="formBox">
                <CardOne :title="father.fatherTitle" v-if="father.showMoudle">
                  <template #mainTitCustom>
                    <div
                      class="dependNum"
                      v-if="
                        father.key == 'dependantList' &&
                        father.data.filter(item => !item.unSave).length > 0
                      "
                    >
                      受供养人数目：{{ father.data.filter(item => !item.unSave).length }}
                    </div>
                  </template>
                  <template #content>
                    <el-row :gutter="20" v-if="!father.showTable" class="selfStyle">
                      <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.key === 'monthlyIncome' && child.domType === 'Input'
                                  ? ''
                                  : child.label
                              "
                              :prop="father.key + '.' + child.key"
                              :rules="
                                child.required
                                  ? [
                                      {
                                        required: true,
                                        message: `${child.label}不能为空`,
                                        trigger: child.domType === 'Select' ? 'change' : 'blur'
                                      }
                                    ]
                                  : undefined
                              "
                              :key="child.key"
                              :label-width="child.labelWidth"
                              :label-position="child.labelPosition"
                            >
                              <!-- 自定义 label 插槽 -->
                              <template
                                v-if="
                                  (child.key === 'monthlyIncome' || child.key === 'liquidAssets') &&
                                  child.domType === 'Input'
                                "
                                #label
                              >
                                <div class="custom-label">
                                  <span>{{ child.label }}</span>
                                  <el-tooltip :content="child.tooltip" placement="top">
                                    <el-icon><QuestionFilled /></el-icon>
                                  </el-tooltip>
                                </div>
                              </template>
                              <el-input
                                v-if="child.domType === 'Input'"
                                :type="child.inputType"
                                v-model="form[father.key][child.key]"
                                :placeholder="child.placeholder"
                                maxlength="30"
                                :disabled="editStatus"
                              >
                                <template #append v-if="child.unit">
                                  <span>{{ child.unit }}</span>
                                </template>
                              </el-input>
                              <el-select
                                v-if="child.domType === 'Select'"
                                v-model="form[father.key][child.key]"
                                :placeholder="child.placeholder"
                                @change="handleSelectChange(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"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                :placeholder="child.placeholder"
                                :disabled="editStatus"
                                :disabled-date="time => disabledDate(time, child)"
                                :default-value="defaultDisplayDate"
                                @change="handleDateChange(child)"
                              />

                              <el-input
                                v-if="child.domType === 'arrowRight'"
                                v-model="form[father.key][child.key]"
                                :placeholder="child.placeholder"
                                @click="handleFoucs(child)"
                                :suffix-icon="ArrowRight"
                                readonly
                                :disabled="editStatus"
                              >
                              </el-input>
                              <el-checkbox-group
                                v-if="child.domType === 'Checkbox'"
                                v-model="form[father.key][child.key]"
                                :disabled="editStatus"
                              >
                                <template class="customCheckBox">
                                  <el-checkbox
                                    v-for="item in child.options"
                                    :key="item.value"
                                    :label="item.value"
                                  >
                                    {{ item.label }}
                                  </el-checkbox>

                                  <el-input
                                    style="width: 250px"
                                    v-if="
                                      child.key === 'liquidAssetType' &&
                                      form[father.key][child.key] &&
                                      form[father.key][child.key].filter(item => item == 'G')
                                        .length > 0
                                    "
                                    v-model="form[father.key]['otherLiquidAsset']"
                                    placeholder="请输入说明"
                                    :disabled="editStatus"
                                  />
                                </template>
                              </el-checkbox-group>
                            </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">
                            <!-- 远程搜索选择框 -->
                            <el-select
                              v-if="column.type === 'remoteSelect'"
                              v-model="scope.row[column.prop]"
                              filterable
                              remote
                              reserve-keyword
                              :placeholder="column.placeholder"
                              :remote-method="
                                query => searchSelectList(query, column.searchType, scope.row)
                              "
                              :loading="searchLoadingStates[column.searchType]"
                              :disabled="editStatus"
                              @change="handleRemoteSelectChange(scope.row, column, father)"
                            >
                              <template v-if="column.searchType !== 'insuranceType'">
                                <el-option
                                  v-for="item in searchOptions[column.searchType] || []"
                                  :key="item.id"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </template>
                              <template v-else>
                                <el-option
                                  v-for="item in scope.row.insuranceTypeOption || []"
                                  :key="item.id"
                                  :label="item.label"
                                  :value="item.value"
                                />
                              </template>
                            </el-select>

                            <!-- 普通选择框 -->
                            <el-select
                              v-else-if="column.type === 'select'"
                              v-model="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                            >
                              <el-option
                                v-for="item in fetchDictData(column.dictType)"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>

                            <!-- 日期选择器 -->
                            <el-date-picker
                              v-else-if="column.type === 'datePicker'"
                              v-model="scope.row[column.prop]"
                              type="date"
                              format="YYYY-MM-DD"
                              value-format="YYYY-MM-DD"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                              style="width: 100%"
                            />

                            <!-- 数字输入框 -->
                            <el-input
                              v-else-if="
                                column.type === 'inputNumber' && !!scope.row.showSumInsured
                              "
                              v-model.number="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                              type="number"
                            >
                              <template v-if="column.unit" #append>
                                <span>{{ column.unit }}</span>
                              </template>
                            </el-input>
                            <el-input
                              v-else-if="column.type === 'inputNumber' && scope.row.showSumInsured"
                              v-model.number="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                              type="number"
                            >
                              <template v-if="column.unit" #append>
                                <span>{{ column.unit }}</span>
                              </template>
                            </el-input>
                            <!-- 普通输入框（默认） -->
                            <el-input
                              v-else-if="column.prop !== 'sumInsured'"
                              v-model="scope.row[column.prop]"
                              :placeholder="column.placeholder"
                              :disabled="editStatus"
                            />
                          </template>
                        </el-table-column>

                        <!-- 操作列（固定） -->
                        <el-table-column
                          :width="father.key == 'dependantList' ? 150 : 80"
                          align="center"
                          label="操作"
                        >
                          <template #default="scope">
                            <el-button
                              type="primary"
                              size="small"
                              v-if="father.key == 'dependantList'"
                              @click="saveTableData(father, scope.row)"
                            >
                              {{ scope.row.unSave ? '未保存' : '已保存' }}
                            </el-button>
                            <el-button
                              type="danger"
                              size="small"
                              @click="deleteChildren(father, scope.$index)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-row>
                  </template>
                </CardOne>
              </div>
            </el-row>
            <el-row>
              <el-col>
                <div class="tabButton">
                  <el-button
                    type="primary"
                    icon="RefreshRight"
                    size="large"
                    @click="submitForm('temp')"
                    :disabled="editStatus"
                    >暂存</el-button
                  >
                  <el-button
                    type="success"
                    icon="Check"
                    @click="submitForm('save')"
                    size="large"
                    :disabled="editStatus"
                    >保存,去填写预约单</el-button
                  >
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </CommonForm>
    </div>
    <!-- <div v-else class="domEmpty" v-loading="loading"></div> -->
  </div>
</template>
<script setup name="fanForm">
import CommonForm from '@/views/components/commonForm'
import CardOne from '@/components/formCard/cardOne'
import { processUserName } from '@/utils/common'
import useDictStore from '@/store/modules/dict'
import fanFormDomData from '@/formJson/fnaForm'
import { watch, nextTick } from 'vue'
import { addfanForm, getfanFormDetail, editFanForm, getCustomerList } from '@/api/sign/fna'
import {
  getUserSaleExpandList,
  getAllTeam,
  getInsuranceCompany,
  getInsuranceCategory
} from '@/api/common'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  customerInfo: { type: Object, default: () => {} }, //客户详情
  activeName: { type: String, default: '' }, //tab名称

  fnaFormBizId: { type: String, default: '' }, //提交状态，新增、修改
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  dictTypeLists: { type: Array, default: () => [] }, //多个字典值数据
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  tabIndex: { type: [String, Number], default: '' }, //tab索引
  tabSource: { type: String, default: '' } //引用这个组件的页面来源，用于逻辑判断
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
const fanContainerRef = ref(null)
const loading = ref(false)
const fanFormRef = ref(null)
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const noYesList = ref([]) // 是否列表
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const data = reactive({
  form: {},
  processedFanFormData: [], // 处理后的表单数据
  tempFanFormValue: {}, // 切换tab得时候保存临时填写得值
  tempFanFormData: [], // 处理后的表单数据
  oldFanFormData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const {
  form,
  rules,
  processedFanFormData,
  queryParams,
  oldFanFormData,
  tempFanFormValue,
  tempFanFormData
} = toRefs(data)
const handleRemoteSelectChange = async (row, column, father) => {
  console.log(row, column)
  // 通过保险公司查保险种类 row中收集了insurer的值
  if (column.prop == 'insurer') {
    const params1 = {
      pageNo: 1,
      pageSize: 10
    }
    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
        }
      })
      row.insuranceTypeOption = response1.data.records
    }
  }
  if (column.prop == 'insuranceType' && row.insuranceType) {
    //如果险种选择了重疾险，则显示重疾险的输入框
    row.insuranceTypeOption.forEach(item => {
      if (item.value == row.insuranceType) {
        row.sumInsured = ''
        if (item.code == 'CATEGORY5934890141') {
          row.showSumInsured = true
        } else {
          row.showSumInsured = false
        }
        row.insuranceType = item.label
        row.insuranceCategoryBizId = item.code
      }
    })
  }
}
// 搜索方法
const searchSelectList = async (query, fieldKey, row) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true
  let queryString = query.trim()
  try {
    // 根据不同的字段key调用不同的API
    if (fieldKey === 'brokerName') {
      const params5 = {
        pageNo: 1,
        pageSize: 10,
        queryContent: queryString
      }
      const response5 = await getUserSaleExpandList(params5)
      if (response5.code == 200) {
        response5.data.records = response5.data.records.map(item => {
          return {
            ...item,
            label: item.realName,
            value: item.userSaleBizId
          }
        })
        searchOptions.value[fieldKey] = response5.data.records
      }
    } else if (fieldKey === 'brokerTeam') {
      const params8 = {
        pageNo: 1,
        pageSize: 10,
        teamName: queryString
      }
      const response8 = await getAllTeam(params8)
      if (response8.code == 200) {
        response8.data.records = response8.data.records.map(item => {
          return {
            ...item,
            label: item.teamName,
            value: item.teamBizId
          }
        })
        searchOptions.value[fieldKey] = response8.data.records
      }
    } else if (fieldKey === 'insurer') {
      const params9 = {
        pageNo: 1,
        pageSize: 10,
        queryContent: queryString
      }
      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 == 'insuranceType') {
      if (!row.insurer) {
        proxy.$modal.confirm(`请先选择保险公司`, {
          showCancel: '0',
          title: '填写提示'
        })
        row.insuranceType = ''
        return
      }
      const params1 = {
        pageNo: 1,
        pageSize: 10,
        name: queryString
      }
      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
          }
        })
        row.insuranceTypeOption = response1.data.records
      }
    }
  } catch (error) {
    console.error(`${fieldKey} 搜索失败`, error)
    searchOptions.value[fieldKey] = []
  } finally {
    searchLoadingStates.value[fieldKey] = false
  }
}

const disabledDate = time => {
  return time.getTime() > Date.now()
}

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

  for (const section of processedData) {
    if (section.fatherRequired) {
      rules.value[section.key] = {}
    }
    //给表单赋值各模块key,对应表单的father.key便于收集值
    if (section.keyType == 'Object') {
      form.value[section.key] = {}
    }
    if (section.data) {
      for (const field of section.data) {
        if (field.customerKey) {
          for (const cKey in props.customerInfo) {
            if (cKey == field.customerKey && !props.fnaFormBizId) {
              form.value[section.key][field.key] = props.customerInfo[cKey]
            }
          }
        }
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
      }
    }
  }
  if (props.fnaFormBizId) {
    getFanformInfo(props.fnaFormBizId, processedData)
    editStatus.value = true
  } else {
    // tab切走在切回来时，表单会重置，所以这里需要把表单的值赋回去
    if (Object.keys(tempFanFormValue.value).length > 0) {
      form.value = JSON.parse(JSON.stringify(tempFanFormValue.value))
    }
    if (tempFanFormData.value.length > 0) {
      processedFanFormData.value = oldFanFormData.value = JSON.parse(
        JSON.stringify(tempFanFormData.value)
      )
    } else {
      processedFanFormData.value = oldFanFormData.value = processedData
    }
    editStatus.value = false
    loading.value = false
  }
  processedFanFormData.value = oldFanFormData.value = processedData
  console.log('====================================')
  console.log('新增', form.value)
  console.log('====================================')
}
// 添加表单子级dom
const addChildren = father => {
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  let obj1 = {
    brokerName: '',
    brokerGender: '',
    brokerNumber: '',
    brokerTeam: '',
    brokerRatio: '',
    remark: ''
  }
  let obj2 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    policyholderRel: '',
    dependantAge: '',
    unSave: true //新增受供养人的时候是未保存状态
  }
  let obj3 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    insurer: '',
    insuranceType: '',
    currency: '',
    policyIssueDate: '',
    showSumInsured: false //重疾险显示保额输入框
  }
  let obj4 = {
    propertyType: '',
    address: '',
    marketValue: '',
    currency: ''
  }

  for (const section of processedData) {
    if (father.key == 'brokerList' && section.key == father.key) {
      section.data.push(obj1)
    }
    if (father.key == 'dependantList' && section.key == father.key) {
      if (father.data.length == 0 || father.data.filter(item => item.unSave).length == 0) {
        section.data.push(obj2)
      } else if (father.data.filter(item => item.unSave).length > 0) {
        proxy.$modal.confirm(`请先保存‘新增的受供养人’信息再添加`, {
          showCancel: '0',
          title: '填写提示'
        })
      }
    }
    if (father.key == 'existingSecurityOwner' && section.key == father.key) {
      section.data.push(obj3)
    }
    if (father.key == 'primaryResidence' && section.key == father.key) {
      section.data.push(obj4)
    }
  }
  processedFanFormData.value = processedData
}

const deleteChildren = (father, childIndex) => {
  if (editStatus.value) {
    proxy.$modal.confirm(`请先点击编辑再进行删除操作`, { showCancel: '0', title: '填写提示' })
    return
  }
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  for (const section of processedData) {
    if (father.key == 'brokerList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (father.key == 'dependantList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (father.key == 'existingSecurityOwner' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (father.key == 'primaryResidence' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
  }
  processedFanFormData.value = processedData
}
// 保存表格数据
const saveTableData = (father, row) => {
  if (father.key == 'dependantList') {
    console.log(!row.policyholderRel && !row.dependantAge)

    if (!row.policyholderRel && !row.dependantAge) {
      proxy.$modal.confirm(`请先填写受供养人信息再保存`, { showCancel: '0', title: '填写提示' })
      return
    }
    row.unSave = false
  }
}
const resetShow = (childKey, status) => {
  console.log(childKey, status)

  for (const section of processedFanFormData.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

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = () => {
  editStatus.value = !editStatus.value
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.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
            }
          }
        }
      }
    }
  }
  processedFanFormData.value = processedData
}
//给表单赋值 方便表单回显 obj 为表单数据
const setFormValue = (obj, formData) => {
  console.log('回显值', obj)

  loading.value = true
  let processedData = JSON.parse(JSON.stringify(formData))
  // 重疾险要加上row.showSumInsured = true便于控制重疾险保额输入框的显示
  for (const section of processedData) {
    if (section.keyType == 'Array') {
      if (section.key == 'existingSecurityOwner' && obj[section.key]) {
        obj[section.key].forEach(item => {
          if (item.insuranceCategoryBizId == 'CATEGORY5934890141') {
            item.showSumInsured = true
          }
        })
      }
      section.data = obj[section.key] ? obj[section.key] : []
    } else if (section.keyType == 'Object') {
      obj[section.key].premiumFundingSource = obj[section.key].premiumFundingSource
        ? obj[section.key].premiumFundingSource.split(',')
        : []
      obj[section.key].liquidAssetType = obj[section.key].liquidAssetType
        ? obj[section.key].liquidAssetType.split(',')
        : []
      form.value[section.key] = obj[section.key]
    }
  }

  processedFanFormData.value = processedData
  loading.value = false
  nextTick(() => {
    fanFormRef.value.clearValidate()
  })
}

// 获取校验失败的字段信息
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 submitForm = saveType => {
  let oldForm = JSON.parse(JSON.stringify(form.value))
  // 深拷贝原始数据
  let resDom = JSON.parse(JSON.stringify(processedFanFormData.value))
  let result = {}
  // return

  proxy.$refs['fanFormRef'].validate((valid, fields) => {
    if (valid) {
      for (const section of resDom) {
        if (section.keyType == 'Array' && section.data.length > 0) {
          section.data.forEach(item => {
            if (item.brokerName) {
              dictStore.userSaleExpandList.forEach(item2 => {
                if (item2.value == item.brokerName) {
                  item.brokerName = item2.label
                }
              })
            }
            if (item.brokerTeam) {
              dictStore.allTeaList.forEach(item2 => {
                if (item2.value == item.brokerTeam) {
                  item.brokerTeam = item2.label
                }
              })
            }
            if (item.insurer) {
              dictStore.allInsuranceCompanyList.forEach(item2 => {
                if (item2.value == item.insurer) {
                  item.insurer = item2.label
                }
              })
            }
            // if (item.insuranceType) {
            //   item.insuranceTypeOption.forEach(item2 => {
            //     if (item2.value == item.insuranceType) {
            //       item.insuranceType = item2.label
            //     }
            //   })
            // }
          })
          result[section.key] = section.data
        }
      }
      result.premiumAffordability = JSON.parse(JSON.stringify(form.value.premiumAffordability))

      result.premiumAffordability.liquidAssetType =
        result.premiumAffordability.liquidAssetType.join(',')
      result.premiumAffordability.premiumFundingSource =
        result.premiumAffordability.premiumFundingSource.join(',')
      if (result.premiumAffordability.liquidAssetType.includes('G')) {
        result.premiumAffordability.otherLiquidAsset = oldForm.premiumAffordability.otherLiquidAsset
      }
      result.saveType = saveType
      result.customerBizId = props.customerBizId
      console.log('====================================')
      console.log('提交的数据', result)
      console.log('====================================')
      // return
      if (props.fnaFormBizId) {
        result.fnaFormBizId = props.fnaFormBizId
        editFanForm(result).then(res => {
          if (res.code == 200) {
            handleEditStatus()
            proxy.$message.success('fanForm修改成功')
            emit('handleSuccess', {
              tab: 'fnaform',
              fnaFormBizId: props.fnaFormBizId,
              type: 'edit'
            })
          }
        })
      } else {
        addfanForm(result).then(res => {
          if (res.code == 200) {
            proxy.$message.success('fnaForm新增成功')
            emit('handleSuccess', {
              tab: 'fnaform',
              fnaFormBizId: res.data.fnaFormBizId,
              type: 'add'
            })
          }
        })
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}

// 获取流程详情
function getFanformInfo(fnaFormBizId, formData) {
  getfanFormDetail(fnaFormBizId).then(async res => {
    if (res.code == 200) {
      // 回显值
      setFormValue(res.data, formData)
    }
  })
}
const anchorList = computed(() => {
  let data = []
  for (const section of processedFanFormData.value) {
    if (section.showMoudle) {
      data.push({ title: section.anchorKey, name: section.fatherTitle })
    }
  }
  return data
})
watch(fanFormRef, newVal => {
  if (newVal) {
    for (const key in rules.value) {
      for (const key2 in rules.value[key]) {
        fanFormRef.value.clearValidate(key2)
      }
    }
  }
})
watch(
  () => props.activeName,
  newVal => {
    fanContainerRef.value = null
    tempFanFormValue.value = JSON.parse(JSON.stringify(form.value))
    tempFanFormData.value = JSON.parse(JSON.stringify(processedFanFormData.value))
    if (newVal === 'fnaform') {
      openList.value = false
      processFormData()
    }
  }
)
</script>
<style lang="scss" scoped>
.editBtn {
  position: fixed;
  right: 3.5%;
  top: 22%;
  z-index: 999;
}
.dependNum {
  font-size: 14px;
  font-weight: none;
  margin-left: 10px;
}
.customCheckBox {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.domEmpty {
  width: 100%;

  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #a8abb2;
  margin-top: 100px;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.fatherLable {
  font-size: 18px;
  border-left: 4px solid #165dff;
  padding-left: 5px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  .openCon {
    margin-left: 10px;
    cursor: pointer;
  }
}
.subTitle {
  font-size: 15px;
  /* padding-left: 8px; */
  margin-bottom: 10px;
}
.deleteIcon {
  color: red;
  font-size: 18px;
  padding-top: 10px;
}
.formBox {
  width: 100%;
  .childLabel {
    font-size: 14px;
    /* padding-left: 15px; */
    margin-bottom: 15px;
  }
  .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;
}
.selfStyle :deep(.el-form-item--label-top .el-form-item__label) {
  text-align: none !important;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* @media only screen and (min-width: 768px) {
  .formInput {
    margin-top: 30px !important;
  }
}

@media only screen and (min-width: 1200px) {
  .formInput {
    margin-top: 30px !important;
  }
} */
</style>
