buli
2023-07-14 e6068da47c1bef5517c9e5fdc8c726766867ad4e
force-app/main/default/pages/NewAndEditAddress.page
@@ -1,16 +1,9 @@
<!--
  @description       :
  @author            : ChangeMeIn@UserSettingsUnder.SFDoc
  @group             :
  @last modified on  : 03-17-2022
  @last modified by  : ChangeMeIn@UserSettingsUnder.SFDoc
-->
<apex:page standardController="Address__c" extensions="NewAndEditAddressController" id="page">
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{! URLFOR($Resource.AWSService, 'AWSService.js') }" />
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <script src="../../soap/ajax/53.0/connection.js" type="text/javascript"></script>
    <apex:includeScript value="{!URLFOR($Resource.connection20)}"/>
    <style>
        .disabledbutton {
            pointer-events: none;
@@ -20,6 +13,9 @@
    <script>
        AWSService.sfSessionId = '{!GETSESSIONID()}';
        var staticResources = JSON.parse('{!staticResource}');
        //zhj MEBG新方案改造 2022-11-29 start
        var staticResourcesV2 = JSON.parse('{!staticResourceV2}');
        //zhj MEBG新方案改造 2022-11-29 end
        var staticResourcesContact = JSON.parse('{!staticResourceContact}');
        var requiredFieldAPIList = JSON.parse('{!requiredFieldAPIListStr}');
        var fieldAPIToLabelMap = JSON.parse('{!fieldAPIToLabelMapStr}');
@@ -27,10 +23,11 @@
        var requiredAPIToChangedLabelMap = new Map();
        requiredAPIToChangedLabelMap.set('LastName', '{!PIPL_Name_Label}');
        console.log('{!contactsInfo}');
        var VLookUpFields = new Set(['Contacts__c', 'Province__c', 'City__c', 'Customer__c']);
        //var VLookUpFields = new Set(['Contacts__c', 'Province__c', 'City__c', 'Customer__c']);
        var VLookUpFields = {! VLookUpFieldsJson};
        function ProcessPI(addressJson, payloadForNewPI) {
            blockme();
            if ({!isNewMode}) {
            if ({!isNewMode} || {!isCloneMode}) {
                NewPIToAWS(addressJson, payloadForNewPI)
            }else {
                UpdatePIToAWS(addressJson, payloadForNewPI)
@@ -64,7 +61,11 @@
            let Telephone = addressJson.Telephone__c;
            let ZipCode = addressJson.ZipCode__c;
            let DetailedAddress = addressJson.Detailed_Address__c;
            //zhj PIPL 2022-06-08 start
            let ContactName = addressJson.ContactName__c
            let addressPIData = new Object();
            addressPIData.contactName = ContactName;
            //zhj PIPL 2022-06-08 end
            addressPIData.telephone = Telephone;
            addressPIData.zipCode = ZipCode;
            addressPIData.detailedAddress = DetailedAddress;
@@ -88,7 +89,7 @@
            if(phone ){
                if(phone.value){
                    if(!/^1[3|5|8|7][0-9]\d{4,8}$/.test(phone.value)){
                       error_msg += ';电话号码错误';
                        error_msg += ';电话号码错误';
                    }
                }else{
                    if(phone.previousSibling && phone.previousSibling.className.indexOf('requiredBlock')>-1){
@@ -120,14 +121,27 @@
            let nodelist = document.querySelectorAll("[data-id]");
            let result = {}
            result.RecordTypeId = '{!rtTypeId}';
            //result.RecordTypeId = '{!rtTypeId}';
            for (let index = 0; index < nodelist.length; index++) {
                if (VLookUpFields.has(nodelist[index].getAttribute("data-id"))) {
                let tag_name = nodelist[index].tagName.toLowerCase();
                if(tag_name == 'div'){
                    console.log(nodelist[index])
                }
                if (VLookUpFields.indexOf(nodelist[index].getAttribute("data-id")) >= 0) {
                    console.log(nodelist[index].id.indexOf('lkwgt'));
                    if (nodelist[index].id.indexOf('lkwgt') == -1) {
                        let vlookUpNodeId = nodelist[index].id + '_lkid';
                        let vlookUpNodeValue = document.getElementById(vlookUpNodeId).value;
                        result[nodelist[index].getAttribute("data-id")] = vlookUpNodeValue;
                        if (tag_name == 'div') {
                            vlookUpNodeId = nodelist[index].id.substring(0,nodelist[index].id.length-4) + '_lkid';
                        }
                        let vlookUpNodeValue = document.getElementById(vlookUpNodeId);
                        let v = '';
                        if(vlookUpNodeValue){
                            v = vlookUpNodeValue.value;
                        }else{
                            v = nodelist[index].value;
                        }
                        result[nodelist[index].getAttribute("data-id")] = v;
                    }
                } else if (nodelist[index].type == 'checkbox') {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].checked;
@@ -148,14 +162,32 @@
            }
            return result;
        }
        function EditButton(isDisabled){
            var topele = document.getElementById('topButtonRow');
            var bottomele = document.getElementById('bottomButtonRow');
            if (isDisabled) {
                topele.classList.add("disabledbutton");
                bottomele.classList.add("disabledbutton");
            }else {
                topele.classList.remove("disabledbutton");
                bottomele.classList.remove("disabledbutton");
            }
        }
        function QueryAddressFromAWS() {
            AWSService.query(staticResources.queryUrl, '{!AWSDataId}', queryBack, staticResources.token);
        }
        var queryBack = function queryBack(data) {
            console.log('data = ' + data);
            document.querySelector("[data-id='Telephone__c']").value = data.object.telephone;
            document.querySelector("[data-id='ZipCode__c']").value = data.object.zipCode;
            document.querySelector("[data-id='Detailed_Address__c']").value = data.object.detailedAddress;
            if(document.querySelector("[data-id='Telephone__c']"))
                document.querySelector("[data-id='Telephone__c']").value = data.object.telephone;
            if(document.querySelector("[data-id='ZipCode__c']"))
                document.querySelector("[data-id='ZipCode__c']").value = data.object.zipCode;
            if(document.querySelector("[data-id='Detailed_Address__c']"))
                document.querySelector("[data-id='Detailed_Address__c']").value = data.object.detailedAddress;
            if(document.querySelector("[data-id='ContactName__c']"))
                document.querySelector("[data-id='ContactName__c']").value = data.object.contactName;
            unblockUI();
        };
@@ -164,18 +196,28 @@
            let r = result;
            console.log('Result from AWS' + r);
            console.log('payloadJson=' + payloadJson);
            //zhj PIPL 2022-06-08 start
            payloadJson.ContactName__c = r.object[0].contactName;
            payloadJson.Telephone__c = r.object[0].telephone;
            payloadJson.ZipCode__c = r.object[0].zipCode;
            payloadJson.Detailed_Address__c = r.object[0].detailedAddress;
            payloadJson.Telephone_Encrypted__c = r.object[0].telephoneEncrypt;
            payloadJson.ZipCode_Encrypted__c = r.object[0].zipCodeEncrypt;
            payloadJson.Detailed_Address_Encrypted__c = r.object[0].detailedAddressEncrypt;
            //zhj MEBG新方案改造 2022-11-29 start
            // payloadJson.ContactName_Encrypted__c = r.object[0].contactNameEncrypt;
            // payloadJson.Telephone_Encrypted__c = r.object[0].telephoneEncrypt;
            // payloadJson.ZipCode_Encrypted__c = r.object[0].zipCodeEncrypt;
            // payloadJson.Detailed_Address_Encrypted__c = r.object[0].detailedAddressEncrypt;
            //zhj MEBG新方案改造 2022-11-29 end
            //zhj PIPL 2022-06-08 end
            //payloadJson.AWS_Data_Id__c = r.object[0].dataId;
            payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            if (isNewMode) {
            if (isNewMode || {!isCloneMode}) {
                payloadJson.AWS_Data_Id__c = r.object[0].dataId;
                delete payloadJson.OwnerId;
            } else {
                payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            }
            if('{!rtTypeId}'){
                payloadJson.RecordTypeId = '{!rtTypeId}';//Add by zhj for Record Type Issue 20220421
            }
            return payloadJson;
        }
@@ -199,18 +241,26 @@
            let obj = JSON.parse(payloadForNewPI);
            obj[0].dataId = '{!AWSDataId}';
            let payloadForNewPIJson = JSON.stringify(obj);
            AWSService.update(staticResources.updateUrl, addressJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack,redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.update(staticResources.updateUrl, addressJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack,redirectCallBack);
            AWSService.update(staticResourcesV2.updateUrl, addressJson, payloadForNewPIJson, controllerSaveMethod, staticResourcesV2.token, staticResources.transactionUrl, false, insertOrUpdateBack,redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        function NewPIToAWS(addressJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.NewAndEditAddressController.saveAddress}';
            AWSService.insert(staticResources.newUrl, addressJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, true, insertOrUpdateBack,redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 start
            //AWSService.insert(staticResources.newUrl, addressJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, true, insertOrUpdateBack,redirectCallBack);
            AWSService.insert(staticResourcesV2.newUrl, addressJson, payloadForNewPI, controllerSaveMethod, staticResourcesV2.token, staticResources.transactionUrl, true, insertOrUpdateBack,redirectCallBack);
            //zhj MEBG新方案改造 2022-11-29 end
        }
        function checkRequiredFieldMsg(formData) {
            let blankRequiredFields = '';
            for(i = 0;i<requiredFieldAPIList.length;i++){
                if(formData[requiredFieldAPIList[i]]){
                if (formData[requiredFieldAPIList[i]] && (VLookUpFields.indexOf(requiredFieldAPIList[i]) == -1)) {
                    continue;
                }else if((VLookUpFields.indexOf(requiredFieldAPIList[i]) != -1) && formData[requiredFieldAPIList[i]] != '000000000000000'){
                    continue;
                }else{
                    let fieldAPIValue = requiredFieldAPIList[i]
@@ -229,6 +279,7 @@
            return blankRequiredFields;
        }
        function saveAddressProcess(saveMode) {
            EditButton(true);
            disableButtonStatus();
            redirectMode = saveMode;
@@ -237,13 +288,13 @@
            //1. Get Address Information from Form
            let addressJson = getAddressInformation();
            //2. Validate the Address field value formate, for example the email formate or phone formate
            let validationResultMessage = validateFieldValueFormate();
            console.log(validationResultMessage);
            if (validationResultMessage) {
                //Popup error message.  - To Do After POC
                alertErrorMessage(validationResultMessage);
                return
            }
            // let validationResultMessage = validateFieldValueFormate();
            // console.log(validationResultMessage);
            // if (validationResultMessage) {
            //     //Popup error message.  - To Do After POC
            //     alertErrorMessage(validationResultMessage);
            //     return
            // }
            // Check Required Field
            let checkRequiredFieldMsgResult = checkRequiredFieldMsg(addressJson);
            if (checkRequiredFieldMsgResult) {
@@ -264,6 +315,7 @@
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'pbError';
            unblockUI();
            EditButton(false);
        }
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
@@ -282,10 +334,11 @@
            //1. Check account value
            let accountNodeId = document.querySelector("[data-id='Customer__c']").id + '_lkid';
            let accountValue = document.getElementById(accountNodeId).value;
            let searchContactKeyWord = document.querySelector("[data-id='Contacts__c']").value;
            console.log(accountValue);
            if (accountValue != '000000000000000') {
                let baseUrl = "/apex/SearchContactPage";
                let suffixUrl = "?contactId=" + contactNodeId + "&accountId=" + accountValue;
                let suffixUrl = "?contactId=" + contactNodeId + "&accountId=" + accountValue+"&searchContactKeyWord=" + searchContactKeyWord;
                let newSearchContactParam = 'height=600,width=800,left=100,top=100,dialogHide=true,resizable=no,scrollbars=yes,toolbar=no,status=no';
                newSearchContactWindow = window.open(baseUrl + suffixUrl, 'Popup', newSearchContactParam);
                if (window.focus) {
@@ -324,15 +377,17 @@
        function queryContactName() {
            let sfId = document.getElementById(document.querySelector("[data-id='Contacts__c']").id + '_lkid').value;
            let contactsInfo = JSON.parse('{!contactsInfo}');
            let dataId = contactsInfo[sfId];
            let queryContactBack = function(data){
                //To Do later
                console.log('ContactData = ' + data.object);
            if(sfId && sfId != '000000000000000'){
                let contactsInfo = JSON.parse('{!contactsInfo}');
                let dataId = contactsInfo[sfId];
                let queryContactBack = function(data){
                    //To Do later
                    console.log('ContactData = ' + data.object);
                
                document.querySelector("[data-id='Contacts__c']").value = data.object.lastName;
                    document.querySelector("[data-id='Contacts__c']").value = data.object.lastName;
                }
                AWSService.query(staticResourcesContact.queryUrl, dataId, queryContactBack, staticResources.token);
            }
            AWSService.query(staticResourcesContact.queryUrl, dataId, queryContactBack, staticResources.token);
            // let url = staticResourcesContact.queryUrl + '?dataId=' + dataId;
            // fetch(url, {
            //     method: 'GET',
@@ -378,7 +433,7 @@
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />
                                <h2 class="mainTitle">收货地址编辑</h2>
                            </td>
                            <td class="pbButton" id="topButtonRow">
                            <td class="pbButton" id="topButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveAddressProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveAddressProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
@@ -401,8 +456,12 @@
                    
                    <!--Each section has layoutFields, let's iterate them as well-->
                    <apex:repeat value="{!layoutSection.layoutFields}" var="layoutField">
                        <apex:inputField html-data-id="{!layoutField.fieldAPI}" value="{!Address__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)}"
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Address__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&isNewMode}"
                            required="{!layoutField.isRequired}" />
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Address__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI!='RecordTypeId'}"
                            required="{!layoutField.isRequired}" />
                        <apex:outputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Address__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI=='RecordTypeId'}"
                       />
                        <apex:pageblocksectionitem rendered="{!layoutField.isPlaceHolder}">
                        </apex:pageblocksectionitem>
                    </apex:repeat>
@@ -417,7 +476,16 @@
                        for (let n = 0; n < layoutSection.length; n++) {
                            let layoutField = layoutSection[n];
                            if (layoutField.fieldAPI != '' && document.querySelector("[data-id='"+layoutField.fieldAPI+"']") != null) {
                                document.querySelector("[data-id='"+layoutField.fieldAPI+"']").disabled = !(layoutField.editableField);
                                let e = document.querySelector("[data-id='"+layoutField.fieldAPI+"']");
                                e.disabled = !(layoutField.editableField);
                                if (!(layoutField.editableField)) {
                                    if (e.getAttribute("multiple") && e.getAttribute("multiple") == 'multiple') {
                                        e.parentNode.classList.add("disabledbutton");
                                    }
                                    if (e.tagName == 'DIV') {
                                        e.classList.add("disabledbutton");
                                    }
                                }
                            }
                        }
                    }
@@ -430,16 +498,19 @@
                        QueryAddressFromAWS();
                    }
                    //Replace Vlookup Field
                    replaceSearchContactLookup();
                    // replaceSearchContactLookup();
                    //3. Set Readonly Attribute
                // document.querySelector("[data-id='OwnerId']").classList.add("disabledbutton");
                    // document.querySelector("[data-id='OwnerId']").classList.add("disabledbutton");
                    document.getElementById('topButtonRow').style = '';
             document.getElementById('bottomButtonRow').style = '';
                    /*
                    jQuery(".lookupInput").each(function(i,e){
                        let je =jQuery(e).find('input');
                        je.attr("readonly","");
                        je.css("background","unset");
                        
                        let dataid = je.attr('data-id');
                        if(['Province__c', 'OwnerId'].indexOf(dataid) > -1) return;
                        if(['Hospital_Name__c','Department_Class__c','OwnerId'].indexOf(dataid) > -1) return;
                        jQuery(e).children(":last-child").before('<img class="closeIcon" data-id="'+dataid+'" generate="" alt="Clear" src="/s.gif" style="display: inline-block;">');
                    })
                    
@@ -455,13 +526,33 @@
                        let id = jQuery("input[data-id='"+jQuery(this).attr("data-id")+ "']").attr("id");
                        let input = document.getElementById(id);
                        if(input){
                           input.value = '';
                     let hidden = document.getElementById(id+'_lkid');
                            input.value = '';
                            let hidden = document.getElementById(id+'_lkid');
                            if(hidden){
                               hidden.value = '';
                                hidden.value = '';
                            }
                        }
                    });
                    */
                    let previous_value = {};
                    jQuery(".lookupInput input").each(function(i,e){
                        let je =jQuery(e);
                        let dataid = je.attr('data-id');
                        if(['Contacts__c'].indexOf(dataid) < 0) return;
                        jQuery(e).focus(function(){
                            previous_value[this.id] = this.value;
                        })
                        jQuery(e).change(function(){
                            if (previous_value[this.id] != jQuery(this).val()) {
                                document.getElementById(this.id+'_lkid').value = '';
                            }
                        })
                    })
                });
            </script>
            <div class="pbBottomButtons">
@@ -470,7 +561,7 @@
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />&nbsp;</td>
                            <td class="pbButtonb" id="bottomButtonRow">
                            <td class="pbButtonb" id="bottomButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveAddressProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveAddressProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />