<template>
  <div>
    <div v-if="processedFanFormData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button
              v-if="props.fnaFormBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="fanFormRef" :model="form" :rules="rules">
        <div v-for="father in processedFanFormData">
          <div>
            <div class="fatherLable">
              {{ father.fatherTitle }}
              <div class="openCon" v-if="father.openIcon" @click="changeOpenStatus(father)">
                <el-icon v-if="!father.isOpen"><Hide /></el-icon>
                <el-icon v-else><View /></el-icon>
              </div>
            </div>
            <div class="subTitle" v-if="father.subTitle && father.isOpen">
              {{ father.subTitle }}
            </div>
          </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-input
                      v-if="child.inputType === '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%' }"
                      class="formInput"
                    />
                    <el-select
                      v-if="child.domType === 'Select'"
                      v-model="form[father.key][child.key]"
                      :placeholder="child.placeholder"
                      @change="handleSelectChange(father, child)"
                      :disabled="child.disabled"
                      clearable
                    >
                      <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"
                      @change="changeCheck(father, child)"
                    >
                      <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"
                      clearable
                    >
                      <el-option
                        v-for="item in searchOptions[child.key] || []"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </template>
          </el-row>
          <el-row v-if="father.showTable && father.isOpen">
            <el-table :data="father.data" border>
              <template v-if="father.key == 'familyMembers'">
                <el-table-column label="亲属" prop="childTitle" width="100px" align="center">
                  <template #default="scope">
                    {{
                      scope.row.type == '4'
                        ? `${scope.row.childTitle}-${scope.$index - 2}`
                        : scope.row.childTitle
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="年龄" prop="age" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.age"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="是否需要供养" prop="needProvide" align="center">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.needProvide"
                      placeholder="请选择"
                      :disabled="editStatus"
                      clearable
                    >
                      <el-option
                        v-for="item in scope.row.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  width="60px"
                  v-if="father.data && father.data.some(item => item.type === '4')"
                  align="center"
                  label="操作"
                >
                  <template #default="scope">
                    <el-icon
                      v-if="scope.row.type == '4'"
                      @click="deleteChildren(father, scope.$index)"
                      class="deleteIcon"
                      ><Delete
                    /></el-icon>
                  </template>
                </el-table-column>
              </template>
              <template
                v-if="
                  father.key == 'existingSecurityOwner' || father.key == 'existingSecurityInsured'
                "
              >
                <el-table-column label="保险公司" prop="insurer" align="center">
                  <template #default="scope">
                    <el-input
                      size="default"
                      placeholder="请输入"
                      v-model="scope.row.insurer"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="保障类型" prop="insuranceType" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.insuranceType"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="保额" prop="sumInsured" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.sumInsured"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>

                <el-table-column label="币种" prop="currency" align="center">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.currency"
                      placeholder="请选择"
                      :disabled="editStatus"
                      clearable
                    >
                      <el-option
                        v-for="item in scope.row.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="保单签发日期" prop="policyIssueDate" align="center">
                  <template #default="scope">
                    <el-date-picker
                      style="width: 100%"
                      v-model="scope.row.policyIssueDate"
                      type="date"
                      placeholder="请输入"
                      :disabled="editStatus"
                      :disabled-date="disabledDate"
                    />
                  </template>
                </el-table-column>
                <el-table-column width="60px" align="center" label="操作">
                  <template #default="scope">
                    <el-icon @click="deleteChildren(father, scope.$index)" class="deleteIcon"
                      ><Delete
                    /></el-icon>
                  </template>
                </el-table-column>
              </template>
              <template v-if="father.key == 'investment'">
                <el-table-column label="地址" prop="address" align="center">
                  <template #default="scope">
                    <el-input
                      size="default"
                      placeholder="请输入"
                      v-model="scope.row.address"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="市值" prop="marketValue" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.marketValue"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="币种" prop="currency" align="center">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.currency"
                      placeholder="请选择"
                      :disabled="editStatus"
                      clearable
                    >
                      <el-option
                        v-for="item in scope.row.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column width="60px" align="center" label="操作">
                  <template #default="scope">
                    <el-icon @click="deleteChildren(father, scope.$index)" class="deleteIcon"
                      ><Delete
                    /></el-icon>
                  </template>
                </el-table-column>
              </template>

              <template v-if="father.key == 'primaryResidence'">
                <el-table-column label="自住用途之房地产地址" prop="address" align="center">
                  <template #default="scope">
                    <el-input
                      size="default"
                      placeholder="请输入"
                      v-model="scope.row.address"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="自住用途之房地产市值" prop="marketValue" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.marketValue"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="币种" prop="currency" align="center">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.currency"
                      placeholder="请选择"
                      :disabled="editStatus"
                      clearable
                    >
                      <el-option
                        v-for="item in scope.row.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column width="60px" align="center" label="操作">
                  <template #default="scope">
                    <el-icon @click="deleteChildren(father, scope.$index)" class="deleteIcon"
                      ><Delete
                    /></el-icon>
                  </template>
                </el-table-column>
              </template>
              <template v-if="father.key == 'taxList'">
                <el-table-column label="税务国家" prop="taxCountry" align="center">
                  <template #default="scope">
                    <el-input
                      size="default"
                      placeholder="请输入"
                      v-model="scope.row.taxCountry"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="税务编号" prop="taxNumber" align="center">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.taxNumber"
                      size="default"
                      placeholder="请输入"
                      :disabled="editStatus"
                    />
                  </template>
                </el-table-column>
                <el-table-column width="60px" align="center" label="操作">
                  <template #default="scope">
                    <el-icon @click="deleteChildren(father, scope.$index)" class="deleteIcon"
                      ><Delete
                    /></el-icon>
                  </template>
                </el-table-column>
              </template>
            </el-table>
            <el-col
              :span="24"
              v-if="father.addChildren"
              style="display: flex; justify-content: center"
            >
              <el-button
                :disabled="editStatus"
                style="margin-top: 10px"
                type="primary"
                icon="Plus"
                @click="addChildren(father)"
                >{{ father.addChildrenTxt }}</el-button
              >
            </el-col>
          </el-row>
        </div>

        <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>
    </div>
    <div v-else class="domEmpty" v-loading="loading"></div>
  </div>
</template>
<script setup name="fanForm">
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 { listTenantUser } 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名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  fnaFormBizId: { type: String, default: '' }, //提交状态，新增、修改
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  dictTypeLists: { type: Array, default: () => [] } //多个字典值数据
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
// const { sys_no_yes } = proxy.useDict('sys_no_yes')
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 changeCheck = (father, child) => {
  if (child.key == 'liquidAssetType') {
    resetShow('otherLiquidAsset', form.value[father.key][child.key].includes('G'))
  }
}
const changeOpenStatus = father => {
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  for (const section of processedData) {
    if (
      father.key == 'familyMembers' &&
      section.key == father.key &&
      section.moudleType == 'family'
    ) {
      section.isOpen = !father.isOpen
    }
    if (section.moudleType == 'finance' && father.key !== 'familyMembers') {
      section.isOpen = !father.isOpen
    }
  }
  processedFanFormData.value = processedData
  console.log('processedFanFormData.value', processedFanFormData.value)
}
const disabledDate = time => {
  return time.getTime() > Date.now()
}
// 搜索方法
const searchSelectList = async (query, fieldKey) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true

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

      const response = await listTenantUser(params)
      if (response.code == 200) {
        let result = processUserName(response.data.records)
        result = result.map(item => {
          return {
            value: item.userBizId,
            label: item.showName
          }
        })
        searchOptions.value[fieldKey] = result
      }
    }
    // 可以添加其他字段的处理,可以放其他的字段得请求，目前只有accountName，以后有了其他的在填充
    else if (fieldKey === 'otherField') {
      console.log('otherField')
    }
  } 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 == '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 == 'Array') {
      form.value[section.key] = []
      if (section.key == 'familyMembers') {
        form.value[section.key] = section.data
      }
    } 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])))
              form.value[formKey].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 == 'sys_no_yes') {
                    noYesList.value = child.options
                  }
                }
                if (props.fnaFormBizId) {
                  child.disabled = true
                } else {
                  child.disabled = false
                }
              }
            }
            if (field.dictType) {
              // 获取字典数据
              field.options = fetchDictData(field.dictType)
              if (field.dictType == 'sys_no_yes') {
                noYesList.value = field.options
              }
            }
            //
            /*
            1.没有嵌套子级的也就是没有children的数据加rules，根据data中的required字段判断是否必填
            2.有嵌套子级的也就是有children的数据，根据children中的required字段判断是否必填，现在没这个需求，所以先注释
            */
            if (field.required && section.child == 'no') {
              rules.value[section.key][field.key] = [
                { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
              ]
            }
            if (props.fnaFormBizId) {
              field.disabled = true
            } else {
              if (field.key == 'customerName' && section.key == 'personalData') {
                form.value['personalData'][field.key] = props.customerInfo.firstNamePinyin
              }
              field.disabled = false
            }
          }
          if (section.child == 'yes') {
            form.value[formKey] = section.data //便于表单收集值
          }
        }
      }
    }
  }
  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
  }
}
// 添加表单子级dom
const addChildren = father => {
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  let obj = {
    type: '4',
    childTitle: '儿女',
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    delete: true, //是否显示删除按钮
    age: '',
    needProvide: '',
    options: noYesList.value
  }
  let obj2 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    insurer: '',
    insuranceType: '',
    sumInsured: '',
    policyIssueDate: '',
    currency: '',
    options: fetchDictData('bx_currency_type')
  }
  let obj3 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    address: '',
    currency: '',
    marketValue: '',
    options: fetchDictData('bx_currency_type')
  }
  let obj4 = {
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    span: 24, //栅格布局份数
    taxCountry: '',
    taxNumber: ''
  }

  for (const section of processedData) {
    if (father.key == 'familyMembers' && section.key == father.key) {
      section.data.push(obj)
    }
    if (father.key == 'existingSecurityOwner' && section.key == father.key) {
      section.data.push(obj2)
    }
    if (father.key == 'existingSecurityInsured' && section.key == father.key) {
      section.data.push(obj2)
    }
    if (father.key == 'investment' && section.key == father.key) {
      section.data.push(obj3)
    }
    if (father.key == 'primaryResidence' && section.key == father.key) {
      section.data.push(obj3)
    }
    if (father.key == 'taxList' && section.key == father.key) {
      section.data.push(obj4)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  form.value[father.key].push(obj)
  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 == 'familyMembers' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (father.key == 'taxList' && section.key == father.key) {
      section.data.splice(childIndex, 1)
    }
    if (
      (father.key == 'existingSecurityOwner' || father.key == 'existingSecurityInsured') &&
      section.key == father.key
    ) {
      section.data.splice(childIndex, 1)
    }
    if (
      (father.key == 'investment' || father.key == 'primaryResidence') &&
      section.key == father.key
    ) {
      section.data.splice(childIndex, 1)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  form.value[father.key].splice(childIndex, 1)

  processedFanFormData.value = processedData
}
// 根据联动重置表单项的显示与否
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) => {
  loading.value = true

  let newForm = JSON.parse(JSON.stringify(form.value))
  // 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.根据最新的表单数据更新processedFanFormData的值,因为有些模块是多项的，所以表单数据要和dom对应上，防止dom有form表单里没有对应的数据会报错
  let newChildren = {
    type: '4',
    childTitle: '儿女',
    delete: true, //是否显示删除按钮
    age: '',
    needProvide: '',
    options: noYesList.value
  }
  // 深拷贝原始表单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' && key == section.key) {
          newForm[key] = []
        } else if (section.keyType == 'Object' && key == section.key) {
          newForm[key] = {}
        }
      }
      if (section.data) {
        if (section.key == 'familyMembers' && section.key == key) {
          // 根据家人得type对应，如果填写得有儿女processedFanFormData和form应该加上对应得值
          newForm[key].forEach((item, index) => {
            // 儿女特殊处理，因为可能有多个儿女为了区分是哪个儿女，所以加上id
            if (item.type == '4') {
              item.id = index + 1
              section.data.push({ id: index + 1, ...newChildren })
              form.value[key].push({ id: index + 1, ...newChildren })
            }
          })
        } else if (key !== 'familyMembers' && section.key == key) {
          if (isArray(newForm[key]) && newForm[key].length <= section.dataLength) {
            let num = section.dataLength - newForm[key].length
            for (let i = 0; i < num; i++) {
              newForm[key].push(section.data[0])
            }
          }
        }

        if (section.key == 'personalData' && key == section.key) {
          if (isObject(newForm[key])) {
            for (const key2 in newForm[key]) {
              // 如果就业情况为其他，显示其他就业情况
              if (key2 == 'employment' && newForm[key][key2] == 'OTHER') {
                for (const item of section.data) {
                  if (item.key == 'otherEmployment') {
                    item.show = true
                  }
                }
              }
            }
          }
        }

      }
    }
  }
  // 回显表单值特殊处理
  for (const key in form.value) {
    for (const key2 in newForm) {
      if (key == key2 && key == 'familyMembers') {
        if (newForm[key2].length > 0) {
          form.value[key] = form.value[key].map(item1 => {
            newForm[key2].forEach(item2 => {
              if (item1.type == '4' && item1.id == item2.id) {
                item1.age = item2.age
                item1.needProvide = item2.needProvide
              } else {
                if (item1.type == item2.type && !item2.id) {
                  item1.age = item2.age
                  item1.needProvide = item2.needProvide
                }
              }
            })
            return item1
          })
        }
      } else if (key == key2 && key !== 'familyMembers') {
        if (isArray(newForm[key2]) && newForm[key].length > 0) {
          form.value[key] = newForm[key2]
        } else if (isObject(newForm[key2])) {
          for (const key3 in newForm[key2]) {
            if (!newForm[key2][key3]) {
              if (key3 == 'premiumFundingSource' || key3 == 'liquidAssetType') {
                newForm[key2][key3] = []
              } else {
                newForm[key2][key3] = ''
              }
            } else {
              if (key3 == 'premiumFundingSource' || key3 == 'liquidAssetType') {
                newForm[key2][key3] = newForm[key2][key3].split(',')
              }
            }
          }
          form.value[key] = newForm[key2]
        }
      }
    }
  }
  for (const section of processedData) {
    for (const key1 in obj) {
      if (section.data) {
        if (
          obj[key1] &&
          key1 !== 'familyMembers' &&
          key1 == section.key &&
          section.keyType == 'Array'
        ) {
          section.data = obj[key1].map(item => {
            for (const key2 in item) {
              if (key2 == 'currency') {
                item.options = fetchDictData('bx_currency_type')
              } else if (key2 == 'needProvide') {
                item.options = fetchDictData('sys_no_yes')
              }
            }
            return {
              ...item
            }
          })
        } else if (
          key1 == 'familyMembers' &&
          key1 == section.key &&
          section.keyType == 'Array' &&
          obj[key1]
        ) {
          section.data = form.value[key1].map(item => {
            for (const key2 in item) {
              if (key2 == 'needProvide') {
                item.options = fetchDictData('sys_no_yes')
              }
            }
            return {
              ...item
            }
          })
        }
        // 流动资产包含其他的时候，显示其他说明
        if (section.key == 'liquidAssets') {
          for (const field of section.data) {
            if (
              field.key == 'otherLiquidAsset' &&
              obj[section.key]['liquidAssetType'] &&
              obj[section.key]['liquidAssetType'].includes('G')
            ) {
              field.show = true
            }
          }
        }
      }
    }
  }

  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 result = JSON.parse(JSON.stringify(form.value))
  let resDom = JSON.parse(JSON.stringify(processedFanFormData.value))
  console.log('result', result)

  // return

  proxy.$refs['fanFormRef'].validate((valid, fields) => {
    if (valid) {
      for (const section of resDom) {
        for (const key1 in result) {
          // key1 !== 'familyMembers' &&
          if (section.key == key1 && section.keyType == 'Array') {
            result[key1] = section.data
          }
        }
      }
      for (const key in result) {
        if (isObject(result[key])) {
          for (const key2 in result[key]) {
            if (isArray(result[key][key2])) {
              if (
                key == 'liquidAssets' &&
                key2 == 'liquidAssetType' &&
                !result[key][key2].includes('G')
              ) {
                result[key]['otherLiquidAsset'] = ''
              }
              result[key][key2] = result[key][key2].join(',')
            }
          }
        }
        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.dictType
              delete item.options
              delete item.delete
              delete item.subTitle
              if (item.policyIssueDate) {
                item.policyIssueDate = proxy.formatToDate(item.policyIssueDate)
              }
              return item
            })
            .filter(item => Object.keys(item).length > 0) // 过滤空对象
        }
        if (key == 'familyMembers') {
          result[key] = result[key].filter(item => {
            if (item.age || item.needProvide) return item
          })
        }
      }
      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)
    }
  })
}
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 => {
    tempFanFormValue.value = JSON.parse(JSON.stringify(form.value))
    tempFanFormData.value = JSON.parse(JSON.stringify(processedFanFormData.value))
    if (newVal === 'fnaform') {
      openList.value = false
      setTimeout(() => {
        processFormData()
      }, 500)
    }
  }
)
</script>
<style lang="scss" scoped>
.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;
}

/* @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>
