<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">
        <el-row v-for="father in processedFanFormData" style="margin-bottom: 10px">
          <div class="formBox">
            <div class="fatherLable">{{ father.fatherTitle }}</div>

            <el-row v-if="father.child == 'no'">
              <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"
                      v-if="child.layout == 'row'"
                    >
                      <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"
                      />
                      <el-select
                        v-if="child.domType === 'Select'"
                        v-model="form[father.key][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.domType === 'DatePicker'"
                        v-model="form[father.key][child.key]"
                        type="date"
                        :placeholder="child.placeholder"
                        :disabled="child.disabled"
                      />
                    </el-form-item>
                    <el-form-item
                      :label="child.label"
                      :prop="child.key"
                      :key="child.key"
                      v-if="child.layout == 'column'"
                    >
                      <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"
                      />
                    </el-form-item>
                  </div>
                </el-col>
              </template>
            </el-row>
            <!-- 有子孙的dom -->
            <el-row v-if="father.child == 'yes'">
              <template v-for="(child, childIndex) in father.data" :key="child.id">
                <el-col :span="child.span">
                  <div class="childLabel" v-if="father.key == 'familyMembers'">
                    {{
                      child.type == '4' ? `${child.childTitle}-${childIndex - 2}` : child.childTitle
                    }}
                  </div>
                  <div
                    class="childLabel"
                    v-if="
                      father.key == 'existingSecurityOwner' ||
                      father.key == 'existingSecurityInsured'
                    "
                  >
                    {{ `${child.childTitle}-${childIndex + 1}` }}
                  </div>
                </el-col>
                <template v-for="grandchildren in child.children" :key="grandchildren.key">
                  <el-col
                    :sm="grandchildren.sm"
                    :lg="grandchildren.lg"
                    class="formItem"
                    v-if="grandchildren.show"
                  >
                    <el-form-item
                      :label="grandchildren.label"
                      :prop="grandchildren.key"
                      :key="grandchildren.key"
                      :label-width="grandchildren.labelWidth"
                    >
                      <el-input
                        v-if="grandchildren.domType === 'Input'"
                        :type="grandchildren.inputType"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        :placeholder="grandchildren.placeholder"
                        maxlength="30"
                        :disabled="grandchildren.disabled"
                      />
                      <el-select
                        v-if="grandchildren.domType === 'Select'"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        :placeholder="grandchildren.placeholder"
                        @change="handleSelectChange(grandchildren)"
                        :disabled="grandchildren.disabled"
                      >
                        <el-option
                          v-for="item in grandchildren.options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-date-picker
                        style="width: 100%"
                        v-if="grandchildren.domType === 'DatePicker'"
                        v-model="form[father.key][childIndex][grandchildren.key]"
                        type="date"
                        :placeholder="grandchildren.placeholder"
                        :disabled="grandchildren.disabled"
                      />
                    </el-form-item>
                  </el-col>
                </template>
                <el-col
                  v-if="child.delete"
                  :span="3"
                  style="margin-left: 10px"
                  @click="deleteChildren(father, childIndex)"
                >
                  <el-icon style="color: red; font-size: 18px; padding-top: 15px"
                    ><Delete
                  /></el-icon>
                </el-col>
              </template>
              <el-col
                :span="24"
                v-if="father.addFamilyChildren"
                style="display: flex; justify-content: flex-end"
              >
                <el-button type="primary" icon="Plus" @click="addChildren(father)"
                  >添加儿女</el-button
                >
              </el-col>
            </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
              >
              <!-- :disabled="editStatus" -->
              <el-button type="primary" icon="Check" @click="submitForm" size="large"
                >提交</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script setup name="customer">
import fanFormDomData from '@/formJson/fnaForm'
import { getDicts } from '@/api/system/dict/data'
import { watch } from 'vue'
import { addCustomer, getCustomerDetail, editCustomer, getCustomerList } from '@/api/sign/fna'
console.log('fanFormDomData', fanFormDomData)

const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  fnaFormBizId: { type: String, default: '' } //提交状态，新增、修改
})
const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()
// const { sys_no_yes } = proxy.useDict('sys_no_yes')
const saveKey = ref({}) // 用于存储当前点击的drawer框返回的对象,修改的时候回显值也要存key
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const noYesList = ref([]) // 是否列表

// 快捷地址的数据
const addressQuickList = ref([])

