动态表单( 自定义字段进行新增 vue3)

一、 字段配置

启用:是否显示

必填: 是否校验 

二 获取字段设置列表

根据字段设置,可以获取到字段列表, 进行展示新增页面

类型描述(待定):

单行文本 :input
下拉单选:select
下拉多选:selectMultiple
多行文本框: textarea
社媒: socialMedia
地区选择:regionalSelect
人员单选: personnelSelect
人员多选: personnelSelectMultiple
日期选择: datePicker
币种汇率: currencyRate
二级下拉选择(客户来源、商机来源):secondLevelSelect

2.1 后端返回格式

{
    "msg": "请求成功",
    "code": "200",
    "data": [
        {
            "fieldGroup": 1,
            "fieldList": [
                {
                    "templateId": "1824301171154497536",
                    "fieldCode": "name",
                    "fieldName": "客户名称",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 1,
                    "enable": 1,
                    "required": 1,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080448",
                    "fieldCode": "domainName",
                    "fieldName": "域名",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 2,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080449",
                    "fieldCode": "industry",
                    "fieldName": "行业",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080450",
                    "fieldCode": "establishTime",
                    "fieldName": "成立年份",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单选",
                    "fieldTypeCode": "yearSelect",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080451",
                    "fieldCode": "scale",
                    "fieldName": "规模",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080452",
                    "fieldCode": "income",
                    "fieldName": "年收入",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080453",
                    "fieldCode": "description",
                    "fieldName": "公司描述",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080454",
                    "fieldCode": "regionalSelect",
                    "fieldName": "所在地",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "地区选择",
                    "fieldTypeCode": "regionalSelect",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080455",
                    "fieldCode": "postcode",
                    "fieldName": "邮政编码",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080456",
                    "fieldCode": "address",
                    "fieldName": "地址",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171167080457",
                    "fieldCode": "email",
                    "fieldName": "公司邮箱",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171171274752",
                    "fieldCode": "mobile",
                    "fieldName": "公司电话",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171171274753",
                    "fieldCode": "fax",
                    "fieldName": "公司传真",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171171274754",
                    "fieldCode": "remark",
                    "fieldName": "备注",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "多行文本",
                    "fieldTypeCode": "textarea",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                },
                {
                    "templateId": "1824301171171274755",
                    "fieldCode": "socialMedia",
                    "fieldName": "社媒",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "社媒",
                    "fieldTypeCode": "socialMedia",
                    "fieldGroup": 1,
                    "special": 0,
                    "enable": 1,
                    "required": 0,
                    "dictionaryCode": null
                }
            ]
        },
        {
            "fieldGroup": 9,
            "fieldList": [
                {
                    "templateId": "1824301171355824128",
                    "fieldCode": "1824301171355824129",
                    "fieldName": "啊生生世世身上",
                    "tid": "1",
                    "type": 1,
                    "fieldTypeName": "单行文本",
                    "fieldTypeCode": "input",
                    "fieldGroup": 9,
                    "special": 0,
                    "enable": 0,
                    "required": 0,
                    "dictionaryCode": null
                }
            ]
        }
    ]
}

2.2 解析:如何封装数据

根据【启用:是否显示;必填: 是否校验 】来组装数据,

是否显示:没有就从数组中去除

是否校验: 如果校验,就封装rule 到对象当中

更多按钮: 把不是必填的塞到一个新的list当中 

