Li Jun
2022-04-19 2f183a6b0a83ec3f7d35375d5d25d200efc2a3e1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<apex:page standardController="On_Call__c" extensions="OnCallController" id="page">
    <apex:includeScript value="{! URLFOR($Resource.AWSService, 'AWSService.js') }" />
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <script src="../../soap/ajax/53.0/connection.js" type="text/javascript"></script>
    <style>
        .disabledbutton {
            pointer-events: none;
            opacity: 0.4;
        }
    </style>
    <script>
        //Initial Required Information
        AWSService.sfSessionId = '{!GETSESSIONID()}';
        var staticResources = JSON.parse('{!staticResource}');
        var requiredFieldAPIList = JSON.parse('{!requiredFieldAPIListStr}');
        var fieldAPIToLabelMap = JSON.parse('{!fieldAPIToLabelMapStr}');
        var VLookUpFields = new Set(['segment__c','Hospital__c','Oncall_Equipment__c','OwnerId']);
        var redirectMode = 'Save';
 
        //Redirect Required Parameter
        var redirectCallBack = function redirectCallBack(sfId, errorMessage) {
            if (sfId) {
                if (redirectMode == 'Save') {
                    window.open('/' + sfId, '_self');
                } else if (redirectMode == 'SaveAndNew') {
                    window.open('/setup/ui/recordtypeselect.jsp?ent=' + '{!sobjecttypeForFrontEnd}' + '&retURL=/' + '{!sobjectPrefix}' + '/o&save_new_url=/' + '{!sobjectPrefix}' + '/e?retURL=%2F' + '{!sobjectPrefix}' + '%2Fo', '_self');
                }
            } else {
                // alert(errorMessage);
                alertErrorMessage(errorMessage);
            }
        }
 
        //Query Required Parameter
        var queryBack = function queryBack(data) {
            console.log('data = ' + data);
            //document.querySelector("[id='page:form:pageBlock:pageBlockSection:j_id1:0:j_id2']").value = data.object.callerPhone;
            document.getElementById(api_id_map['Caller_phone__c']).value = data.object.callerPhone;    //20220404  By Chen Yanan
            document.querySelector("[data-id='Responsible_Person_HP__c']").value = data.object.responsiblePersonHP;
            unblockUI();
        };
 
        //Check If Insert Or Update
        var insertOrUpdateBack = function insertOrUpdateBack(payloadJson, result, isNewMode) {
            debugger
            console.log(result);
            let r = result;
            console.log('Result from AWS' + JSON.stringify(r));
            console.log('payloadJson=' + JSON.stringify(payloadJson));
            payloadJson.Caller_phone__c = r.object[0].callerPhone;
            payloadJson.Responsible_Person_HP__c = r.object[0].responsiblePersonHP;
            payloadJson.Caller_Phone_Encrypt__c = r.object[0].callerPhoneEncrypt;
            payloadJson.Responsible_PersonHP_Encrypt__c = r.object[0].responsiblePersonHPEncrypt;
            payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            if (isNewMode|| {!isCloneMode} ||!'{!AWSDataId}') {//Add by Li Jun for PIPL 20220413
                payloadJson.AWS_Data_Id__c = r.object[0].dataId;
                delete payloadJson.OwnerId;
            } else {
                payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            }
            debugger
            return payloadJson;
        }
 
        // New Or Edit
        function ProcessPI(onCallJson, payloadForNewPI) {
            blockme();
            if ({!isNewMode} || {!isCloneMode} ||!'{!AWSDataId}') {//Add by Li Jun for PIPL 20220413
                NewPIToAWS(onCallJson, payloadForNewPI)
            }else {
                UpdatePIToAWS(onCallJson, payloadForNewPI)
            }
        }
 
        //Get Sensitive Information
        function getPIPayload(onCallJson) {
            let onCallPayloadList = [];
            let callerPhone = onCallJson.Caller_phone__c;
            let responsiblePersonHP = onCallJson.Responsible_Person_HP__c;
            let onCallPIData = new Object();
            onCallPIData.callerPhone = callerPhone;
            onCallPIData.responsiblePersonHP = responsiblePersonHP;
            onCallPIData.sfRecordId = '';
            console.log('onCall PI Data:' + JSON.stringify(onCallPIData));
            onCallPayloadList.push(onCallPIData);
            console.log(JSON.stringify(onCallPayloadList));
            return JSON.stringify(onCallPayloadList);
        }
 
        //Check Validate Field Value
        function validateFieldValueFormate() {
            return true;
        }
 
        //Get Page Information
        function getOnCallInformation() {
            let nodelist = document.querySelectorAll("[data-id]");
            let result = {}         
            for (let index = 0; index < nodelist.length; index++) {
                if (VLookUpFields.has(nodelist[index].getAttribute("data-id"))) {
                    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;
                    }
                } else if (nodelist[index].type == 'checkbox') {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].checked;
                } else if (nodelist[index].type == 'select-multiple') {
                    //nodelist[index].getAttribute("data-id")
                    let multiple = nodelist[index].getAttribute("data-id");
                    let targets = document.querySelector("[data-id=" + multiple + "]").parentNode.children[1].children[0].children[1].children[2].children[0].innerText;
                    targets = targets.replace(/\n/g, ";");
                    console.log('targets = ' + targets);
                    result[nodelist[index].getAttribute("data-id")] = targets;
                } else {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].value;
                }
                let x = index + 1;
                if (x <= nodelist.length - 1 && (nodelist[x].getAttribute("data-id") == nodelist[index].getAttribute("data-id"))) {
                    index++;
                }
            }
            console.log(JSON.stringify(result));
            return result;
        }
 
        //Query from AWS
        function QueryOnCallFromAWS() {
            AWSService.query(staticResources.queryUrl, '{!AWSDataId}', queryBack, staticResources.token);
        }
 
        //Update Sensitive Information to AWS
        function UpdatePIToAWS(onCallJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.OnCallController.saveOnCall}';
            let obj = JSON.parse(payloadForNewPI);
            obj[0].dataId = '{!AWSDataId}';
            let payloadForNewPIJson = JSON.stringify(obj);
            AWSService.update(staticResources.updateUrl, onCallJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
        }
 
        //Insert Sensitive Information to AWS
        function NewPIToAWS(onCallJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.OnCallController.saveOnCall}';
            AWSService.insert(staticResources.newUrl, onCallJson, payloadForNewPI, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, true, insertOrUpdateBack, redirectCallBack);
        }
 
        //Check Required Fields
        function checkRequiredFieldMsg(formData) {
            let blankRequiredFields = '';
            for (i = 0; i < requiredFieldAPIList.length; i++) {
                if (formData[requiredFieldAPIList[i]]) {
                    continue;
                } else {
                    if (blankRequiredFields == '') {
                        blankRequiredFields = blankRequiredFields + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    } else {
                        blankRequiredFields = blankRequiredFields + ',' + fieldAPIToLabelMap[requiredFieldAPIList[i]];
                    }
 
                }
            }
            return blankRequiredFields;
        }
 
        //Base Process
        function saveOnCallProcess(saveMode) {
            redirectMode = saveMode;
            console.log('redirectMode' + redirectMode);
            hiddenErrorMsgNode();
            //1. Get onCall Information from Form
            let onCallJson = getOnCallInformation();
            //2. Validate the onCall 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('邮箱格式输入有误,请重新输入!');
                return
            }
            // Check Required Field
            let checkRequiredFieldMsgResult = checkRequiredFieldMsg(onCallJson);
            if (checkRequiredFieldMsgResult) {
                alertErrorMessage('{!Input_Required_Field_Msg}' + checkRequiredFieldMsgResult);
                return
            }
            //3. Prepare the payload for New PI API To AWS - To Do
            let payloadForNewPI = getPIPayload(onCallJson);
 
            //4. onCall to AWS 
            ProcessPI(onCallJson, payloadForNewPI);
        }
 
        //Alert Error Message
        function alertErrorMessage(errorMsg) {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsg = '错误:无效数据。' + '\n' + errorMsg;
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'pbError';
            unblockUI();
        }
 
        //Hide Error Message
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:form:block:msgContent");
            errorMsgNode.innerText = '';
            errorMsgNode.className = '';
        }
        var GetEleApiName = function(ele){
            for(let ci in ele.classList){
                let c = ele.classList[ci];
                if(c.indexOf('PIBackApi'+'_')>-1){
                    return c.replace('PIBackApi'+'_','');
                }
            }
            return '';
        }
 
        function IsFormTag(tag_name){
            if (!tag_name) {
                return false;
            }
            return ['input','select','textarea'].indexOf(tag_name.toLowerCase())>-1;
        }
        
        function IsFormElement(e){
            return IsFormTag(e.tagName);
        }
    </script>
    <div class="bPageTitle">
        <div class="ptBody">
            <div class="content">
                <img src="/img/s.gif" alt="OnCall" class="pageTitleIcon" title="OnCall" />
                <h1 class="pageType">OnCall编辑
                    <span class="titleSeparatingColon">:</span>
                </h1>
                <h2 class="pageDescription">新建OnCall</h2>
                <div class="blank">&nbsp;</div>
            </div>
            <div class="links">
                <a href="javascript:openPopupFocusEscapePounds(%27https://help.salesforce.com/apex/htdoor?loc=help&amp;target=onCalls_edit.htm&amp;section=onCalls&amp;language=zh_CN&amp;release=234.18.8&amp;instance=CS117&amp;showSplash=true%27, %27Help%27, 700, 600, %27width=700,height=600,resizable=yes,toolbar=yes,status=no,scrollbars=yes,menubar=yes,directories=no,location=no,dependant=no%27, false, false);"
                    title="此页面的帮助 (新窗口)">
                    <span class="helpLink">此页面的帮助</span>
                    <img src="/img/s.gif" alt="" class="helpIcon" />
                </a>
            </div>
        </div>
        <div class="ptBreadcrumb"></div>
    </div>
    <apex:form id="form">
        <apex:pageblock id="block" >
            <div class="pbHeader">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />
                                <h2 class="mainTitle">OnCall编辑</h2>
                            </td>
                            <td class="pbButton" id="topButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveOnCallProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveOnCallProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- Error Msg-->
            <div style="text-align: center;">
                <apex:outputPanel id="errorMsg">
                    <apex:pageMessages id="msgContent" escape="false" />
                </apex:outputPanel>
            </div>
            <!-- Iterate the layoutSections, which is a list of sections -->
            <apex:repeat value="{!layoutSections}" var="layoutSection">
                <apex:pageBlockSection title="{!layoutSection.name}" collapsible="{!layoutSection.allowCollapse}" columns="{!layoutSection.columns}">
 
                    <!--Each section has layoutFields, let's iterate them as well-->
                    <apex:repeat value="{!layoutSection.layoutFields}" var="layoutField">
                       <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!On_Call__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&isNewMode}"
                            required="{!layoutField.isRequired}" />
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!On_Call__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="{!On_Call__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&not(isNewMode)&&layoutField.fieldAPI=='RecordTypeId'}"
                       />
                        <apex:pageblocksectionitem rendered="{!layoutField.isPlaceHolder}">
                        </apex:pageblocksectionitem>
                    </apex:repeat>
 
                </apex:pageBlockSection>
            </apex:repeat>
            <script>
                var init_nodes = document.getElementsByClassName("PIBackApi");
                var api_id_map={};
                for(let ei in init_nodes){
                    let e = init_nodes[ei];
                    if(IsFormElement(e)){
                        if(e.getAttribute("multiple") != 'multiple' || e.style.display == 'none' && e.id.indexOf('selected') < 0){
                            api_id_map[GetEleApiName(e)] = e.id;
                        }
                        
                    }
                }
                //Append Page
                sfdcPage.appendToOnloadQueue(function () {
                    var layoutSections = JSON.parse('{!layoutSectionsStr}');
                    for (let m = 0; m < layoutSections.length; m++) {
                        let layoutSection = layoutSections[m].layoutFields;
                        for (let n = 0; n < layoutSection.length; n++) {
                            let layoutField = layoutSection[n];
                            if (layoutField.fieldAPI != '' && document.querySelector("[data-id='"+layoutField.fieldAPI+"']") != null) {
                                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");
                                    }
                                }
                            }
                        }
                    }
                    //2. Query AWS Data by dataId 
                    console.log('Mode for onCall Page:' + {!isNewMode});
                    if (!{!isNewMode}) {
                        blockme();
                        QueryOnCallFromAWS();
                    };
                    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(['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;">');
                    })
                    
                    jQuery(".lookupInput").on("mouseenter","img[generate]",function(e){
                        this.className = "closeIconOn";
                    });
                    
                    jQuery(".lookupInput").on("mouseleave","img[generate]",function(e){
                        this.className = "closeIcon"
                    });
                    
                    jQuery(".lookupInput").on("click","img[generate]",function(e){
                        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');
                            if(hidden){
                                hidden.value = '';
                            }
                        }
                    });
                });
            </script>
            <div class="pbBottomButtons">
                <table cellspacing="0" cellpadding="0" border="0">
                    <tbody>
                        <tr>
                            <td class="pbTitle">
                                <img src="/img/s.gif" alt="" class="minWidth" title="" width="1" height="1" />&nbsp;</td>
                            <td class="pbButtonb" id="bottomButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveOnCallProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveOnCallProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </apex:pageblock>
 
    </apex:form>
</apex:page>