<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="customerName">
                        <el-input v-model="form.customerName" placeholder="请输入线索名称" />
                    </el-form-item>

                    <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="routerData.type == '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-input v-model="form.liaison.departmentPosition" placeholder="请输入部门职务" />
                    </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="详细地址：">
                        <el-input v-model="form.liaison.address" placeholder="请输入详细地址"/>
                    </el-form-item>

                    <el-form-item label="线索来源：">
                        <SelectDict v-model="form.customerSourceDictValue" placeholder="请选择线索来源" dictCode="customer_source"></SelectDict>
                    </el-form-item>

                    <el-form-item label="线索状态：" prop="clueStatusDictValue">
                        <SelectDict v-model="form.clueStatusDictValue" placeholder="请选择线索状态" dictCode="clue_status"></SelectDict>
                    </el-form-item>

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

                    <el-form-item label="归属人员：" v-if="routerData.hasPublicCustomer != 1" prop="ownerBy">
                        <SelectUser v-model="form.ownerBy" placeholder="归属人员"></SelectUser>
                    </el-form-item>

                    <CreateQuickTask v-model="form.task" />
                </div>
                <div class="right">
                    <!-- <el-form-item label="企业网址：" prop='customerCompany.website'>
                        <el-input @input="removeSpace('website', $event)" v-model.trim="form.customerCompany.website" placeholder="请输入企业网址" />
                    </el-form-item>
                    <el-form-item label="企业邮箱：" prop='customerCompany.email'>
                        <el-input @input="removeSpace('companyEmail', $event)" v-model.trim="form.customerCompany.email" placeholder="请输入企业电子邮箱" />
                    </el-form-item>

                    <el-form-item label="电子邮箱：" prop="liaison.email">
                        <el-input @input="removeSpace('email', $event)" v-model.trim="form.liaison.email" 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>
                    <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>
                    <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="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.telephone" placeholder="请输入手机号码" />
                    </el-form-item>

                    <el-form-item label="固定电话：">
                        <el-input v-model="form.liaison.fixedLineTelephone" 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="传真号码：">
                        <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>
                </div>
            </el-form>
        </div>
        <div class="footer flex">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</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="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 name="addClue" lang="ts">
    import { addCustomer, getCustomer, updateCustomer, checkCustomer } from '@/api/customer';
    import { CustomerQuery, CustomerForm } from '@/api/customer/types';
    import { AxiosResponse } from 'axios'
    // import SelectUser from '@/components/SelectOrg/SelectUser.vue'
    import { region } from '@/utils/region';
    import { useDictCache } from '@/hooks/web/useDict'
    import CreateQuickTask from '@/components/common/createQuickTask.vue';
    import useUserStore from '@/store/modules/user';
    import useTagsViewStore from "@/store/modules/tagsView";
    import AddLiaisonEmail from '@/components/common/addLiaisonEmail.vue';
    import AddCompanyEmail from '@/components/common/addCompanyEmail.vue';
    import AddWebsite from '@/components/common/addWebsite.vue';
    const tagsViewStore = useTagsViewStore()

    const { queryDictDetailByCodes } = useDictCache([
        'customer_source',
        'clue_status',
        'liaison_role',
        'task_remind_type',
        'task_remind_mode',
        'task_mark_tag',
        'task_priority_grade',
        'call_dict_value'
    ])
    queryDictDetailByCodes()

    const router: any = useRouter();
    const route = useRoute();
    let routerData = router.currentRoute.value.query

    const regionValue = ref<string[]>([])
    const getRegion = (value: string[]) => {
        if(value){
            form.value.continent = value[0]
            form.value.country = value[1]
        }
    }

    const buttonLoading = ref(false);
    const { userInfo } = useUserStore();
    const initFormData: CustomerForm = {
        liaison: {
            name: undefined,
            call: undefined,
            liaisonRoleDictValue: '',
            departmentPosition: '',
            address: '',
            email: '',
            email1: '',
            email2: '',
            email3: '',
            linkedin: '',
            facebook: '',
            whatsapp: '',
            telephone: '',
            twitter: '',
            faxNumber: '',
            postcode: '',
            qq: '',
            skype: '',
            wangwang: '',
            wechat: '',
            hasPrimaryLialison: true,
            fixedLineTelephone: '',
            homeElectricity: '',
        },
        hasPublicCustomer: routerData.hasPublicCustomer == 1,
        customerCompany: {
            website: '',
            website1: '',
            website2: '',
            website3: '',
            email: '',
            email1: '',
            email2: '',
            email3: '',
        },
        customerName: undefined,
        ownerBy: routerData.hasPublicCustomer == 1 ? '' : userInfo.id,
        customerForm: 11,
        task: {},
        standbyList: [{label:'联系人邮箱',value:''},{label:'联系人备用邮箱',value:''}],
        standbyCompanyList: [{label:'企业邮箱',value:''},{label:'企业备用邮箱',value:''}],
        standbyWebsiteList: [{label:'企业网址',value:''},{label:'企业备用网址',value:''}],
    }

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

    const data = reactive<PageData<CustomerForm, CustomerQuery>>({
        form: { ...initFormData },
        rules: {
            customerName: [
                { required: true, message: "线索名称不能为空", trigger: "blur" }
            ],
            clueStatusDictValue: [
                { required: true, message: "线索状态不能为空", trigger: "change" }
            ],
            'liaison.name': [
                { required: true, message: "联系人姓名不能为空", trigger: "blur" }
            ],
            continent: [
                { required: true, message: "区域名称不能为空", trigger: "change" }
            ],
            'task.taskBeginTime': [
                { required: true, message: "下次跟进时间不能为空", trigger: "change" }
            ],
            'task.ownerBy': [
                { required: true, message: "跟进人员不能为空", trigger: "blur" }
            ],
            'task.taskContent': [
                { required: true, message: "跟进内容不能为空", trigger: "blur" }
            ],
            'task.remindType': [
                { required: true, message: "任务提醒不能为空", trigger: "change" }
            ],
            'task.objectiveValue': [
                { required: true, message: "任务目的不能为空", trigger: "change" }
            ],
            ownerBy: [
                { required: routerData.hasPublicCustomer != 1, message: "归属人员不能为空", trigger: "blur" }
            ],
        }
    });

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

    // 编辑时查数据
    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()
            getCustomer(routerData.id).then((res: AxiosResponse) => {
                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);
                        }
                    });
                    Object.assign(form.value, res.result);
                    if(form.value.continent && form.value.country) {
                        regionValue.value = [form.value.continent, form.value.country]
                    }
                    form.value.liaison.call = String(form.value.liaison.call)
                    form.value.customerCompany = form.value.customerCompany || { website: '',email:'' }
                }
            })
        }else {
            if(catchId.value) {
                reset()
            }
            catchId.value = undefined
            tagsViewStore.editeTitle(route.path, '添加线索')
        }
        if(routerData.type == 'add' && routerData.checkValue){  //查重后带过来的值
            if(routerData.checkValue){  //查重后带过来的值
                if(routerData.checkSecond!='undefined'){
                    form.value[routerData.checkFrist][routerData.checkSecond]=routerData.checkValue
                    if(routerData.checkFrist=='customerCompany'&&routerData.checkSecond=='website'){
                        form.value.standbyWebsiteList[0].value = routerData.checkValue
                    }else if(routerData.checkFrist=='customerCompany'&&routerData.checkSecond=='email'){
                        form.value.standbyCompanyList[0].value = routerData.checkValue
                    }else if(routerData.checkFrist=='liaison'&&routerData.checkSecond=='email'){
                        form.value.standbyList[0].value = routerData.checkValue
                    }
                }else{
                    form.value[routerData.checkFrist]=routerData.checkValue
                }
            }
        }
        // 邮箱建档数据
        if(routerData.email) {
            form.value.standbyList[0].value = routerData.email
            form.value.liaison.email = routerData.email
        }
    }

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

    /** 提交按钮 */
    const visible = ref(false)
    const ruleData = ref([])
    const isCreate = ref(false)
    const submitForm = () => {
        clueFormRef.value?.validate((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;
                checkCustomer(form.value).then(res => {
                    if(res.success) {
                        isCreate.value = true
                        if(res.result) {
                            buttonLoading.value = false;
                            openDialog(res.result)
                        }else{
                            save()
                        }
                    }else{
                        buttonLoading.value = false;
                        isCreate.value = false
                        openDialog(res.result)
                    }
                }).catch(() => {
                    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 = () => {
        if(errorCanSaveVOList.value.length != 0) {
            form.value.errorCanSaveVOList = errorCanSaveVOList.value
        }
        let request = routerData.type == 'add' ? addCustomer : updateCustomer
        request(form.value).then(res => {
            if(res.success) {
                visible.value = false
                ElMessage.success((routerData.type == 'edit' ? '编辑' : '新增') + "成功");
                router.push('../clue/detail?id=' + (routerData.type == 'add' ? res.result : routerData.id) + '&hasPublicCustomer=' + routerData.hasPublicCustomer)
            }
        }).finally(() => {
            buttonLoading.value = false
            visible.value = false
        })
    }

    onActivated(() => {
        getDetailData()
    })

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

<style lang="scss" scoped>
	.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
        }
    }
</style>
