Look Up

ahoTang / 2024-02-06 / 原文

<template>
    <div>
        <div class="slds-form-element">
            <div class="slds-form-element__control">
                <div class="slds-combobox_container">
                    <div id="box" class={boxClass} aria-expanded="true" aria-haspopup="listbox" role="combobox">
                        {searchLabel}
                        <div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right" role="none">
                            <template if:true={isValue}>
                                <!-- height: 100%; -->
                                <div style="position: absolute;top: 0;left: 0;width: 100%;
                                background-color: rgb(201, 201, 201);pointer-events: none;">
                                    <div id="lookup-pill" class="slds-pill-container" style="position: relative;">
                                        <lightning-pill label={valueObj} name={valueObj} onremove={handleRemovePill} disabled={disabled}>
                                            <lightning-icon icon-name={iconName} alternative-text="acc"></lightning-icon>
                                        </lightning-pill>
                                    </div>
                                </div>
                            </template>
                            <template if:false={isValue}>
                                <div class="slds-p-top_none">
                                    <lightning-input class={inputClass} type="search" id="input" value={searchTerm}
                                        onclick={handleClick}  onchange={searchChange} onblur={onBlur} disabled={disabled}
                                        variant="label-hidden" autocomplete="off" placeholder="Search..." label='account search'>
                                    </lightning-input>
                                </div>
                            </template>
                        </div>
                        <div id="listbox-id-1" class="slds-dropdown slds-dropdown_length-with-icon-7 slds-dropdown_fluid" role="listbox" 
                        onmouseleave={handleMouseleave} onmouseenter={handleMouseenter}>
                            <ul class="slds-listbox slds-listbox_vertical" role="presentation">
                                <template for:each={options} for:item="item">
                                    <li key={item.Id} onclick={onSelect} data-id={item.Id} role="presentation">
                                        <span class="slds-lookup__item-action slds-lookup__item-action--label" role="option">
                                            <lightning-icon class="slds-icon slds-icon--small slds-icon-text-default" icon-name={iconName} alternative-text={objName} size="small"></lightning-icon>
                                            <span class="slds-truncate">{item.Name}</span>
                                        </span>
                                    </li>
                                </template>
                                <li class="sticky-li" onclick={newObject} data-id="NewRecord"  role="presentation">
                                    <span class="slds-lookup__item-action slds-lookup__item-action--label" role="option">
                                        <span class="slds-truncate">新建</span>
                                    </span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <template if:true={showModal}>
        <!-- Modal/Popup Box LWC starts here -->
        <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <!-- Modal/Popup Box LWC header here -->
                <header class="slds-modal__header">
                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                        <lightning-icon icon-name="utility:close"
                            alternative-text="close"
                            variant="inverse"
                            size="small" ></lightning-icon>
                        <span class="slds-assistive-text">Close</span>
                    </button>
                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">新建客户人员</h2>
                </header>
                <!-- Modal/Popup Box LWC body starts here -->
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                    <!-- <lightning-record-form  object-api-name="Agency_Contact__c" layout-type="Full" columns="2" mode="edit" no-save-button no-cancel-button>
                    </lightning-record-form> -->
                    <lightning-record-edit-form object-api-name="Contact">
                        <lightning-layout multiple-rows="true">
                            <lightning-layout-item size="6">
                                <lightning-input-field required="true" value={theContact.Name} onchange={fieldChange} field-name="LastName"></lightning-input-field>
                            </lightning-layout-item>
                            <!-- <lightning-layout-item size="6">
                                <lightning-input-field value={theContact.UnifiedI_Contact_ID__c} onchange={fieldChange} field-name="UnifiedI_Contact_ID__c"></lightning-input-field>
                            </lightning-layout-item> -->
                            <lightning-layout-item size="6">
                                <lightning-input-field required="true" value={theContact.AccountId} onchange={fieldChange} field-name="AccountId"></lightning-input-field>
                            </lightning-layout-item>
                            <!-- <lightning-layout-item size="6">
                                <lightning-input-field value={theContact.ServicePlatformCode__c} onchange={fieldChange} field-name="ServicePlatformCode__c"></lightning-input-field>
                            </lightning-layout-item> -->
                            <lightning-layout-item size="6">
                                <label for="custom-phone" class="slds-form-element__label slds-no-flex">手机号</label>
                                <lightning-input-field value={theContact.Phone} onchange={fieldChange} field-name="Phone" id="custom-phone" variant="label-hidden"></lightning-input-field>
                            </lightning-layout-item>
                            <!-- <lightning-layout-item size="6">
                                <lightning-input-field value={theContact.Strategic_dept_Class__c} onchange={fieldChange} field-name="Strategic_dept_Class__c"></lightning-input-field>
                            </lightning-layout-item> -->
                        </lightning-layout>
                    </lightning-record-edit-form>
                </div>
                <!-- Modal/Popup Box LWC footer starts here -->
                <footer class="slds-modal__footer">
                    <button class="slds-button slds-button_brand" onclick={sureSave}>保存</button>
                    <button class="slds-button slds-button_neutral" onclick={closeModal}>取消</button>
                </footer>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>
