<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"
              >编辑</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>
              <template v-for="child in father.data" :key="child.key">
                <el-col :span="8" class="formItem" v-if="child.show">
                  <div>
                    <el-form-item :label="child.label" :prop="child.key" :key="child.key">
                      <el-input
                        v-if="child.type === 'Input'"
                        :type="child.inputType"
                        v-model="form[child.key]"
                        :placeholder="child.placeholder"
                        maxlength="30"
                        :disabled="child.disabled"
                      />
                      <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"
                      />

                      <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 { 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 { getDicts } from '@/api/system/dict/data'
import { watch, nextTick } from 'vue'
import { addCustomer, getCustomerDetail, editCustomer, getCustomerList } 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 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: {},
  processedCustomerData: [], // 处理后的表单数据
  oldCustomerData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, processedCustomerData, queryParams, oldCustomerData } = toRefs(data)
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 == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } 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(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 {
          field.disabled = false
        }
      }
    }
  }

  if (props.customerBizId) {
    getCustomerInfo(props.customerBizId, processedData)
  } else {
    editStatus.value = false
    processedCustomerData.value = oldCustomerData.value = processedData
  }
}

//弹出右侧抽屉
const handleFoucs = child => {
  if (child.disabled) return
  console.log('saveKey.value', saveKey.value)

  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 => {
        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 => {
        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 => {
  // 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[drawerInfo.value.code]} ${newObj[drawerInfo.value.key]}`
        saveKey.value[drawerInfo.value.key] = newObj
        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
        break
      case 'country':
        info.objType = drawerInfo.value.drawerType
        form.value[drawerInfo.value.key] = info.name
        saveKey.value[drawerInfo.value.key] = info
        break
      default:
        break
    }
  }
  console.log('saveKey.value', saveKey.value)

  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

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = () => {
  editStatus.value = !editStatus.value
  console.log('触发了编辑状态', 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 {
          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
        }
        //要判断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]
          }
        }
      }
    }
  })

  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
}
// 数组去重
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 = () => {
  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 {
        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 }
        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') {
      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;
  }
  .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>
