<template>
    <div class="add-area">
        <div class="header flex-center">
            <p>{{pageType=='edit'?'编辑':'新建'}}客户</p>
            <p>*为必填项</p>
        </div>
        <div class="content">
            <el-form ref="clueFormRef" :model="form" :rules="rules" class="flex" :label-width="125" v-loading="loadingDetail">
                <div class="left">
                    <div class='section_block'>基础信息</div>
                    <el-form-item label="客户代码：" prop="dataCode">
                        <el-input v-model="form.dataCode" disabled />
                    </el-form-item>
                    <el-form-item label="区域名称：" prop="continent">
                        <el-cascader :options="region" v-model="regionValue" clearable filterable @change="getRegion"/>
                    </el-form-item>
                    <el-form-item label="归属人员：" prop="ownerBy">
                        <div>
                            <SelectUser @onOk="selectsUser" v-model="form.ownerBy" :inputWidth='330'></SelectUser>
                        </div>
                    </el-form-item>
                    <el-form-item label="客户名称：" prop="customerName">
                        <el-input v-model="form.customerName" placeholder="请输入客户名称" />
                    </el-form-item>
                    <el-form-item label="意向产品：" prop="intendedProductsIds">
                        <SelectDict v-model="form.intendedProductsIds" placeholder="意向产品" dictCode="intended_products_type"></SelectDict>
                    </el-form-item>
                    <el-form-item label="客户状态：" prop="customerStatusDictValue">
                        <SelectDict v-model="form.customerStatusDictValue" selectedFirst placeholder="客户状态" dictCode="customer_status"></SelectDict>
                    </el-form-item>
                    <el-form-item label="客户来源：" prop="customerSourceDictValue">
                        <SelectDict v-model="form.customerSourceDictValue" placeholder="客户来源" dictCode="customer_source"></SelectDict>
                    </el-form-item>
                    <el-form-item label="客户类型：" prop="customerTypeDictValue">
                        <SelectDict v-model="form.customerTypeDictValue" placeholder="客户类型" dictCode="customer_type" @change="changeType"></SelectDict>
                    </el-form-item>
                    <el-form-item v-if='form.customerTypeDictValue=="10"' label="代理合作：" prop="cooperativeCustomerId">
                        <el-select-v2
                            v-model="form.cooperativeCustomerId"
                            :options="customerOption"
                            placeholder="请选择客户"
                            filterable
                        />
                    </el-form-item>
                    <el-form-item label="客户等级：" prop="customerLevelDictValue">
                        <SelectDict type='radio' v-model="form.customerLevelDictValue" placeholder="客户等级" dictCode="customer_level"></SelectDict>
                    </el-form-item>
                    <el-form-item label="信用等级：" prop="customerCreditLevelDictValue">
                        <SelectDict type='radio' v-model="form.customerCreditLevelDictValue" placeholder="客户信用等级" dictCode="credit_rating"></SelectDict>
                    </el-form-item>
                    <el-form-item label="经济性质：" prop="customerEconomicNatureDictValue">
                        <SelectDict v-model="form.customerEconomicNatureDictValue" placeholder="客户经济性质" dictCode="economic_nature"></SelectDict>
                    </el-form-item>
                    <el-form-item label="助记名称：" prop="mnemonicName">
                        <el-input v-model="form.mnemonicName" placeholder="请输入助记名称" />
                    </el-form-item>
                    <el-form-item label="备注信息：" prop="remark">
                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                    </el-form-item>


                    <div class='section_block'>企业信息</div>
                    <el-form-item label="企业规模：" prop="customerCompany.scaleDictValue">
                        <SelectDict v-model="form.customerCompany.scaleDictValue" placeholder="请选择企业规模" dictCode="company_scale"></SelectDict>
                    </el-form-item>
                    <!-- <el-form-item label="企业网址：" prop="customerCompany.website">
                        <el-input @input="removeSpace('website', $event)" v-model.trim="form.customerCompany.website" placeholder="请输入企业网址" />
                    </el-form-item> -->

                    <AddWebsite v-model:standbyWebsiteList="form.standbyWebsiteList" v-model="form.customerCompany.website" v-model:valueOne="form.customerCompany.website1" v-model:valueTwo="form.customerCompany.website2" v-model:valueThree="form.customerCompany.website3"></AddWebsite>

                    <el-form-item label="所属行业：" prop="customerCompany.industry">
                        <el-input v-model="form.customerCompany.industry" placeholder="请输入所属行业" />
                    </el-form-item>
                    <el-form-item label="通信地址：" prop="customerCompany.communicationAddress">
                        <el-input v-model="form.customerCompany.communicationAddress" placeholder="请输入通信地址" />
                    </el-form-item>
                    <el-form-item label="邮政编码：" prop="customerCompany.postcode">
                        <el-input v-model="form.customerCompany.postcode" placeholder="请输入邮政编码" />
                    </el-form-item>
                    <el-form-item label="传真号码：" prop="customerCompany.faxNumber">
                        <el-input v-model="form.customerCompany.faxNumber" placeholder="请输入传真号码" />
                    </el-form-item>
                    <!-- <el-form-item label="电子邮箱：" prop="customerCompany.email">
                        <el-input v-model="form.customerCompany.email" placeholder="请输入电子邮箱" />
                    </el-form-item> -->
                    <AddCompanyEmail v-model:standbyCompanyList="form.standbyCompanyList" v-model="form.customerCompany.email" v-model:valueOne="form.customerCompany.email1" v-model:valueTwo="form.customerCompany.email2" v-model:valueThree="form.customerCompany.email3"></AddCompanyEmail>

                    <el-form-item label="联系电话：" prop="customerCompany.telephone">
                        <el-input v-model="form.customerCompany.telephone" placeholder="请输入联系电话" />
                    </el-form-item>

                    <div class='section_block'>附加信息</div>

                    <CreateQuickTask v-model="form.task"></CreateQuickTask>
                </div>


                <div class="right">
                    <div class='section_block'>首要联系人</div>
                    <el-form-item label="联系人姓名：" prop="liaison.name">
                        <el-input v-model="form.liaison.name" placeholder="请输入联系人姓名" />
                    </el-form-item>
                    <el-form-item label="尊称：">
                        <SelectDict type="radio" v-model="form.liaison.call" :selectedFirst="pageType == 'add'" dictCode="call_dict_value"></SelectDict>
                    </el-form-item>
                    <el-form-item label="角色：">
                        <SelectDict v-model="form.liaison.liaisonRoleDictValue" placeholder="请选择角色" dictCode="liaison_role"></SelectDict>
                    </el-form-item>

                    <el-form-item label="生日：">
                        <el-date-picker
                            v-model="form.liaison.birthday"
                            value-format="YYYY-MM-DD"
                            type="date"
                            placeholder="请选择生日"
                        />
                    </el-form-item>

                    <el-form-item label="部门职务：" prop="liaison.departmentPosition">
                        <el-input v-model="form.liaison.departmentPosition" placeholder="请输入部门职务" />
                    </el-form-item>

                    <el-form-item label="手机号码："  prop="liaison.telephone">
                        <el-input v-model="form.liaison.telephone" placeholder="请输入手机号码" />
                    </el-form-item>

                    <!-- <el-form-item label="电子邮箱：" prop="liaison.email">
                        <el-input @input="removeSpace('email', $event)" v-model="form.liaison.email" placeholder="请输入电子邮箱" />
                    </el-form-item> -->

                    <AddLiaisonEmail v-model:standbyList="form.standbyList" v-model="form.liaison.email" v-model:valueOne="form.liaison.email1" v-model:valueTwo="form.liaison.email2" v-model:valueThree="form.liaison.email3"></AddLiaisonEmail>

                    <el-form-item label="固定电话：">
                        <el-input v-model="form.liaison.fixedLineTelephone" placeholder="请输入传真号码" />
                    </el-form-item>

                    <el-form-item label="传真号码：">
                        <el-input v-model="form.liaison.faxNumber" placeholder="请输入传真号码" />
                    </el-form-item>

                    <el-form-item label="邮政编码：">
                        <el-input v-model="form.liaison.postcode" placeholder="请输入邮政编码" />
                    </el-form-item>

                    <el-form-item label="宅电：">
                        <el-input v-model="form.liaison.homeElectricity" placeholder="请输入内容" />
                    </el-form-item>

                    <el-form-item label="QQ：">
                        <el-input v-model="form.liaison.qq" placeholder="请输入QQ" />
                    </el-form-item>

                    <el-form-item label="SKYPE：">
                        <el-input v-model="form.liaison.skype" placeholder="请输入SKYPE" />
                    </el-form-item>

                    <el-form-item label="旺旺：">
                        <el-input v-model="form.liaison.wangwang" placeholder="请输入旺旺" />
                    </el-form-item>

                    <el-form-item label="微信：">
                        <el-input v-model="form.liaison.wechat" placeholder="请输入微信" />
                    </el-form-item>
                    <el-form-item label="Twitter：">
                        <el-input v-model="form.liaison.twitter" placeholder="请输入Twitter" />
                    </el-form-item>

                    <el-form-item label="Linkedin：">
                        <el-input v-model="form.liaison.linkedin" placeholder="请输入Linkedin" />
                    </el-form-item>

                    <el-form-item label="Facebook：">
                        <el-input v-model="form.liaison.facebook" placeholder="请输入Facebook" />
                    </el-form-item>
                    <el-form-item label="Whatsapp：">
                        <el-input v-model="form.liaison.whatsapp" placeholder="请输入Whatsapp" />
                    </el-form-item>

                    <el-form-item label="所在地区：">
                        <el-input v-model="form.liaison.internationalArea" placeholder="请输入所在地区" />
                    </el-form-item>

                    <el-form-item label="备注信息：">
                        <el-input v-model="form.liaison.remark" type="textarea" placeholder="请输入内容" />
                    </el-form-item>


                    <div class='section_block'>财务信息</div>
                    <el-form-item label="开户行：" prop="openingBank">
                        <el-input v-model="form.openingBank" placeholder="请输入开户行" />
                    </el-form-item>
                    <el-form-item label="税号：" prop="taxNumber">
                        <el-input v-model="form.taxNumber" placeholder="请输入税号" />
                    </el-form-item>
                    <el-form-item label="银行账号：" prop="bankAccount">
                        <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <div class="footer flex">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{pageType=='edit'?'提交':'新建客户'}}</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('continue')" v-if="pageType!='edit'">提交后继续创建</el-button>
            <el-button @click="reset">重置</el-button>
        </div>
    </div>

    <el-dialog title="温馨提示" v-model="visible" width="1250px" class="rule-dialog">
        <p style="margin-bottom:8px">您{{pageType=='edit'?'编辑':isCreate?'添加':'创建'}}的客户与以下资料触发查重，{{ isCreate ? '若继续创建，以下查重结果归属人将同步收到查重消息提醒，请确认后提交' : '暂无法变更，可与以下查重结果归属人进一步沟通客户归属问题' }}</p>
        <el-table
            :data="ruleData"
            height="100%"
        >
            <el-table-column align="center" label="名称" prop="customerName">
                <template #default="scope">
                    <el-tag :type="scope.row.resourceType=='10'?'':scope.row.resourceType=='11'?'success':'warning'">{{ scope.row.resourceType=='10'?'客户':scope.row.resourceType=='11'?'线索':'联系人' }}</el-tag>
                    <span style="margin-left: 4px;">{{ scope.row.customerName }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="联系人姓名" prop="name"></el-table-column> -->
            <!-- <el-table-column align="center" label="邮箱" prop="email"></el-table-column> -->
            <el-table-column align="center" label="归属人" prop="ownerByName">
                <template #default="scope">
                    <span>{{ scope.row.ownerByName?scope.row.ownerByName:'公海' }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="最后跟进" prop="lastFollowUpTime"></el-table-column> -->
            <el-table-column align="center" label="未跟进天数" prop="noFollowUpDate"></el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime"></el-table-column>
            <el-table-column align="center" label="重复字段" prop="duplicateFieldNow">
                <template #default="scope">
                    <span style="color: #f56c6c;">{{ scope.row.duplicateFieldNow }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="重复值" prop="createTime">
                <template #default="scope">
                    <span style="color: #f56c6c;">{{ scope.row.duplicateValue }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="查重字段" prop="errorMsg">
                <template #default="scope">
                    <span style="color: #f56c6c;">{{ scope.row.errorMsg }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="查重值" prop="duplicateValueNow">
                <template #default="scope">
                    <span style="color: #f56c6c;">{{ scope.row.duplicateValueNow }}</span>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="visible = false">{{ isCreate ? '取消' : '关闭' }}</el-button>
                <el-button v-if="isCreate" :loading="buttonLoading" type="primary" @click="save">立即创建</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="addCustomer">
    import {useDictCache} from '@/hooks/web/useDict'
    import { addCustomer, getCustomer, updateCustomer,generateBizCode, checkCustomer,listCustomer } from '@/api/customer';
    import { CustomerQuery, CustomerForm } from '@/api/customer/types';
    import { listRole } from '@/api/system/role';
    import { AxiosResponse } from 'axios'
    import { RoleVO } from '@/api/system/role/types';
    // import SelectUser from '@/components/SelectOrg/SelectUser.vue'
    import {region} from '@/utils/region';
    import { listDetialByCodes } from "@/api/system/dict/";
    import CreateQuickTask from '@/components/common/createQuickTask.vue';
    import AddLiaisonEmail from '@/components/common/addLiaisonEmail.vue';
    import AddCompanyEmail from '@/components/common/addCompanyEmail.vue';
    import AddWebsite from '@/components/common/addWebsite.vue';
    import useUserStore from '@/store/modules/user';
    import useTagsViewStore from "@/store/modules/tagsView";
    const tagsViewStore = useTagsViewStore()
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    const { queryDictDetailByCodes } = useDictCache(['customer_status',
        'customer_type','customer_source','economic_nature',
        'company_scale','customer_level','credit_rating',
        'task_remind_type','liaison_role',
        'intended_products_type','task_mark_tag',
        'task_priority_grade','task_remind_mode', 'call_dict_value'])
    queryDictDetailByCodes()
    const loadingDetail = ref(false)
    const router: any = useRouter();
    const route = useRoute();
    let queryData = router.currentRoute.value.query
    const regionValue = ref([])
    const getRegion = (value) => {
        if(value){
            form.value.continent = value[0]
            form.value.country = value[1]
        }

    }


    interface selectTypes {
        label: '',
        value?: string | number
    }

    const buttonLoading = ref(false);

    const { userInfo } = useUserStore();
    const initFormData: CustomerForm = {
        customerForm: 10,
        customerName: '',
        ownerByName: '',
        ownerBy:userInfo.id,
        bankAccount: '',
        continent: '',
        country: '',
        dataCode: '',
        customerCreditLevelDictValue: '',
        customerEconomicNatureDictValue: '',
        customerLevelDictValue: '',
        customerSourceDictValue: '',
        customerStatusDictValue: '',
        customerTypeDictValue: '',
        hasFromClue: false,
        hasPublicCustomer: false,
        intendedProductsIds: '',
        intendedProductsNames: '',
        mnemonicName: '',
        openingBank: '',
        remark: '',
        taxNumber: '',
        followUpTime:'',
        cooperativeCustomerId:'',
        liaison: {
            name: '',
            call: 0,
            liaisonRoleDictValue: '',
            departmentPosition: '',
            address: '',
            birthday:'',
            email: '',
            email1:'',
            email2:'',
            email3:'',
            linkedin: '',
            facebook: '',
            whatsapp: '',
            telephone: '',
            twitter: '',
            faxNumber: '',
            postcode: '',
            qq: '',
            skype: '',
            wangwang: '',
            wechat: '',
            hasPrimaryLialison: true,
            remark:'',
        },
        customerCompany: {
            name: '',
            address: '',
            communicationAddress: '',
            customerId: 0,
            email: '',
            faxNumber: '',
            industry: '',
            postcode: '',
            scaleDictValue: '',
            telephone: '',
            website: '',
            website1: '',
            website2: '',
            website3: '',
        },
        task:{
            taskBeginTime: '',
            taskContent: '',
            objectiveValue:'',
            remindModels: ['site'],
            remindType: '',
            ownerBy: ''
        },
        standbyList: [{label:'联系人邮箱',value:''},{label:'联系人备用邮箱',value:''}],
        standbyCompanyList: [{label:'企业邮箱',value:''},{label:'企业备用邮箱',value:''}],
        standbyWebsiteList: [{label:'企业网址',value:''},{label:'企业备用网址',value:''}],
    }

    const changeType = (val:any)=>{
        if(val==10){
            getCustomerData()
        }else{
            form.value.cooperativeCustomerId=''
            form.value.cooperativeCustomerName=''
        }
    }

    const removeSpace = (type: string, value: string) => {
        let showValue = value.replace(/\s+/g, '')
        if(type == 'website') {
            form.value.customerCompany.website = showValue
        }else if(type=='email'){
            form.value.liaison.email = showValue
        }
    }

    // 获取客户列表数据
    const customerOption = ref([])
    const getCustomerData = () => {
        listCustomer({ pageIndex: 1, pageSize: 999999, customerTypeDictValue:'5', commonScope: 1, commonScopeType: '10' }).then(res => {
            if(res.success) {
                customerOption.value = res.result.records.map((item: { customerName: string, id: number|string }) => {
                    let obj = { label: item.customerName, value: item.id as string}
                    return obj
                })
            }
        })
    }
    const data = reactive<PageData<CustomerForm, CustomerQuery>>({
        form: { ...initFormData },
        rules: {
            continent: [
                { required: true, message: "区域名称不能为空", trigger: "change" }
            ],
            customerName: [
                { required: true, message: "客户名称不能为空", trigger: "blur" }
            ],
            customerStatusDictValue: [
                { required: true, message: "请选择客户状态", trigger: "blur" }
            ],
            cooperativeCustomerId: [
                { required: true, message: "请选择代理合作的客户", trigger: "blur" }
            ],
            customerSourceDictValue: [
                { required: false, message: "请选择客户来源", trigger: "blur" }
            ],
            customerEconomicNatureDictValue: [
                { required: false, message: "请选择经济性质", trigger: "blur" }
            ],
            'liaison.name': [
                { required: true, message: "联系人姓名不能为空", trigger: "blur" }
            ],
            'task.taskBeginTime': [
                { required: true, message: "请选择跟进时间", trigger: "change" }
            ],
            'task.taskContent': [
                { required: true, message: "请填写跟进主题", trigger: "blur" }
            ],
            'task.objectiveValue': [
                { required: true, message: "任务目的不能为空", trigger: "change" }
            ],
            'task.remindType': [
                { required: true, message: "任务提醒不能为空", trigger: "change" }
            ],
            'task.ownerBy': [
                { required: true, message: "请选择跟进人员", trigger: "blur" }
            ],
            ownerBy: [
                { required: !(queryData.form == 'public' || queryData.form == 'rubbish'), message: "归属人员不能为空", trigger: "blur" }
            ],

        }
    });

    const { form, rules } = toRefs(data);

    const ownerByName = ref()
    const selectsUser = (data: { realName: string,id:number|string }[]) => {
        form.value.ownerByName = data[0].realName
        form.value.ownerBy = data[0].id
    }

    /** 表单重置 */
    const clueFormRef = ref()
    const reset = () => {
        regionValue.value = []
        form.value = {...initFormData};
        clueFormRef.value?.resetFields();
        form.value.dataCode = dataCode.value
        form.value.standbyList= [{label:'联系人邮箱',value:''},{label:'联系人备用邮箱',value:''}]
        form.value.standbyCompanyList= [{label:'企业邮箱',value:''},{label:'企业备用邮箱',value:''}]
        form.value.standbyWebsiteList= [{label:'企业网址',value:''},{label:'企业备用网址',value:''}]
    }

    // 获取客户code
    const dataCode = ref()
    const getCode = ()=>{
        generateBizCode({bizTypeCode:10}).then((res: AxiosResponse) => {
            if(res.success) {
                if(res.code==200){
                    dataCode.value = res.result
                    form.value.dataCode = res.result
                }
            }
        })
    }

    // 编辑时查数据
    const pageType = ref()
    const catchId = ref()
    const getDetail = ()=>{
        let refreshQuery = router.currentRoute.value.query
        let id: string = proxy?.$route?.query?.id as string
        pageType.value = proxy?.$route.query.type
        if(proxy?.$route.query.type == 'edit' ){
            if(catchId.value ==id){
                return
            }
            catchId.value = id
            tagsViewStore.editeTitle(route.path, '编辑客户')
            reset()
            catchId.value = id
            loadingDetail.value = true
            getCustomer(id,queryData.scopeMenuId).then((res) => {
                if(res.success) {
                    form.value.standbyList[0].value = res.result.liaison.email
                    form.value.standbyList[1].value = res.result.liaison.email1
                    res.result.customerCompany = res.result.customerCompany || {}
                    form.value.standbyCompanyList[0].value = res.result.customerCompany?res.result.customerCompany.email:''
                    form.value.standbyCompanyList[1].value = res.result.customerCompany?res.result.customerCompany.email1:''
                    form.value.standbyWebsiteList[0].value = res.result.customerCompany?res.result.customerCompany.website:''
                    form.value.standbyWebsiteList[1].value = res.result.customerCompany?res.result.customerCompany.website1:''
                    const otherEmails = [
                        { label: '联系人备用邮箱', value: res.result.liaison?res.result.liaison.email2:'' },
                        { label: '联系人备用邮箱', value: res.result.liaison?res.result.liaison.email3:'' }
                    ];
                    const otherEmailsCompany = [
                        { label: '企业备用邮箱', value: res.result.customerCompany?res.result.customerCompany.email2:'' },
                        { label: '企业备用邮箱', value: res.result.customerCompany?res.result.customerCompany.email3:'' }
                    ];
                    const otherWebsiteCompany = [
                        { label: '企业备用网址', value: res.result.customerCompany?res.result.customerCompany.website2:'' },
                        { label: '企业备用网址', value: res.result.customerCompany?res.result.customerCompany.website3:'' }
                    ];
                    otherEmails.forEach((emailObj) => {
                        if (emailObj.value) {
                            form.value.standbyList.push(emailObj);
                        }
                    });
                    otherEmailsCompany.forEach((emailObj) => {
                        if (emailObj.value) {

                            form.value.standbyCompanyList.push(emailObj);
                        }
                    });
                    otherWebsiteCompany.forEach((emailObj) => {
                        if (emailObj.value) {
                            form.value.standbyWebsiteList.push(emailObj);
                        }
                    });
                    dataCode.value = res.result.dataCode
                    Object.assign(form.value, res.result);
                    regionValue.value = [form.value.continent,form.value.country]
                    form.value.liaison.call = String(form.value.liaison.call)
                    changeType(form.value.customerTypeDictValue)
                }
                loadingDetail.value = false
            })
        }else{
            if(queryData.email){
                form.value.standbyList[0].value = queryData.email
                form.value.liaison.email = queryData.email
            }
            tagsViewStore.editeTitle(route.path, '创建客户')
            if(catchId.value){
                reset()
            }
            catchId.value = undefined
            getCode()
            if(refreshQuery.checkValue){  //查重后带过来的值
                if(refreshQuery.checkSecond!='undefined'){
                    form.value[refreshQuery.checkFrist][refreshQuery.checkSecond]=refreshQuery.checkValue
                    if(refreshQuery.checkFrist=='customerCompany'&&refreshQuery.checkSecond=='website'){
                        form.value.standbyWebsiteList[0].value = refreshQuery.checkValue
                    }else if(refreshQuery.checkFrist=='customerCompany'&&refreshQuery.checkSecond=='email'){
                        form.value.standbyCompanyList[0].value = refreshQuery.checkValue
                    }else if(refreshQuery.checkFrist=='liaison'&&refreshQuery.checkSecond=='email'){
                        form.value.standbyList[0].value = refreshQuery.checkValue
                    }
                }else{
                    form.value[refreshQuery.checkFrist]=refreshQuery.checkValue
                }
            }
        }
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row?: CustomerForm) => {
        reset();
    }

    /** 提交按钮 */
    const visible = ref(false)
    const ruleData = ref([])
    const isCreate = ref(false)
    const isContinue = ref('')
    const submitForm = (val:any) => {
        clueFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                let emailFlag = true
                for(let i = 0; i < 4; i++) {
                    for(let j = 0; j < 4; j++) {
                        if(form.value.customerCompany['email' + (i == 0 ? '' : i)] &&
                            form.value.customerCompany['email' + (i == 0 ? '' : i)] == form.value.liaison['email' + (j == 0 ? '' : j)]) {
                            emailFlag = false
                        }
                    }
                }
                if(!emailFlag) {
                    ElMessage.error('联系人邮箱不能与企业邮箱相同')
                    return false
                }
                buttonLoading.value = true;
                isContinue.value = val
                checkCustomer(form.value).then(async res => {
                    if(res.success) {
                        isCreate.value = true
                        if(res.result) { // 有重复可以创建
                            openDialog(res.result)
                        }else{ // 没有重复
                            save()
                        }
                    }else{ //有重复且不能创建
                        isCreate.value = false
                        openDialog(res.result)
                    }
                }).finally(() => {
                    buttonLoading.value = false;
                })
            }
        });
    }

    const errorCanSaveVOList = ref([])
    const openDialog = (data) => {
        errorCanSaveVOList.value = data
        ruleData.value = (data || []).map(item => {
            let obj = { ...item.object, 
                errorMsg: item.errorMsg,
                duplicateValue: item.duplicateValue,
                resourceType: item.resourceType,
                name: item.name,
                customerName: item.customerName,
                createTime: item.createTime,
                lastFollowUpTime: item.lastFollowUpTime,
                noFollowUpDate: item.noFollowUpDate,
                duplicateFieldNow: item.duplicateFieldNow,
                duplicateValueNow: item.duplicateValueNow,
                ownerByName: item.ownerByName,
            }
            return obj
        })
        visible.value = true
    }

    const save = async () => {
        let id = null
        if(errorCanSaveVOList.value.length != 0) {
            form.value.errorCanSaveVOList = errorCanSaveVOList.value
        }
        if (pageType.value=='edit') {
            await updateCustomer(form.value).finally(() => buttonLoading.value = false);
            id = form.value.id
            ElMessage.success("编辑成功");
            buttonLoading.value = false;
            visible.value = false
        } else {
            await addCustomer(form.value).then(res => {
                if(res.success) {
                    id = res.result
                }
            }).finally(() => buttonLoading.value = false);
            ElMessage.success("新增成功");
            buttonLoading.value = false;
            visible.value = false
        }
        if(isContinue.value=='continue'){
            clueFormRef.value?.resetFields();
            regionValue.value = []
            getCode()

        }else{
            reset()
            router.pushTarget('/customer/customerDetail?id='+id)
        }
    }
    onActivated(()=>{
        getDetail()
    })
    onMounted(() => {
        getDetail()
    })
</script>
<style lang="scss" scoped>
.section_block{
    border-left: 4px solid #1874FF;
    padding: 4px 0 4px 10px;
    font-weight: bold;
    margin-bottom: 20px;
    background-color: #1874ff0d;
}
.el-date-editor.el-input .el-input__wrapper {
	width: 100% !important;
}
.rule-dialog{
    .el-table{
        margin-bottom: 10px;
        border: var(--el-table-border);
        border-bottom: 0;
        :deep(.el-table__header){
            th{
                background-color: #F8FAFC;
                color: #262626;
            }
        }
    }
    p{
        margin-bottom: 10px;
        color: #f56c6c;
        font-size: 16px;
        font-weight: bold
    }
}
:deep(.createQuickTask){
    .el-form-item{
        .el-date-editor, .el-input, .sle-user-el-input {
            width: 330px !important;
            flex-grow: initial !important;
        }
    }
}
</style>