/* eslint-disable no-console */
/* eslint-disable @lwc/lwc/no-async-operation */

import lookUp from '@salesforce/apex/LookUpUtilController.lookUp';
import getPIPLInfo from '@salesforce/apex/LookUpUtilController.getPIPLInfo';//deloitte-zhj 获取解密信息 2023/07/19 
import searchContactInit from '@salesforce/apex/LookUpUtilController.searchContactInit';//deloitte-zhj 搜索需要的PI数据 2023/07/19 
import searchContactByAccountId from '@salesforce/apex/LookUpUtilController.searchContactByAccountId';//deloitte-zhj 新建判断重复 2023/07/19 
import { AWSService } from 'c/piUtils';//deloitte-zhj 调用aws 2023/07/19 
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getRecord } from 'lightning/uiRecordApi';
import { NavigationMixin } from 'lightning/navigation';
import { api, LightningElement, track, wire } from 'lwc';
import saveContact from '@salesforce/apex/LwcDailyReportController.saveContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

export default class NewAccountButton extends NavigationMixin(LightningElement) {
    AWSService;
    @track theContact = {};
    @track showModal = false;
    //记录id
    @api valueId;
    @api objName;
    @api iconName;
    @api disabled;
    @api filter = '';
    //unique key used to mark the unique component. several component use this component need to mapping
    @api uniqueKey;
    //used to set the field to fetch.eg: ['Account.Name'] means we need to search account name field as filter
    @api fields;

    @api searchLabel;
    @track searchTerm;
    //record name value
    @track valueObj;
    //record href
    @track href;
    //fetch result
    @track options;
    //是否展示pill
    @track isValue = false;
    isCanCanle = true;
    @track blurTimeout;
    isOpen = false;
    get boxClass() {
        let classes = "slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus";
        if (this.isOpen) {
            return classes + " slds-is-open";
        }
        return classes;
    }
    _passFilter;
    @api
    get passFilter() {
        return this._passFilter;
    }

    set passFilter(newValue) {
        this._passFilter = newValue;
        this.filter = newValue;
    }
    //css:
    // @track boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus';
    @track inputClass = '';

    //deloitte-zhj staticResourceContact 2023/07/19 
    @track staticResourceContact;
    @track txId;