const phoneQuickList = ref([])
const deleteKeyList = ref([
  'objType',
  'mailingAddress',
  'residentialAddress',
  'residenceAddress',
  'companyAddress'
]) // 存储需要删除的key
const data = reactive({
  form: {
    familyMembers: [],
    personalData: {},
    existingSecurityOwner: [],
    existingSecurityInsured: [],
    incom: {}
  },
  processedFanFormData: [], // 处理后的表单数据
  oldFanFormData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedFanFormData, queryParams, oldFanFormData } = toRefs(data)
const handleInputChange = val => {
  console.log('form', form.value)
}

// 获取字典数据
const fetchDictData = async dictType => {
  try {
    const resp = await getDicts(dictType)
    return resp.data.map(p => ({ label: p.itemLabel, value: p.itemValue }))
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
// 添加英文校验函数
const validateEnglish = (rule, value, callback) => {
  if (value && !/^[A-Za-z]*$/.test(value)) {
    // 清空非英文字符
    form.value.firstNamePinyin = ''
    callback(new Error('只能输入英文字母'))
  } else {
    callback()
  }
}

// 处理表单配置，添加字典数据
const processFormData = async () => {
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(fanFormDomData))

  for (const section of processedData) {
    if (section.data) {
      for (const formKey in form.value) {
        if (section.key == formKey) {
          if (section.dataLength) {
            for (let i = 1; i < section.dataLength; i++) {
              section.data.push(JSON.parse(JSON.stringify(section.data[0])))
            }
          }
          for (const field of section.data) {
            if (section.key == formKey && field.children) {
              for (const child of field.children) {
                if (child.dictType) {
                  // 获取字典数据
                  child.options = await fetchDictData(child.dictType)
                  if (child.dictType == 'sys_no_yes') {
                    noYesList.value = child.options
                  }
                }
              }
            }
            if (field.dictType) {
              // 获取字典数据
              field.options = await 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.fnaFormBizId) {
              field.disabled = true
            } else {
              field.disabled = false
            }
          }
          form.value[formKey] = section.data //便于表单收集值
        }
      }
    }
  }
  processedFanFormData.value = oldFanFormData.value = processedData
  console.log('====================================')
  console.log('form', form.value)
  console.log('====================================')
  // if (props.customerBizId) {
  //   getCustomerInfo(props.customerBizId, processedData)
  // } else {
  //   editStatus.value = false
  //   processedFanFormData.value = oldFanFormData.value = processedData
  // }
}
// 添加表单子级dom
const addChildren = father => {
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  let obj = {
    type: '4',
    childTitle: '儿女',
    span: 24, //栅格布局份数
    id: Date.now() + Math.floor(Math.random() * 1000), //唯一标识
    delete: true, //是否显示删除按钮
    children: [
      {
        label: '年龄',
        key: 'age',
        domType: 'Input',
        inputType: 'number',
        required: false,
        maxLength: 30,
        disabled: false,
        placeholder: '请输入',
        show: true,
        labelWidth: '120px', //标签宽度
        sm: 10, //栅格布局份数
        lg: 8 //栅格布局份数
      },
      {
        label: '是否需要供养',
        key: 'needProvide',
        domType: 'Select',
        required: false,
        maxLength: 30,
        disabled: false,
        placeholder: '请输入',
        show: true,
        dictType: 'sys_no_yes',
        options: noYesList.value,
        labelWidth: '120px', //标签宽度
        sm: 10, //栅格布局份数
        lg: 8 //栅格布局份数
      }
    ]
  }
  for (const section of processedData) {
    if (father.key == 'familyMembers') {
      section.data.push(obj)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  form.value['familyMembers'].push(obj)
  processedFanFormData.value = processedData
}
const deleteChildren = (father, childIndex) => {
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  for (const section of processedData) {
    if (father.key == 'familyMembers') {
      section.data.splice(childIndex, 1)
    }
  }
  //更新form表单对应的数据，以便收集填写的值
  form.value['familyMembers'].splice(childIndex, 1)
  console.log('form.value', form.value)

  processedFanFormData.value = processedData
}
// 根据联动重置表单项的显示与否
const resetShow = (key, status) => {
  for (const section of processedFanFormData.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

    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) {
        if (editStatus.value) {
          field.disabled = true
        } else {
          field.disabled = false
        }
      }
    }
  }
  processedFanFormData.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
        }
        //要判断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]
          }
        }
      }
    }
  })
  console.log('tempPhoneList', tempPhoneList)

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

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

  for (const item of arr) {
    if (!seen.has(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 = () => {
  console.log('form.value', form.value)
  return
  let submitObj = { ...form.value }
  let addressList = []
  submitObj['birthdate'] = proxy.formatToDate(submitObj['birthdate'])

  proxy.$refs['fanFormRef'].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 {
        addCustomer(submitObj).then(res => {
          if (res.code == 200) {
            proxy.$message.success('客户新增成功')
            emit('handleSuccess', {
              tab: 'customer',
              customerBizId: res.data.customerBizId,
              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 }
      } else {
        resetShow('smokeQuantity', false)
        proxy.$refs['fanFormRef'].resetFields()
      }
      processedFanFormData.value = JSON.parse(JSON.stringify(oldFanFormData.value))
      console.log('processedFanFormData.value', processedFanFormData.value)
    })

    .catch(() => {})
}
// 获取流程详情
function getCustomerInfo(customerBizId, formData) {
  getCustomerDetail(customerBizId).then(async res => {
    if (res.code == 200) {
      // 回显值
      setFormValue(res.data, formData)
    }
  })
}
watch(
  () => props.activeName,
  newVal => {
    console.log('newVal', newVal)

    if (newVal === 'fnaform') {
      openList.value = false
      processFormData()
    }
  }
)
</script>
<style lang="scss" scoped>
.topBtn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
    margin-bottom: 5px;
  }
  .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换行并显示省略号 */
/* :deep(.el-form-item__label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  vertical-align: middle;
} */

/* 确保标签对齐方式正确 */
/* :deep(.el-form-item) {
  display: flex;
  align-items: center;
} */

/* :deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
} */
</style>
