<template>
  <div>
    <div v-if="processedCustomerData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button type="warning" icon="DocumentAdd" @click="exportInfo"
              >从已有列表中导入</el-button
            >
            <el-button
              v-if="props.customerBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus"
              style="margin-left: 10px"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="customerRef" :model="form" :rules="rules" label-width="120px">
        <el-row v-for="father in processedCustomerData" style="margin-bottom: 10px">
          <div class="formBox">
            <div class="fatherLable">{{ father.fatherTitle }}</div>
            <div class="fatherDes">{{ father.description }}</div>

            <el-row :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="child.key"
                      :key="child.key"
                      :label-width="child.labelWidth"
                      :label-position="child.labelPosition"
                    > -->
                    <el-form-item
                      :label="
                        child.key === 'residentialAddress' && child.type === 'arrowRight'
                          ? ''
                          : child.label
                      "
                      :prop="child.key"
                      :key="child.key"
                      :label-width="child.labelWidth"
                      :label-position="child.labelPosition"
                    >
                      <!-- 自定义 label 插槽 -->
                      <template
                        v-if="child.key === 'residentialAddress' && child.type === 'arrowRight'"
                        #label
                      >
                        <div class="custom-label">
                          <span>{{ child.label }}</span>
                          <el-checkbox-group
                            v-model="form.isCopyAddress"
                            size="small"
                            style="margin-left: 8px"
                            @change="changeAddressStatus(child)"
                            :disabled="copyAddress"
                          >
                            <el-checkbox :value="true" name="isCopyAddress">
                              同通讯地址
                            </el-checkbox>
                          </el-checkbox-group>
                        </div>
                      </template>
                      <el-input
                        v-if="child.type === 'Input'"
                        :type="child.inputType"
                        v-model="form[child.key]"
                        :placeholder="child.placeholder"
                        maxlength="30"
                        :disabled="child.disabled"
                        @change="handleInputChange(child)"
                      />
                      <el-select
                        v-if="child.type === 'Select'"
                        v-model="form[child.key]"
                        :placeholder="child.placeholder"
                        @change="handleSelectChange(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.type === 'DatePicker'"
                        v-model="form[child.key]"
                        type="date"
                        :placeholder="child.placeholder"
                        :disabled="child.disabled"
                        :disabled-date="time => disabledDate(time, child)"
                        :default-value="defaultDisplayDate"
                        @change="handleDateChange(child)"
                      />

                      <el-input
                        v-if="child.type === 'arrowRight'"
                        v-model="form[child.key]"
                        :placeholder="child.placeholder"
                        @click="handleFoucs(child)"
                        :suffix-icon="ArrowRight"
                        readonly
                        :disabled="child.disabled"
                      >
                      </el-input>
                    </el-form-item>
                  </div>
                </el-col>
              </template>
            </el-row>
          </div>
        </el-row>

        <el-row>
          <el-col>
            <div class="tabButton">
              <el-button
                type="primary"
                icon="RefreshRight"
                @click="resetForm"
                size="large"
                :disabled="editStatus"
                >取消</el-button
              >
              <el-button
                type="primary"
                icon="Check"
                @click="submitForm"
                size="large"
                :disabled="editStatus"
                >提交</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog title="客户信息" v-model="openList" width="600px" append-to-body>
        <div>
          <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" @input="customerList" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" circle @click="customerList" />
              <el-button type="info" icon="Refresh" circle @click="resetCustomerList" />
            </el-form-item>
          </el-form>
          <div class="customerBox">
            <div class="customerItem" v-for="item in tableData" :key="item.id">
              <div class="top">
                <div class="left">
                  <div>{{ item.name }}</div>
                  <div v-if="item.gender" style="margin: 0 5px">-</div>
                  <div v-if="item.gender" class="gender">
                    <dict-tag :options="sys_gender" :value="item.gender" />
                  </div>
                </div>
                <div class="right">
                  <el-button type="primary" size="small" @click="handleExport(item)"
                    >导入客户信息</el-button
                  >
                </div>
              </div>
              <div class="bottom">
                <div class="infoItem">
                  <span>证件类型：</span>
                  <span> <dict-tag :options="csf_id_type" :value="item.idType" /></span>
                </div>
                <div class="infoItem">
                  <span>证件号码：</span>
                  <span> {{ item.idCard || '暂无' }}</span>
                </div>
                <div class="infoItem">
                  <span>电话号码：</span>
                  <span> {{ item.phone || '暂无' }}</span>
                </div>
                <div class="infoItem">
                  <span>出生日期：</span>
                  <span> {{ formatToDate(item.birthdate) || '暂无' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <Phone
      @close="handleCloseDrawer"
      :showDrawer="showPhoneDrawer"
      :drawerInfo="drawerInfo"
      :phoneMenuList="phoneMenuList"
      :phoneQuickList="phoneQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Address
      @close="handleCloseDrawer"
      :showAddressDrawer="showAddressDrawer"
      :drawerInfo="drawerInfo"
      :addressMenuList="addressMenuList"
      :addressQuickList="addressQuickList"
      @confirmDrawer="confirmDrawer"
    />
    <Country
      :showCountryDrawer="showCountryDrawer"
      @close="handleCloseDrawer"
      @confirmCountry="confirmDrawer"
    />
  </div>
</template>
<script setup name="customer">
import { validateEnglish } from '@/utils/validate'
import { calculateExactAge } from '@/utils/date'
import dayjs from 'dayjs'
import { ArrowRight } from '@element-plus/icons-vue'
import customerDomData from '@/formJson/customer'
import Country from '@/views/components/country'
import Phone from '@/views/components/phone'
import Address from '@/views/components/address'

import { watch } from 'vue'
import {
  addCustomer,
  getCustomerDetail,
  editCustomer,
  getCustomerList,
  addFna
} from '@/api/sign/fna'
import useDictStore from '@/store/modules/dict'
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  customerBizId: { type: String, default: '' } //提交状态，新增、修改
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
const { csf_id_type, sys_gender } = proxy.useDict('csf_id_type', 'sys_gender')
const showPhoneDrawer = ref(false) //电话抽屉开关
const showAddressDrawer = ref(false) //地址抽屉开关
const showCountryDrawer = ref(false) //国家/地区抽屉开关
const drawerInfo = ref({}) // 用于存储所有arrowRight类型的输入框输入值
const saveKey = ref({}) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作

const tableLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const customerRef = ref(null)
//计算默认显示的日期（18年前的今天）
const defaultDisplayDate = ref(dayjs().subtract(18, 'year').toDate())
// const copyAddress = ref(false) //是否可以复制地址
// 地址组件菜单数据
const addressMenuList = ref([
  {
    name: '国家/地区',
    icon: false,
    value: '',
    placeholder: '请输入国家/地区',
    key: 'region'
  },
  {
    name: '省市',
    icon: false,
    value: '',
    placeholder: '请输入省市',
    key: 'city'
  },
  {
    name: '街道',
    icon: false,
    value: '',
    placeholder: '请输入街道',
    key: 'street'
  },
  {
    name: '详细地址',
    icon: false,
    value: '',
    placeholder: '请输入详细地址',
    key: 'location'
  }
])
// 快捷地址的数据
const addressQuickList = ref([])
const phoneMenuList = ref([
  {
    name: '区号',
    icon: true,
    value: '',
    placeholder: '请输入区号',
    arrow: true,
    type: 'string'
  },
  {
    name: '电话号码',
    icon: false,
    value: '',
    placeholder: '请输入电话号码',
    type: 'number'
  }
])
const phoneQuickList = ref([])
const deleteKeyList = ref([
  'objType',
  'mailingAddress',
  'residentialAddress',
  'residenceAddress',
  'companyAddress'
]) // 存储需要删除的key
const data = reactive({
  form: { isCopyAddress: [] },
  processedCustomerData: [], // 处理后的表单数据
  oldCustomerData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedCustomerData, queryParams, oldCustomerData } = toRefs(data)
const copyAddress = computed(() => {
  const residenceAddressIndex = addressQuickList.value.findIndex(
    item => item.type === 'residenceAddress'
  )
  if (residenceAddressIndex !== -1) {
    return false
  } else {
    return true
  }
})
const changeAddressStatus = child => {
  // 复用地址
  if (form.value.isCopyAddress.length > 0 && form.value.isCopyAddress[0]) {
    if (child.key == 'residentialAddress') {
      form.value[child.key] = form.value['residenceAddress']
      // 这里是直接复用地址了，但是地址组件的值是双向绑定的，所以这里需要手动更新地址组件的值
      addressQuickList.value.forEach(item => {
        if (item.type == 'residenceAddress') {
          saveKey.value[child.key] = { ...item, type: child.key }
        }
      })
    }
  }
  console.log('saveKey.value', saveKey.value)
}
const handleInputChange = child => {
  if (
    (child.key == 'lastName' || child.key == 'firstName') &&
    form.value['lastName'] &&
    form.value['firstName']
  ) {
    form.value['name'] = form.value['lastName'] + form.value['firstName']
  }
}
const handleDateChange = child => {
  let age = null
  if (child.key == 'birthdate') {
    age = calculateExactAge(proxy.formatToDate(form.value.birthdate))
    if (age >= 18) {
      form.value.age = age
    }
  }
}
const disabledDate = (time, child) => {
  if (child.key == 'birthdate') {
    // 计算18年前的今天
    const eighteenYearsAgo = dayjs().subtract(18, 'year')
    // 禁用今天之后的日期和18年前的今天之后的日期
    return time.getTime() > Date.now() || time.getTime() > eighteenYearsAgo.valueOf()
  } else {
    return time.getTime() > Date.now()
  }
}
const resetCustomerList = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
  customerList()
}

const exportInfo = () => {
  if (props.customerBizId && editStatus.value) {
    proxy.$modal.confirm(`请先点击编辑在导入客户信息`, { showCancel: '0', title: '填写提示' })
    return
  }
  openList.value = true
  customerList()
}
const customerList = () => {
  console.log('触发了')

  tableLoading.value = true
  getCustomerList(queryParams.value).then(res => {
    if (res.code == 200) {
      tableData.value = res.data.records
      total.value = res.data.total
      tableLoading.value = false
    }
  })
}
// 从客户列表中导入客户信息到当前表单
const handleExport = row => {
  oldObjInfo.value = JSON.parse(JSON.stringify(form.value)) // 修改时存储原始数据，便于撤销操作
  setFormValue(row, processedCustomerData.value, true)
  openList.value = 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 () => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(customerDomData))

  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (field.dictType) {
          // 获取字典数据
          field.options = fetchDictData(field.dictType)
        }
        if (field.required) {
          if (field.key === 'firstNamePinyin') {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' },
              { validator: validateEnglish, trigger: 'change' }
            ]
          } else {
            rules.value[field.key] = [
              { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
            ]
          }
        }
        if (props.customerBizId) {
          field.disabled = true
        } else if (field.key !== 'age') {
          field.disabled = false
        }
      }
    }
  }

  if (props.customerBizId) {
    getCustomerInfo(props.customerBizId, processedData)
    editStatus.value = true
  } else {
    editStatus.value = false
    form.value.customerType = 'INDIVIDUAL'
    processedCustomerData.value = oldCustomerData.value = processedData
  }
}