    //deloitte-zhj 解密 2023/07/19 start
    @wire(lookUp, { searchTerm: '$searchTerm', objName: '$objName', filter: '$filter' })
    wiredRecords({ error, data }) {
        console.log('enter wiredRecords');
        if (data) {
            let that = this;
            console.log('data = ' + JSON.stringify(data))
            let dataClone = this.deepClone(data);
            //搜索,需要把对应account下面进行了PIPL的数据查出来,需要搜索值和accountid都存在才行
            console.log('this.filter = ' + this.filter)
            console.log('this.searchTerm = ' + this.searchTerm)
            if (this.filter) {
                searchContactInit({
                    accountId: this.filter
                }).then((r) => {
                    r = JSON.parse(JSON.stringify(r));
                    console.log('r = ' + JSON.stringify(r))
                    if (r.status == 'Success') {
                        let awsIdToContactMap = r.entity.awsIdToContactMap;
                        let conAWSIds = r.entity.conAWSIds;
                        console.log('awsIdToContactMap = ' + awsIdToContactMap);
                        console.log('conAWSIds = ' + conAWSIds);
                        that.AWSService.search(that.staticResourceContact.searchUrl, {
                            dataIds: conAWSIds,
                            contactName: that.searchTerm
                        }, function (data) {
                            console.log('data = ' + JSON.stringify(data));
                            if (data.object) {
                                let limit = data.object.length > 50 ? 50 : data.object.length;//最多找20条
                                for(let i=0; i < limit; i++){
                                    if(awsIdToContactMap.hasOwnProperty(data.object[i].dataId)){
                                        let PIData = {};
                                        PIData.Id = awsIdToContactMap[data.object[i].dataId].Id;
                                        PIData.Name = data.object[i].lastName;
                                        PIData.AWSDataId = data.object[i].dataId;
                                        dataClone.push(PIData)
                                    }
                                }
                                console.log('dataClone = ' + JSON.stringify(dataClone));
                            }
                            that.executeWiredRecords(dataClone);
                        }, that.staticResourceContact.token)
                    } else {
                        console.log('r.msg = ' + r.msg)
                    }
                })
            } else {
                this.executeWiredRecords(dataClone)
            }
        } else if (error) {
            this.error = error;
            this.record = undefined;
            console.log("wire.error", this.error);
        } else {
            console.log('啥都没有');
        }
    }
    deepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }
    executeWiredRecords(dataClone) {
        let arr = [];
        for (var i in dataClone) {
            if (dataClone[i].AWSDataId)
                arr.push(dataClone[i].AWSDataId)
        }
        console.log('arr = ' + arr);
        let that = this;
        if (arr.length != 0) {
            this.AWSService.search(this.staticResourceContact.searchUrl, {
                dataIds: arr
            }, function (dataAWS) {
                console.log('dataAWS = ' + JSON.stringify(dataAWS));
                if (dataAWS && dataAWS.object && dataAWS.object.length > 0) {
                    let awsMap = {};
                    for (let di in dataAWS.object) {
                        awsMap[dataAWS.object[di].dataId] = dataAWS.object[di];
                    }
                    console.log('awsMap = ' + JSON.stringify(awsMap));
                    for (var i in dataClone) {
                        if (awsMap.hasOwnProperty(dataClone[i].AWSDataId)) {
                            dataClone[i].Name = awsMap[dataClone[i].AWSDataId].lastName
                        }
                    }
                    console.log('dataClone = ' + JSON.stringify(dataClone));
                    that.record = dataClone;
                    console.log('that.record = ' + JSON.stringify(that.record));
                    that.error = undefined;
                    that.options = that.record;
                    console.log("common this.options", JSON.stringify(that.options));
                } else {
                    that.record = dataClone;
                    that.error = undefined;
                    that.options = that.record;
                    console.log("common this.options", JSON.stringify(that.options));
                }
            }, this.staticResourceContact.token)
        } else {
            this.record = dataClone;
            this.error = undefined;
            this.options = this.record;
            console.log("common this.options", JSON.stringify(this.options));
        }
    }
    //deloitte-zhj 解密 2023/07/19 end

    //To get preselected or selected record
    @wire(getRecord, { recordId: '$valueId', fields: '$fields' })
    wiredOptions({ error, data }) {
        console.log('wiredOptions');
        if (data) {
            console.log('wiredOptions data = ' + JSON.stringify(data))
            //deloitte-zhj 解密 2023/07/19 start
            if (data.fields.AWS_Data_Id__c && data.fields.AWS_Data_Id__c.value && data.fields.Name.value.includes('***')) {
                console.log('data.fields.AWS_Data_Id__c.value = ' + data.fields.AWS_Data_Id__c.value)
                let that = this;
                this.AWSService.query(this.staticResourceContact.queryUrl, data.fields.AWS_Data_Id__c.value, function (dataAWS) {
                    console.log('queryLeadFromAWSIFS data = ' + JSON.stringify(dataAWS));
                    if (dataAWS.object) {
                        //data.fields.Name.value = dataAWS.object['lastName'];
                        that.record = data;
                        console.log('that.record =  ' + JSON.stringify(that.record));
                        that.error = undefined;
                        that.valueObj = dataAWS.object['lastName'];
                        that.href = '/' + that.record.id;
                        that.isValue = true;
                    } else {
                        that.record = data;
                        that.error = undefined;
                        that.valueObj = that.record.fields.Name.value;
                        that.href = '/' + that.record.id;
                        that.isValue = true;
                    }
                }, this.staticResourceContact.token)
            } else {
                this.record = data;
                this.error = undefined;
                this.valueObj = this.record.fields.Name.value;
                this.href = '/' + this.record.id;
                this.isValue = true;
            }
            //deloitte-zhj 解密 2023/07/19 end
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }


    //deloitte-zhj 获取PIPL需要的数据 2023/07/19 start
    connectedCallback() {
        console.log('enter connectedCallback')
        this.AWSService = new AWSService();
        getPIPLInfo().then((r) => {
            r = JSON.parse(JSON.stringify(r));
            console.log('r = ' + JSON.stringify(r))
            if (r.status == 'Success') {
                this.staticResourceContact = JSON.parse(r.entity.staticResourceContact);
                console.log('this.staticResourceContact.searchUrl = ' + this.staticResourceContact.searchUrl)
            } else {
                console.log('error msg = ' + r.msg)
            }
        })
    }
    //deloitte-zhj 获取PIPL需要的数据 2023/07/19 end

    handleClick() {
        console.log("In handleClick");
        if(this.disabled){
            return;
        }
        this.searchTerm = '';
        this.inputClass = 'slds-has-focus';
        this.isOpen = true;
        //deloitte-zhj refresh wiredRecords start 
        this.searchTerm = 'refresh';
        this.searchTerm = '';
        refreshApex(this.wiredRecords);
        //deloitte-zhj refresh wiredRecords end
        // this.boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus slds-is-open';
    }

    onSelect(event) {
        console.log("In onSelect");
        let ele = event.currentTarget;
        let selectedId = ele.dataset.id;
        let key = this.uniqueKey;
        console.log("key = " + key);
        console.log("selectedId = " + selectedId);
        const valueSelectedEvent = new CustomEvent('valueselect', {
            detail: { selectedId, key },
        });
        this.dispatchEvent(valueSelectedEvent);
        this.isOpen = false;
        // this.boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus';
    }

    searchChange(event) {
        this.searchTerm = event.target.value;
    }

    onBlur() {
        if (!this.isCanCanle) {
            return;
        }
        this.isOpen = false;
        // this.boxClass = 'slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click slds-has-focus';
    }
    @api
    handleRemovePill() {
        console.log("In handleRemovePill");
        this.isValue = false;
        let selectedId = '';
        let key = this.uniqueKey;
        const valueSelectedEvent = new CustomEvent('valueselect', {
            detail: { selectedId, key },
        });
        this.dispatchEvent(valueSelectedEvent);
    }

    newObject() {
        this.isOpen = false;
        this.showModal = true;
        // const newEvent = new CustomEvent('newrecord', {
        //     detail: { key :this.uniqueKey},
        // });
        // this.dispatchEvent(newEvent);
    }
    closeModal() {
        console.log('closeModal');
        this.showModal = false;
    }
    handleMouseleave() {
        this.isCanCanle = true;
    }
    handleMouseenter(event) {
        this.isCanCanle = false;
    }
    sureSave(event) {
        event.preventDefault();//很重要 如果没得这个会导致页面刷新!
        console.log('submitDetails');
        let flag = true;
        let requiredFieldList = this.template.querySelectorAll('lightning-input-field');
        requiredFieldList.forEach(ele => {
            if (ele.required == true && this.stringIsEmpty(ele.value)) {
                ele.reportValidity();
                flag = false;
            }
        });
        console.log(flag);
        if (flag) {
            let payloadForNewPI = [];
            let PIData = {};
            PIData['lastName'] = this.theContact['LastName']
            PIData['phone'] = this.theContact['Phone']
            payloadForNewPI.push(PIData);
            payloadForNewPI = JSON.stringify(payloadForNewPI);
            console.log('payloadForNewPI = ' + payloadForNewPI)
            console.log('this.theContact[AccountId] = ' + this.theContact['AccountId'])
            let that = this;
            //deloitte-zhj 新建判断重复并且进行加密 2023/07/19 start
            searchContactByAccountId({
                accountId: this.theContact['AccountId'],
            }).then((resultAccount) => {
                resultAccount = JSON.parse(JSON.stringify(resultAccount));
                if (resultAccount.status == 'fail') {
                    that.showToast(resultAccount.message, 'Error');
                    console.log()
                    return
                }
                let accountName = resultAccount.accountName;
                let dataIdManageCodeMap = resultAccount.dataIdManageCodeMap;
                let contactList = '';
                for (var i = 0; i < resultAccount.contactList.length; i++) {
                    if (resultAccount.contactList[i].AWS_Data_Id__c)
                        contactList += ',' + resultAccount.contactList[i].AWS_Data_Id__c;
                }
                contactList = contactList.substring(1);
                payloadForNewPI = JSON.parse(payloadForNewPI);
                payloadForNewPI[0].contactIds = contactList;
                payloadForNewPI[0].isMobileVerif = resultAccount.isMobileVerif;
                payloadForNewPI[0].isNameMobileVerif = resultAccount.isNameMobileVerif;
                payloadForNewPI = JSON.stringify(payloadForNewPI);
                //AWS加密
                that.AWSService.post(that.staticResourceContact.newUrl + 'V2', payloadForNewPI, (resultAWS) => {
                    if (resultAWS && resultAWS.object) {
                        //判断已存在相同名字的联系人
                        let errorMsg = '';
                        if (resultAWS.status == '129') {
                            errorMsg = '客户 [ ' + accountName + ' ],已存在相同名字的联系人 人员管理编码 [' + dataIdManageCodeMap[resultAWS.object[0].dataId] + ' ] ,不能重复创建,请了解';
                            that.showToast('Error',errorMsg)
                            return
                        }
                        if (resultAWS.status == '130') {
                            if (resultAWS.object[0] && resultAWS.object[0].sfRecordId != null && resultAWS.object[0].sfRecordId != '') {
                                errorMsg = '已找到重复值: UniqueNumber__c 与记录值重复,ID 为: ' + resultAWS.object[0].sfRecordId + '客户人员信息';
                            }
                            else {
                                errorMsg = '数据中存在重复的电话号码';
                            }
                            that.showToast('Error',errorMsg)
                            return
                        }
                        console.log('resultAWS = ' + JSON.stringify(resultAWS));
                        that.theContact['LastName'] = resultAWS.object[0]['lastName'];
                        that.theContact['Phone'] = resultAWS.object[0]['phone'];
                        that.theContact['AWS_Data_Id__c'] = resultAWS.object[0]['dataId'];
                        that.txId = resultAWS.txId;
                        console.log('that.theContact = ' + that.theContact)
                        //保存到后端
                        saveContact({ contactJson: JSON.stringify(that.theContact) })
                            .then(result => {
                                if (result.code === 200) {
                                    //deloitte-zhj 新建判断重复并且进行加密成功之后需要进行事务确认 2023/07/19 start
                                    that.AWSService.confirm(true, result.msg, that.txId, that.staticResourceContact.token, that.staticResourceContact.transactionUrl, function (resultConfirm) {
                                        console.log('resultConfirm = ' + JSON.stringify(resultConfirm))
                                        that.showToast('success', '保存成功');
                                        let selectedId = result.msg;
                                        let key = that.uniqueKey;
                                        const valueSelectedEvent = new CustomEvent('valueselect', {
                                            detail: { selectedId, key },
                                        });
                                        that.dispatchEvent(valueSelectedEvent);
                                        that.isOpen = false;
                                    });
                                    //deloitte-zhj 新建判断重复并且进行加密成功之后需要进行事务确认 2023/07/19 end
                                } else {
                                    that.showToast('error', '保存失败,' + result.msg);
                                }
                                that.showModal = false;
                            })
                            .catch(error => {
                                that.showToast('error', '保存失败,' + error);
                                that.showModal = false;
                            });
                    } else {
                        console.log('result = ' + JSON.stringify(result));
                    }
                }, that.staticResourceContact.token);
            });
            //deloitte-zhj 新建判断重复并且进行加密 2023/07/19 end

        }
    }
    stringIsEmpty(str) {
        if (str === '' || str === undefined || str === null) {
            return true;
        } else {
            return false;
        }
    }
    showToast(variant, mes) {
        const event = new ShowToastEvent({
            message: mes,
            variant: variant,
        });
        this.dispatchEvent(event);
    }
    //字段信息改变
    async fieldChange(event) {
        const { value } = event.detail;
        const { fieldName } = event.target || event.currentTarget;
        let checked = event.target.value || event.currentTarget.value;
        if (value == undefined && checked != undefined) {
            this.theContact[fieldName] = checked;
        } else {
            this.theContact[fieldName] = value instanceof Array ? value[0] : value;
        }
    }
}
.sticky-li {
    position: sticky;
    /* top: 0; */
    bottom: 0;
    background-color: #fff;
    z-index: 999;
}
.custom-pill {
    position: relative; /* 设置相对定位 */
}

.custom-pill::before {
    content: ""; /* 添加伪元素内容 */
    position: absolute; /* 设置绝对定位,覆盖在 pill 元素之上 */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.2); /* 设置遮罩层颜色,这里使用淡灰色带透明度 */
    pointer-events: none; /* 确保遮罩层不会阻止用户操作 */
}
<c-other-look-up disabled={isAccDis} unique-key="AccountID" value-id={filter} obj-name="Account"
                                        icon-name="standard:account" search-label="" onvalueselect={handleAccSelection} fields={AccountFields}></c-other-look-up>