<template>
    <div class="add-area">
        <div class="header flex-center">
            <p>{{ routerData.type == 'edit' ? '编辑' : '添加' }}联系人</p>
            <p>*为必填项</p>
        </div>
        <div class="content">
            <el-form ref="clueFormRef" :model="form" :rules="rules" class="flex" :label-width="125">
                <div class="left">
                    <el-form-item label="联系人姓名：" prop="name">
                        <el-input v-model="form.name" placeholder="请输入联系人姓名" />
                    </el-form-item>

                    <el-form-item label="尊称：" prop="call">
                        <SelectDict type="radio" v-model="form.call" :selectedFirst="routerData.type == 'add'" dictCode="call_dict_value"></SelectDict>
                    </el-form-item>

                    <el-form-item label="角色：" prop="liaisonRoleDictValue">
                        <SelectDict v-model="form.liaisonRoleDictValue" placeholder="请选择角色" dictCode="liaison_role"></SelectDict>
                    </el-form-item>

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

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

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

                    <!-- <el-form-item label="电子邮箱：" prop="email">
                        <el-input v-model.trim="form.email" placeholder="请输入电子邮箱" />
                    </el-form-item> -->
                    <AddLiaisonEmail v-model:standbyList="form.standbyList" v-model="form.email" v-model:valueOne="form.email1" v-model:valueTwo="form.email2" v-model:valueThree="form.email3"></AddLiaisonEmail>

                    <el-form-item label="客户/线索：" prop="customerForm" class="resource-item">
                        <el-select v-model="form.customerForm" placeholder="选择客户/线索" @change="changeCustomer">
                            <el-option label="客户" value="10"></el-option>
                            <el-option label="线索" value="11"></el-option>
                        </el-select>
                        <paginationSelect
                            style="margin-left: 10px"
                            v-model="form.customerId"
                            placeholder="选择"
                            :selectedName="form.customerName"
                            source="liaison-customer"
                            :listFn="listCustomer"
                            :params="customerParams"
                            :isRemote="!!form.customerForm"
                        />
                    </el-form-item>

                    <el-form-item label="商机/订单：" prop="resourceType" class="resource-item">
                        <el-select v-model="form.resourceType" placeholder="选择商机/订单" clearable @change="changeResource">
                            <el-option label="商机" value="30"></el-option>
                            <el-option label="订单" value="40"></el-option>
                        </el-select>
                        <paginationSelect
                            style="margin-left: 10px"
                            v-model="form.resourceTypeId"
                            placeholder="选择"
                            queryName="title"
                            searchName="title"
                            :selectedName="form.resourceName"
                            source="liaison-resource"
                            :listFn="form.resourceType == '40' ? listOrderForm : listAllBusiness"
                            :params="resoruceParams"
                            :isRemote="!!form.resourceType"
                        />
                    </el-form-item>

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

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

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

                    <CreateQuickTask v-model="form.task" />
                </div>
                <div class="right">
                    <el-form-item label="QQ：" prop="qq">
                        <el-input v-model="form.qq" placeholder="请输入QQ" />
                    </el-form-item>

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

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

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

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

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

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

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

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

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

                    <!-- <el-form-item label="详细地址：" prop="address">
                        <el-input v-model="form.address" placeholder="请输入详细地址" />
                    </el-form-item> -->

                    <el-form-item label="所在地区：" prop="internationalArea">
                        <el-input v-model="form.internationalArea" placeholder="请输入所在地区" />
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <div class="footer flex">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('')">提交</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('continue')" v-if="routerData.type!='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">您{{ routerData.type == 'edit' ? '编辑' : isCreate?'添加':'创建' }}的联系人与以下资料触发查重，{{ isCreate ? '若继续创建，以下查重结果归属人将同步收到查重消息提醒，请确认后提交' : '暂无法变更，可与以下查重结果归属人进一步沟通联系人归属问题' }}</p>
        <el-table
            :data="ruleData"
            height="100%"
        >
            <el-table-column align="center" label="名称" prop="name">
                <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.resourceType=='20'?scope.row.name:scope.row.customerName }}</span>
                </template>
            </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="addliaison">
    import { getLiaison, addLiaison } from '@/api/customer/liaison';
    import { LiaisonQuery, LiaisonForm } from '@/api/customer/liaison/types';
    import { listAllBusiness } from '@/api/business/allBusiness'
    import { listOrderForm } from '@/api/orderForm'
    import { listCustomer } from '@/api/customer';
    import { useDictCache } from '@/hooks/web/useDict'
    import CreateQuickTask from '@/components/common/createQuickTask.vue';
    import { singleCheckCustomer } from '@/api/customer';
    import useTagsViewStore from "@/store/modules/tagsView";
    import AddLiaisonEmail from '@/components/common/addLiaisonEmail.vue';
    import paginationSelect from '@/components/common/paginationSelect.vue';
    const tagsViewStore = useTagsViewStore()

    const router: any = useRouter();
    const route = useRoute();
    let routerData = router.currentRoute.value.query
    const { queryDictDetailByCodes } = useDictCache([
        'liaison_role',
        'task_remind_type',
        'task_remind_mode',
        'task_mark_tag',
        'task_priority_grade',
        'call_dict_value'
    ])
    queryDictDetailByCodes()

    const buttonLoading = ref(false);

    const initFormData: LiaisonForm = {
        id: undefined,
        customerId: routerData?.customerId,
        hasPrimaryLialison: undefined,
        name: undefined,
        call: undefined,
        liaisonRoleDictValue: undefined,
        birthday: undefined,
        departmentPosition: undefined,
        telephone: undefined,
        email: undefined,
        email1: undefined,
        email2: undefined,
        email3: undefined,
        resourceType: routerData?.resourceType,
        resourceTypeId: routerData?.resourceTypeId,
        faxNumber: undefined,
        postcode: undefined,
        contactInformation: undefined,
        remark: undefined,
        qq: undefined,
        skype: undefined,
        wangwang: undefined,
        wechat: undefined,
        twitter: undefined,
        linkedin: undefined,
        facebook: undefined,
        whatsapp: undefined,
        address: undefined,
        homeElectricity: undefined,
        internationalArea: undefined,
        customerForm: undefined,
        task: {
            isCreateTask: false,

        },
        standbyList: [{label:'联系人邮箱',value:''},{label:'联系人备用邮箱',value:''}],
    }
    const validateCustomerForm = (rule: any, value: any, callback: any) => {
        if(!value) return callback(new Error('客户/线索不能为空'))
        if(!form.value.customerId) {
            return callback(new Error(`请选择具体的${ value == 10 ? '客户' : '线索' }`))
        }
        callback()
    }
    const data = reactive<PageData<LiaisonForm, LiaisonQuery>>({
        form: { ...initFormData },
        rules: {
            name: [
                { required: true, message: "联系人姓名不能为空", trigger: "blur" }
            ],
            'task.taskBeginTime': [
                { required: true, message: "下次跟进时间不能为空", trigger: "blur" }
            ],
            'task.ownerBy': [
                { required: true, message: "跟进人员不能为空", trigger: "blur" }
            ],
            'task.objectiveValue': [
                { required: true, message: "任务目的不能为空", trigger: "change" }
            ],
            'task.remindType': [
                { required: true, message: "任务提醒不能为空", trigger: "change" }
            ],
            'task.taskContent': [
                { required: true, message: "任务主题不能为空", trigger: "blur" }
            ],
            customerForm: [
                { required: true, validator: validateCustomerForm, trigger: "blur" }
            ]
        }
    });

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

    let resoruceParams = {
        commonScope: 1,
        commonScopeType: '',
    }
    const changeResource = (val: string) => {
        form.value.resourceTypeId = ''
        resoruceParams.commonScopeType = val
    }

    let customerParams = {
        customerForm: '',
        hasPublicCustomer: 0,
        hasGarbageCustomer: 0,
        commonScope: 1,
        commonScopeType: '',
        id: routerData.customerId,
        customerName: ''
    }
    const changeCustomer = (val: string) => {
        form.value.customerId = ''
        customerParams.customerForm = val
        customerParams.commonScopeType = val
    }

    const initLiaison = ()=>{
        if(routerData.customerId) {
            form.value.customerForm = routerData.customerForm || '10'
            customerParams.id = routerData.customerId
            changeCustomer(form.value.customerForm)
            form.value.customerId = routerData.customerId
        }
        if(routerData.resourceType) {
            form.value.resourceType = routerData.resourceType
            changeResource(routerData.resourceType)
            form.value.resourceTypeId = routerData.resourceTypeId
        }
        if(routerData.email) {
            form.value.standbyList[0].value = routerData.email
            form.value.email = routerData.email
        }
        if(routerData.resourceName) {
            form.value.resourceName = routerData.resourceName
        }
    }
    const catchId = ref()
    const getDetailData = () => {
        routerData = router.currentRoute.value.query
        if(routerData.type == 'edit') {
            if(catchId.value == routerData.id) {
                return
            }
            catchId.value = routerData.id
            tagsViewStore.editeTitle(route.path, '编辑联系人')
            reset()
            getLiaison(routerData.id).then(res => {
                if(res.success) {
                    form.value.standbyList[0].value = res.result.email
                    form.value.standbyList[1].value = res.result.email1
                    const otherEmails = [
                        { label: '联系人备用邮箱', value: res.result.email2 },
                        { label: '联系人备用邮箱', value: res.result.email3 }
                    ]
                    otherEmails.forEach((emailObj) => {
                        if (emailObj.value) {
                            form.value.standbyList.push(emailObj);
                        }
                    });
                    res.result.customerForm = res.result.customerForm ? String(res.result.customerForm) : '' //下拉框是字符串类型
                    changeCustomer(res.result.customerForm)
                    if(res.result.resourceType) {
                        changeResource(res.result.resourceType)
                    }
                    Object.assign(form.value, res.result);
                    form.value.call = String(form.value.call)
                }
            })
        }else{
            if(catchId.value) {
                reset()
            }
            catchId.value = undefined
            tagsViewStore.editeTitle(route.path, '添加联系人')
            initLiaison()
        }
    }

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


    const visible = ref(false)
    const ruleData = ref([])
    const isCreate = ref(false)
    const isContinue = ref('')
    /** 提交按钮 */
    const submitForm = (val?:string) => {
        clueFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                isContinue.value = val
                let params: any = {
                    fieldCode:'liaison.email',
                    email:form.value.email,
                    email1:form.value.email1,
                    email2:form.value.email2,
                    email3:form.value.email3,
                    customerForm:'10'
                }
                if(routerData.type == 'edit') {
                    params.id = routerData.id
                }
                singleCheckCustomer(params).then(async res => {
                    if(res.success) {
                        isCreate.value = true
                        if(res.result) { // 有重复可以创建
                            buttonLoading.value = false;
                            openDialog(res.result)
                        }else{ // 没有重复
                            save()
                        }
                    }else{ //有重复且不能创建
                        isCreate.value = false
                        buttonLoading.value = false;
                        openDialog(res.result)
                    }
                })
            }
        });
    }

    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 () => {
        if(errorCanSaveVOList.value.length != 0) {
            form.value.errorCanSaveVOList = errorCanSaveVOList.value
        }
        await addLiaison(form.value).finally(() => buttonLoading.value = false);
        ElMessage.success(routerData.type == 'edit'?"编辑成功":"新增成功");
        visible.value = false
        if(isContinue.value=='continue'){
            reset()
            initLiaison()
        }else{
            router.push('../liaison')
        }
    }

    onMounted(()=>{
        getDetailData()
    })

    onActivated(() => {
        getDetailData()
    })
</script>

<style scoped lang="scss">
    .resource-item{
        :deep(.el-select) {
            width: 160px!important;
        }
    }
    .rule-dialog{
        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>