//弹出右侧抽屉
const handleFoucs = child => {
  if (child.disabled) return
  drawerInfo.value = JSON.parse(JSON.stringify(child))

  switch (child.drawerType) {
    case 'phone':
      phoneMenuList.value[0].key = child.code
      phoneMenuList.value[1].key = child.key
      phoneMenuList.value.forEach(item => {
        item.value = ''
        for (const key in saveKey.value) {
          if (key == child.key) {
            for (const key2 in saveKey.value[key]) {
              if (item.key == key2) {
                item.value = saveKey.value[key][key2]
              }
            }
          }
        }
      })

      showPhoneDrawer.value = true
      break
    case 'address':
      addressMenuList.value.forEach(item => {
        item.value = ''
        for (const key in saveKey.value) {
          if (key == child.key) {
            for (const key2 in saveKey.value[key]) {
              if (item.key == key2) {
                item.value = saveKey.value[key][key2]
              }
            }
          }
        }
      })
      showAddressDrawer.value = true
      break
    case 'country':
      showCountryDrawer.value = true
      break
    default:
      break
  }
}
// 处理抽屉关闭
const handleCloseDrawer = () => {
  showPhoneDrawer.value = false
  showAddressDrawer.value = false
  showCountryDrawer.value = false
  drawerInfo.value = {}
}
// 点击了抽屉的确定
const confirmDrawer = info => {
  // console.log('抽屉info', info)

  // info 为抽屉返回的值
  if (drawerInfo.value.type == 'arrowRight' && drawerInfo.value.drawerType) {
    // console.log('drawerInfo.value', drawerInfo.value)

    let newObj = info[drawerInfo.value.key]
    //要判断drawerType
    switch (drawerInfo.value.drawerType) {
      case 'phone':
        newObj.objType = drawerInfo.value.drawerType
        // 因为电话有多个，根据点击的电话类型在抽屉里回显，所以要用drawerInfo.value.code来控制
        form.value[info.key] = newObj.phoneString = `${newObj[drawerInfo.value.code]} ${
          newObj[drawerInfo.value.key]
        }`
        newObj.key = drawerInfo.value.key
        saveKey.value[drawerInfo.value.key] = newObj
        // debugger
        // 检查数组中是否已存在key的电话
        const existingIndex = phoneQuickList.value.findIndex(item => item.key === newObj.key)

        if (existingIndex !== -1) {
          // 更新已存在的电话
          phoneQuickList.value[existingIndex] = {
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          }
        } else {
          // 添加新的快捷电话
          phoneQuickList.value.push({
            code: newObj[drawerInfo.value.code],
            mobile: newObj[drawerInfo.value.key],
            key: drawerInfo.value.key,
            phoneString: newObj.phoneString
          })
        }
        phoneQuickList.value = removeDuplicates(phoneQuickList.value, 'phoneString')
        break
      case 'address':
        newObj.objType = drawerInfo.value.drawerType
        newObj.type = drawerInfo.value.key
        form.value[info.key] = `${newObj.region} ${newObj.city} ${newObj.street} ${newObj.location}`
        saveKey.value[info.key] = newObj
        console.log('newObj', newObj)
        newObj.addressString = `${newObj.region}${newObj.city}${newObj.street}${newObj.location}`
        // 检查数组中是否已存在key的地址
        // debugger

        const existinAddressIndex = addressQuickList.value.findIndex(
          item => item.type === newObj.type
        )

        if (existinAddressIndex !== -1) {
          // 更新已存在的电话
          addressQuickList.value[existinAddressIndex] = {
            ...newObj
          }
        } else {
          // 添加新的快捷电话
          addressQuickList.value.push(newObj)
        }
        addressQuickList.value = removeDuplicates(addressQuickList.value, 'addressString')

        console.log('填写地址', copyAddress.value)

        break
      case 'country':
        info.objType = drawerInfo.value.drawerType
        form.value[drawerInfo.value.key] = info.name
        saveKey.value[drawerInfo.value.key] = info
        break
      default:
        break
    }
    // 手动触发表单验证
    nextTick(() => {
      // 根据不同的drawerType确定要验证的字段key
      const validateField = drawerInfo.value.key
      customerRef.value.clearValidate(validateField)
    })
  }

  handleCloseDrawer()
}
// 根据联动重置表单项的显示与否
const resetShow = (key, status) => {
  for (const section of processedCustomerData.value) {
    if (section.data) {
      for (const field of section.data) {
        if (field.key == key) {
          // 获取字典数据
          field.show = status
          if (!status) {
            form.value[key] = ''
          }
        }
      }
    }
  }
}
const handleSelectChange = child => {
  switch (child.key) {
    case 'smoke':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key] == '1') {
        resetShow('smokeQuantity', true)
      } else {
        resetShow('smokeQuantity', false)
      }
      break
    case 'idType':
      // 选择吸烟，展示吸烟数量
      if (form.value[child.key] == 'idCard') {
        resetShow('idCardAddress', true)
      } else {
        resetShow('idCardAddress', false)
      }
      break
    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = () => {
  editStatus.value = !editStatus.value
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedCustomerData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (editStatus.value) {
          field.disabled = true
        } else if (field.key !== 'age') {
          field.disabled = false
        }
      }
    }
  }
  processedCustomerData.value = processedData
}
//给表单赋值 方便表单回显 obj 为表单数据
const setFormValue = (obj, formData, exportValue) => {
  let tempPhoneList = []
  let tempAddressList = []
  addressQuickList.value = []
  phoneQuickList.value = []
  // 深拷贝原始数据
  form.value = JSON.parse(JSON.stringify(obj))
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(formData))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (obj.smokeQuantity && field.key == 'smokeQuantity') {
          field.show = true
        }
        //证件类型是身份证，身份证地址就显示否则不显示
        if (field.key == 'idCardAddress' && obj.idType == 'idCard') {
          field.show = true
        }
        //要判断drawerType,因为抽屉要回显数据
        switch (field.drawerType) {
          case 'phone':
            let phoneObj = {}
            for (const key1 in field) {
              for (const key2 in obj) {
                if (key1 !== 'drawerType' && field[key1] == key2) {
                  if (key1 == 'code' && obj[key2]) {
                    phoneObj[field[key1]] = obj[key2].includes('+') ? obj[key2] : `+${obj[key2]}`
                  } else {
                    phoneObj[field[key1]] = obj[key2]
                  }
                }
              }
            }

            if (phoneObj[field.key]) {
              phoneObj.phoneString = form.value[field.key] = `${phoneObj[field.code]} ${
                phoneObj[field.key]
              }`
              tempPhoneList.push(phoneObj)
            }
            phoneObj.objType = field.drawerType
            phoneObj.key = field.key
            phoneObj.phoneCode = field.code
            saveKey.value[field.key] = phoneObj
            break
          case 'address':
            let addressObj = null
            for (const key1 in field) {
              if (obj.addressList && obj.addressList.length > 0) {
                obj.addressList.forEach(item => {
                  if (key1 == item.type) {
                    addressObj = item
                  }
                })
              }
            }

            if (addressObj) {
              form.value[
                field.key
              ] = `${addressObj.region} ${addressObj.city} ${addressObj.street} ${addressObj.location}`
              addressObj.addressString = `${addressObj.region}${addressObj.city}${addressObj.street}${addressObj.location}`
              addressObj.objType = field.drawerType
              saveKey.value[field.key] = addressObj
              if (tempAddressList.length > 0) {
                tempAddressList.forEach(item => {
                  if (item.addressString !== addressObj.addressString) {
                    tempAddressList.push(addressObj)
                  }
                })
              } else {
                tempAddressList.push(addressObj)
              }
            }

            break
          case 'country':
            form.value[field.key] = obj.countryName
            saveKey.value[field.key] = {
              country: obj.country || '',
              countryCode: obj.country || '',
              countryName: obj.countryName || '',
              name: obj.countryName || '',
              objType: field.drawerType
            }
            break
          default:
            break
        }
      }
    }
  }
  addressQuickList.value = tempAddressList
  tempPhoneList.forEach(item => {
    for (const key in saveKey.value) {
      if (item.key == key) {
        for (const key2 in saveKey.value[key]) {
          if (item.key == key2) {
            item.mobile = saveKey.value[key][key2]
          }
          if (item.phoneCode == key2) {
            item.code = saveKey.value[key][key2]
          }
        }
      }
    }
  })
  if (form.value['birthdate']) {
    let age = calculateExactAge(proxy.formatToDate(form.value.birthdate))
    if (age >= 18) {
      form.value.age = age
    }
  } else {
    form.value.age = null
  }

  phoneQuickList.value = removeDuplicates(tempPhoneList, 'phoneString')
  addressQuickList.value = removeDuplicates(tempAddressList, 'addressString')

  if (!exportValue) {
    // 保存一份就得表单数据便于做撤销操作
    oldObjInfo.value = JSON.parse(JSON.stringify(form.value))
  }
  processedCustomerData.value = oldCustomerData.value = processedData
  // console.log('====================================')
  // console.log('processedCustomerData.value', processedCustomerData.value)
  // console.log('====================================')
  // console.log('====================================')
  // console.log('form', form.value)
  // console.log('====================================')
}
// 数组去重
function removeDuplicates(arr, key) {
  const seen = new Map()
  const result = []

  for (const item of arr) {
    if (!seen.has(item[key]) && item[key]) {
      seen.set(item[key], true)
      result.push(item)
    }
  }

  return result
}
// 获取校验失败的字段信息
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 submitForm = () => {
  let submitObj = { ...form.value }
  let addressList = []
  submitObj['birthdate'] = proxy.formatToDate(submitObj['birthdate'])

  proxy.$refs['customerRef'].validate((valid, fields) => {
    if (valid) {
      //处理表单数据
      for (const key1 in form.value) {
        for (const key2 in saveKey.value) {
          //要判断drawerType
          switch (saveKey.value[key2].objType) {
            case 'phone':
              if (key1 == key2) {
                for (const key3 in saveKey.value[key2]) {
                  submitObj[key3] = saveKey.value[key2][key3]
                }
              }

              break
            case 'address':
              if (key1 == key2) {
                addressList.push(saveKey.value[key2])
              }
              break
            case 'country':
              if (key1 == key2) {
                submitObj['country'] = saveKey.value[key2]['countryCode']
                submitObj['countryName'] = saveKey.value[key2]['name']
              }
              break
            default:
              break
          }
        }
      }
      submitObj['birthdate'] = proxy.formatToDate(submitObj['birthdate'])
      submitObj['addressList'] = addressList
      // 删除多余字段
      deleteKeyList.value.forEach(item => {
        delete submitObj[item]
      })

      if (props.customerBizId) {
        editCustomer(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus()
            proxy.$message.success('客户修改成功')
            emit('handleSuccess', {
              tab: 'customer',
              customerBizId: props.customerBizId,
              type: 'edit'
            })
          }
        })
      } else {
        addFna({ remark: '' }).then(response => {
          if (response.code == 200) {
            //  res.data.fnaBizId 写到这了，先增加fna，再增加客户 看一下流程是否报错
            addCustomer(submitObj).then(res => {
              if (res.code == 200) {
                proxy.$message.success('客户新增成功')
                emit('handleSuccess', {
                  tab: 'customer',
                  customerBizId: res.data.customerBizId,
                  fnaBizId: response.data.fnaBizId,
                  type: 'add'
                })
              }
            })
          }
        })
      }

      // emit('submitForm', submitObj)
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}
const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      if (props.customerBizId) {
        form.value = { ...oldObjInfo.value }
        editStatus.value = true
      } else {
        resetShow('smokeQuantity', false)
        proxy.$refs['customerRef'].resetFields()
      }
      processedCustomerData.value = JSON.parse(JSON.stringify(oldCustomerData.value))
    })

    .catch(() => {})
}
// 获取客户详情
function getCustomerInfo(customerBizId, formData) {
  getCustomerDetail(customerBizId).then(async res => {
    if (res.code == 200) {
      // 回显值
      setFormValue(res.data, formData)
    }
  })
}
watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'customer') {
      processFormData()
    }
  }
)
</script>
<style lang="scss" scoped>
.custom-label {
  width: 100%;
  display: flex;
  align-items: center;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
  }
  .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-right: 20px; */
  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;
  }
}
</style>