[
    {
        "title": "基础信息",
        "fieldList": [
            {
                "templateId": "1824301171154497536",
                "fieldCode": "name",
                "fieldName": "客户名称",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 1,
                "enable": 1,
                "required": 1,
                "dictionaryCode": null,
                "rules": [
                    {
                        "required": true,
                        "message": "客户名称不能为空",
                        "trigger": [
                            "blur",
                            "change"
                        ]
                    },
                    {
                        "min": 0,
                        "max": 50,
                        "message": "客户名称最多50字符",
                        "trigger": "blur"
                    }
                ]
            },
            {
                "templateId": "1824301171167080448",
                "fieldCode": "domainName",
                "fieldName": "域名",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 2,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null,
                "rules": [
                    {
                        "type": "url",
                        "message": "域名格式错误",
                        "trigger": [
                            "blur",
                            "change"
                        ]
                    }
                ]
            }
        ]
    },
    {
        "title": "填写更多信息",
        "showMore": true,
        "fieldList": [
            {
                "templateId": "1824301171167080449",
                "fieldCode": "industry",
                "fieldName": "行业",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080450",
                "fieldCode": "establishTime",
                "fieldName": "成立年份",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单选",
                "fieldTypeCode": "yearSelect",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080451",
                "fieldCode": "scale",
                "fieldName": "规模",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080452",
                "fieldCode": "income",
                "fieldName": "年收入",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080453",
                "fieldCode": "description",
                "fieldName": "公司描述",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080454",
                "fieldCode": "regionalSelect",
                "fieldName": "所在地",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "地区选择",
                "fieldTypeCode": "regionalSelect",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080455",
                "fieldCode": "postcode",
                "fieldName": "邮政编码",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080456",
                "fieldCode": "address",
                "fieldName": "地址",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171167080457",
                "fieldCode": "email",
                "fieldName": "公司邮箱",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null,
                "rules": [
                    {
                        "type": "email",
                        "message": "邮箱格式错误",
                        "trigger": [
                            "blur",
                            "change"
                        ]
                    }
                ]
            },
            {
                "templateId": "1824301171171274752",
                "fieldCode": "mobile",
                "fieldName": "公司电话",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171171274753",
                "fieldCode": "fax",
                "fieldName": "公司传真",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "单行文本",
                "fieldTypeCode": "input",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            },
            {
                "templateId": "1824301171171274754",
                "fieldCode": "remark",
                "fieldName": "备注",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "多行文本",
                "fieldTypeCode": "textarea",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null,
                "rules": [
                    {
                        "min": 0,
                        "max": 300,
                        "message": "备注最多300字符",
                        "trigger": "blur"
                    }
                ]
            },
            {
                "templateId": "1824301171171274755",
                "fieldCode": "socialList",
                "fieldName": "社媒",
                "tid": "1",
                "type": 1,
                "fieldTypeName": "社媒",
                "fieldTypeCode": "socialMedia",
                "fieldGroup": 1,
                "special": 0,
                "enable": 1,
                "required": 0,
                "dictionaryCode": null
            }
        ]
    }
]

2.3 封装数据

allBaseInfo.push(...(item.fieldList || []))

1) ...item.fieldList 拿到的是每一个对象

2):...展开运算符是将一个数组的对象克隆给另一个数组

3)对象合并: 可以将多个对象的成员,合并到一个大的对象中,后面对象中的成员,如果跟前面对象中的成员同名,会覆盖前面的

 
 

封装规则

<!-- 新建和编辑客户 -->
<template>
  <Drawer
    :title="titleText"
    ref="drawer"
    size="648"
    class="commonDrawer"
    @open-drawer="openDrawer"
    @close-drawer="closeDrawer"
  >
    <!-- 内容 -->
    <template #content>
      <!-- 动态表单 -->
      <CustomDynamicForm
        :formData="formData"
        :data="filedList"
        :rules="rules"
        ref="customerFromRef"
        class="custom-loading-icon"
        v-loading="drawerLoading"
        element-loading-text="加载中..."
      />
    </template>

    <!-- 按钮 -->
    <template #foot_button>
      <div class="error-alert" v-show="isContact">
        <el-icon size="16" color="#fa5151"><iconEpWarningFilled /></el-icon>
        <span>请至少填写一个联系方式包括手机号、邮箱、社媒账号</span>
      </div>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="confirmHandler" :disabled="drawerLoading">保存</el-button>
    </template>
  </Drawer>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue"
import CustomDynamicForm from "@/components/dynamicForm/CustomDynamicForm.vue"
import CrmFieldSettingAPI from "@/api/crm/fieldSetting"
import Drawer from "@/components/common/Drawer.vue"
import { DEFAULT_FORM_DATA } from "@/assets/constants/customer"
import { SOCIAL_ITEM } from "@/assets/constants/location"
import { stringMaxLength, validNumberFormat, validUrlFormat } from "@/utils/validator"
import { EMAIL_FORMAT } from "@/assets/constants/validator"
import CrmCustomerAPI from "@/api/crm/customer"
import { ElMessage } from "element-plus"
import { elFormErrorScrollIntoView } from "@/utils/index"
import { useRoute } from "vue-router"
import microApp from "@micro-zoe/micro-app"
import FollowUpApi from "@/api/crm/createFollowUp.ts"

const route = useRoute()
const props = defineProps({
  currentDetailId: {
    type: String,
    default: ""
  }
})
const emits = defineEmits(["clearCurrentDetailId"])
// 弹框标题
const titleText = computed(() => (props.currentDetailId ? "编辑客户" : "新建客户"))
// 是否是编辑
const isEdit = computed(() => (props.currentDetailId ? true : false))
//表单对象
const formData = ref(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
// 模版数据
const filedList = ref<any>([])
// 表单ref DOM节点
const customerFromRef = ref()
// 规则校验
const rules = {}
// 在填写了联系人名称后是否填写手机号、邮箱、社媒的其中一个
const isContact = ref(false)
// 点击了保存按钮
const clickConfirm = ref(false)
// 手动校验手机号、邮箱、社媒的开关
const validFlag = ref(false)
// 保存开关
const saveFlag = ref(false)

const drawerLoading = ref(false)

/** 获取动态表单 */
const openDrawer = async () => {
  try {
    drawerLoading.value = true
    // 弹框开启时获取模版
    await getDynamicForm(1)
    //编辑
    if (props.currentDetailId) {
      loadData()
    }
    drawerLoading.value = false
  } catch (_err) {
    drawerLoading.value = false
  }
}
const closeDrawer = () => {
  // 弹框关闭时重置
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
  isContact.value = false
  clickConfirm.value = false
  emits("clearCurrentDetailId")
}

// 获取联系人信息
const getConnectInfo = () => {
  const obj = [
    {
      fieldCode: "contactName",
      fieldName: "联系人",
      fieldTypeCode: "input",
      rules: [
        {
          required: true,
          message: `联系人不能为空`,
          trigger: "blur"
        },
        stringMaxLength("联系人")
      ]
    },
    {
      fieldCode: "contactMobile",
      fieldName: "手机号",
      fieldTypeCode: "input",
      rules: [
        {
          validator: mobileEmailSocialValid
        }
        // ,
        // validNumberFormat("手机号")
      ]
    },
    {
      fieldCode: "contactEmail",
      fieldName: "邮箱",
      fieldTypeCode: "input",
      rules: [
        {
          validator: mobileEmailSocialValid
        },
        EMAIL_FORMAT
      ]
    },
    {
      fieldCode: "contactSocialList",
      fieldName: "社媒",
      fieldTypeCode: "socialMedia",
      rules: {
        validator: mobileEmailSocialValid
      }
    }
  ]
  return { title: "联系人信息", fieldList: obj }
}
// 联系人-验证:手机号、邮箱、社媒
const mobileEmailSocialValid = (_rule: any, _value: any, callback: any) => {
  if (formData.value.contactName.trim() && clickConfirm.value) {
    const strSocialList = formData.value.contactSocialList.map((item: any) => {
      return `${item.contactWay ? item.contactWay.trim() : ""}${item.socialUrl ? item.socialUrl.trim() : ""}`
    })
    if (
      !formData.value.contactEmail.trim() &&
      !formData.value.contactMobile.trim() &&
      !strSocialList.join("").trim()
    ) {
      isContact.value = true
      callback(new Error(""))
    } else {
      isContact.value = false
      callback()
    }
  } else {
    isContact.value = false
    if (!validFlag.value) {
      manualValidContact()
    }
    callback()
  }
}
const manualValidContact = () => {
  validFlag.value = true
  // 校验社媒
  formData.value.contactSocialList.forEach((_item: any, index: number) => {
    customerFromRef.value.dynamicForm.validateField(`contactSocialList.${index}.socialType`)
    customerFromRef.value.dynamicForm.validateField(`contactSocialList.${index}.contactWay`)
    customerFromRef.value.dynamicForm.validateField(`contactSocialList.${index}.socialUrl`)
  })
  // 校验邮箱
  customerFromRef.value.dynamicForm.validateField("contactEmail")
  // 校验手机号
  customerFromRef.value.dynamicForm.validateField("contactMobile", () => {
    setTimeout(() => {
      validFlag.value = false
    }, 500)
  })
}
/**
 * 获取模版数据
 * @type 业务类型:1-客户、2-联系人、3-商机
 */
const getDynamicForm = async (type) => {
  const res = await CrmFieldSettingAPI.queryFieldList({
    type: type
  })
  filedList.value = []
  // 所有数据
  const dataList = res?.data || []
  // 所有的基础信息
  const allBaseInfo: any[] = []
  // 自定义信息
  let customerInfo: any[] = []
  // 页面基础信息
  const baseInfo: any[] = []
  // 基础信息中的更多模块
  const more: any[] = []

  dataList.forEach((item) => {
    if (item.fieldGroup === 1) {
      allBaseInfo.push(...(item.fieldList || []))
    }
    if (item.fieldGroup === 9) {
      customerInfo.push(...(item.fieldList || []))
    }
  })
  allBaseInfo.forEach((item: any) => {
    // 判断字段是否启用
    if (item.enable === 1) {
      // 调整社媒字段名称
      if (item.fieldCode === "socialMedia") {
        item.fieldCode = "socialList"
      }
      // 基础信息必填展示在更多信息外面
      if (item.required === 1) {
        item.rules = [
          {
            required: true,
            message: `${item.fieldName}不能为空`,
            trigger: ["blur", "change"]
          }
        ]
        baseInfo.push(item)
      } else if (item.special === 2) {
        baseInfo.push(item)
      } else {
        more.push(item)
      }

      // 客户名称
      if (item.fieldCode === "name") {
        if (item.rules) {
          item.rules.push(stringMaxLength("客户名称"))
        } else {
          item.rules = [stringMaxLength("客户名称")]
        }
      }
      // 备注
      if (item.fieldCode === "remark") {
        if (item.rules) {
          item.rules.push(stringMaxLength("备注", 300))
        } else {
          item.rules = [stringMaxLength("备注", 300)]
        }
      }
      // 成立年份
      if (item.fieldCode === "establishTime") {
        item.disabledDate = (item: Date) => {
          return item.getTime() > Date.now()
        }
      }

      if (item.fieldCode === "email") {
        if (item.rules) {
          item.rules = [...item.rules, EMAIL_FORMAT]
        } else {
          item.rules = [EMAIL_FORMAT]
        }
      }
      // postcode-邮政编码; fax-公司传真; mobile-公司电话
      // if (["postcode", "fax", "mobile"].includes(item.fieldCode)) {
      //   if (item.rules) {
      //     item.rules = [...item.rules, validNumberFormat(item.fieldName)]
      //   } else {
      //     item.rules = [validNumberFormat(item.fieldName)]
      //   }
      // }
      if (item.fieldCode === "domainName") {
        if (item.rules) {
          item.rules = [...item.rules, validUrlFormat(item.fieldName)]
        } else {
          item.rules = [validUrlFormat(item.fieldName)]
        }
      }
    }
  })
  filedList.value.push({ title: "基础信息", fieldList: baseInfo })
  if (more.length) {
    if (isEdit.value) {
      baseInfo.push(...more)
    } else {
      filedList.value.push({
        title: "填写更多信息",
        showMore: true,
        fieldList: more
      })
    }
  }
  console.log("filedList", JSON.stringify(filedList.value))

  //编辑不显示联系人信息
  if (!isEdit.value) {
    // 封装联系人信息
    filedList.value.push(getConnectInfo())
  }
  // 封装自定义信息
  customerInfo = customerInfo.filter((item) => {
    if (item.enable === 1) {
      item.fieldValue = ""
      if (item.required === 1) {
        item.rules = [
          {
            required: true,
            message: `${item.fieldName}不能为空`,
            trigger: "blur"
          }
        ]
      }
      formData.value.fieldDefinedList.push(item)
    }
  })
  if (formData.value.fieldDefinedList.length) {
    filedList.value.push({
      title: "自定义信息",
      fieldList: [{ fieldCode: "fieldDefinedList", fieldTypeCode: "fieldDefinedList" }]
    })
  }
}

// 抽屉弹框ref DOM节点
const drawer = ref<InstanceType<typeof Drawer> | null>(null)
// 关闭抽屉弹框
const handleClose = () => {
  drawer.value?.isClose()
}
// 打开抽屉弹框
const selectOpen = () => {
  drawer.value?.isOpen()
}
// 保存数据
const confirmHandler = () => {
  if (!saveFlag.value) {
    saveFlag.value = true
    drawerLoading.value = true
    clickConfirm.value = true
    customerFromRef.value.dynamicForm.validate((valid) => {
      if (valid) {
        const data = JSON.parse(JSON.stringify(formData.value))
        // 社媒信息
        const socialList: any = []
        data.socialList.forEach((item: any) => {
          if (item.contactWay.trim()) {
            socialList.push({
              // 联系方式id
              contactWayId: "",
              // 业务id:客户id、联系人id
              businessId: props.currentDetailId || "",
              // 业务类型:1-客户、2-联系人
              businessType: 1,
              // 类型:1-手机、2-邮箱、3-社媒
              contactType: 3,
              ...item
            })
          }
        })
        // 联系人信息
        const contactList: any = {
          contactId: "",
          name: data.contactName,
          contactWayList: []
        }
        if (data.contactMobile.trim()) {
          contactList.contactWayList.push({
            // 联系方式id
            contactWayId: "",
            // 业务id:客户id、联系人id
            businessId: "",
            // 业务类型:1-客户、2-联系人
            businessType: 2,
            // 类型:1-手机、2-邮箱、3-社媒
            contactType: 1,
            contactWay: data.contactMobile
          })
        }
        if (data.contactEmail.trim()) {
          contactList.contactWayList.push({
            // 联系方式id
            contactWayId: "",
            // 业务id:客户id、联系人id
            businessId: "",
            // 业务类型:1-客户、2-联系人
            businessType: 2,
            // 类型:1-手机、2-邮箱、3-社媒
            contactType: 2,
            contactWay: data.contactEmail
          })
        }

        data.contactSocialList.forEach((item: any) => {
          if (item.contactWay.trim()) {
            contactList.contactWayList.push({
              // 联系方式id
              contactWayId: "",
              // 业务id:客户id、联系人id
              businessId: "",
              // 业务类型:1-客户、2-联系人
              businessType: 2,
              // 类型:1-手机、2-邮箱、3-社媒
              contactType: 3,
              ...item
            })
          }
        })
        // 自定义字段信息
        const fieldDefinedDataList = data.fieldDefinedList.map((item) => {
          return {
            fieldName: item.fieldName,
            fieldCode: item.fieldCode,
            fieldValue: item.fieldValue
          }
        })
        // 所在地
        // 区域code
        const region = data?.regionalSelect ? data.regionalSelect[0] : ""
        // 国家code
        const country = data?.regionalSelect ? data.regionalSelect[1] : ""
        // 省/州code
        const province = data?.regionalSelect ? data.regionalSelect[2] : ""
        // 城市code
        const city = data?.regionalSelect ? data.regionalSelect[3] : ""
        const delArr = [
          "socialList",
          "contactName",
          "contactMobile",
          "contactEmail",
          "contactSocialList",
          "regionalSelect",
          "fieldDefinedList"
        ]
        delArr.forEach((key) => {
          Reflect.deleteProperty(data, key)
        })
        // 调用接口
        if (!props.currentDetailId) {
          //校验售卖
          checkSale((addFlag: boolean) => {
            // 联系人到达上线
            if (!addFlag) {
              isContact.value = false
              saveFlag.value = false
              drawerLoading.value = false
              clickConfirm.value = false
            } else {
              // 联系人未到达上线
              //新建
              CrmCustomerAPI.addCustomer({
                ...data,
                socialList,
                contactList: [contactList],
                fieldDefinedDataList,
                region,
                country,
                province,
                city
              })
                .then((res: any) => {
                  if (res.code === "200") {
                    ElMessage.success("保存成功!")
                    drawer.value?.isClose()
                    // 当前在客户列表页面
                    microApp.forceSetData("crm", { type: "updateCustomer" }, () => {
                      //"数据已经发送完成"
                    })
                  }
                })
                .catch((err) => {
                  err.msg && ElMessage.error(err.msg)
                })
                .finally(() => {
                  saveFlag.value = false
                  drawerLoading.value = false
                })
            }
          })
        } else {
          //编辑
          CrmCustomerAPI.editCustomer({
            customerId: props.currentDetailId || "",
            ...data,
            socialList,
            contactList: [contactList],
            fieldDefinedDataList,
            region,
            country,
            province,
            city
          })
            .then((res: any) => {
              if (res.code === "200") {
                if (res?.data?.userIdChanged) {
                  if (res?.data?.changType === 1) {
                    ElMessageBox.alert(
                      `更新成功,存在域名重复数据,已自动将此数据分配给原负责人“${res?.data?.userName}”,如有问题请联系销售经理!`,
                      "提示",
                      {
                        confirmButtonText: "知道了",
                        type: "warning",
                        customClass: "myLongElMessageBox"
                      }
                    )
                  } else if (res?.data?.changType === 2) {
                    ElMessageBox.alert(
                      "更新成功,存在域名重复数据,已自动将此客户所有重复数据分配给您,请及时合并数据!",
                      "提示",
                      {
                        confirmButtonText: "知道了",
                        type: "warning"
                      }
                    )
                  }
                } else {
                  ElMessage.success("更新成功!")
                }
                drawer.value?.isClose()
                // 保存成功后通知ocs子应用更新数据
                microApp.forceSetData("crm", { type: "updateCustomer" }, () => {
                  // "数据已经发送完成"
                })
                microApp.forceSetData("ocs", { type: "updateData" }, () => {})
              }
            })
            .catch((err) => {
              err.msg && ElMessage.error(err.msg)
            })
            .finally(() => {
              saveFlag.value = false
              drawerLoading.value = false
            })
        }
      } else {
        // 数据校验失败
        // 使用$nextTick的原因是,错误提示的元素是在视图更新后出现的,不使用$nextTick获取元素是undefined
        nextTick(() => {
          elFormErrorScrollIntoView()
        })
        saveFlag.value = false
        drawerLoading.value = false
      }
      clickConfirm.value = false
    })
  }
}

const checkSale = (callback = (_val) => {}) => {
  FollowUpApi.getCanAddContact()
    .then((res: any) => {
      if (res?.code === "200") {
        if (res?.data) {
          if (res.data.addFlag) {
            callback(true)
          } else {
            let sum = res.data.licCountNum
            ElMessage({
              message: `当前联系人数量已达到上限${sum}个,请及时扩充`,
              type: "warning",
              plain: true,
              customClass: "custom-message-color"
            })
            callback(false)
          }
        }
      }
    })
    .catch((err: any) => {
      err?.msg && ElMessage.error(err?.msg)
    })
}
// 新建社媒
function addSocial(key: string) {
  const currentSocial = formData.value[key]
  currentSocial[currentSocial.length] = {
    ...SOCIAL_ITEM
  }
}
// 删除指定的社媒
function deleteSocial(key: string, index: number) {
  const currentSocial = formData.value[key]
  currentSocial.splice(index, 1)
}
//复制字段
const copyFields = (source, target) => {
  for (const key in target) {
    if (source.hasOwnProperty(key) && source[key]) {
      target[key] = source[key]
    }
  }
}
// 回显编辑的数据
const loadData = async () => {
  try {
    //编辑
    const res: any = await CrmCustomerAPI.getCustomerDetailById({
      customerId: props.currentDetailId
    })
    if (res.code === "200") {
      const resData = res?.data || null
      if (resData) {
        copyFields(resData, formData.value)
        //处理所在地
        formData.value.regionalSelect = []
        if (resData.region) {
          formData.value.regionalSelect.push(resData.region)
        }
        if (resData.country) {
          formData.value.regionalSelect.push(resData.country)
        }
        if (resData.province) {
          formData.value.regionalSelect.push(resData.province)
        }
        if (resData.city) {
          formData.value.regionalSelect.push(resData.city)
        }
        // 联系人-手机号、邮箱、社媒
        if (resData?.contactViewList?.length) {
          formData.value.contactSocialList = []
          resData.contactViewList.forEach((item) => {
            //手机
            if (item.contactType === 1) {
              formData.value.contactMobile = item.contactWay
            }
            //邮箱
            if (item.contactType === 2) {
              formData.value.contactEmail = item.contactWay
            }
            // 社媒
            if (item.contactType === 3) {
              formData.value.contactSocialList.push({
                socialType: item.socialType, // 社媒类型
                contactWay: item.contactWay, // 社媒账号
                socialUrl: item.socialUrl // 主页地址
              })
            }
          })
        } else {
          formData.value.contactMobile = ""
          formData.value.contactEmail = ""
          formData.value.contactSocialList = [JSON.parse(JSON.stringify(SOCIAL_ITEM))]
        }
        // 客户-社媒
        if (resData?.socialList?.length) {
          formData.value.socialList = []
          resData.socialList.forEach((item) => {
            // 社媒
            if (item.contactType === 3) {
              formData.value.socialList.push({
                socialType: item.socialType, // 社媒类型
                contactWay: item.contactWay, // 社媒账号
                socialUrl: item.socialUrl // 主页地址
              })
            }
          })
        } else {
          formData.value.socialList = [JSON.parse(JSON.stringify(SOCIAL_ITEM))]
        }
        // 自定义
        if (resData.fieldDefinedDataList) {
          resData.fieldDefinedDataList.forEach((item, index) => {
            formData.value.fieldDefinedList[index].fieldCode = item.fieldCode
            formData.value.fieldDefinedList[index].fieldName = item.fieldName
            formData.value.fieldDefinedList[index].fieldValue = item.fieldValue
          })
        }
      }
    }
  } catch (error: any) {
    console.error(error)
    error.msg && ElMessage.error(error.msg)
  }
}

// 向子孙组件传递方法
provide("addSocial", addSocial)
provide("deleteSocial", deleteSocial)

defineExpose({
  selectOpen
})
</script>

<style lang="scss" scoped>
// el-drawer设置
.title {
  font-family: PingFangSC-SNaNpxibold;
  font-weight: 600;
  font-size: 18px;
  color: #333333;
}
:deep(.el-drawer__close-btn) {
  color: #000000;
}
:deep(.el-drawer__header) {
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 14px;
  margin-bottom: 0px !important;
}
:deep(.el-drawer__footer) {
  padding: 0px;
}
//form
//标题
.customerInfo {
  font-family: PingFangSC-SNaNpxibold;
  font-weight: 600;
  font-size: 16px;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.line {
  width: 2px;
  height: 16px;
  background: #477fff;
  border-radius: 1px;
  margin-right: 10px;
}
//form label
:deep(.el-form-item__label) {
  font-family: PingFangSC-SNaNpxibold;
  font-weight: 600;
  font-size: 14px;
  color: #333333;
}

.more {
  padding: 2px 4px !important;
}
.error-alert {
  position: absolute;
  bottom: 55px;
  right: 0;
  width: 100%;
  height: 40px;
  text-align: start;
  background: #ffece8;
  font-weight: 400;
  font-size: 14px;
  color: #303133;
  display: flex;
  align-items: center;
  .el-icon {
    margin: 0 9px 0 17px;
  }
}
</style>

validator.ts: 

export const stringMaxLength = (msg: string, max = 50) => {
  return {
    min: 0,
    max,
    message: msg + "最多" + max + "字符",
    trigger: "blur"
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值