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
<apex:page standardController="Consum_Apply_Equipment_Set_Detail__c" extensions="NewConsumApplyEquipSetDetailController" 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
        var staticResources = JSON.parse('{!staticResource}');
        var requiredFieldAPIList = JSON.parse('{!requiredFieldAPIListStr}');
        var fieldAPIToLabelMap = JSON.parse('{!fieldAPIToLabelMapStr}');
        var VLookUpFields = new Set(['Consum_Apply__c','Consum_Apply_Equipment_Set__c','Asset__c','Canceled__c','DeliverySlip__c','Return_DeliverySlip__c']);
        var userVLookUpFields = ['Follower_User__c','Consum_Assign_Person__c','Asset_Center_Confirm_Staff__c','Return_Operator__c','Return_wh_chenk_staff__c','Cancel_Mem__c','Lost_item_check_staff__c','Lost_item_check_staff_Final__c'];
        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("[data-id='Trial_User__c']").value = data.object.trialUser;
            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.Trial_User__c = r.object[0].trialUser;
            payloadJson.Trial_User_Encrypt__c = r.object[0].trialUserEncrypt;
            payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            if (isNewMode || {!isCloneMode}) {
                payloadJson.AWS_Data_Id__c = r.object[0].dataId;
            } else {
                payloadJson.AWS_Data_Id__c = '{!AWSDataId}';
            }
            debugger
            return payloadJson;
        }
 
        // New Or Edit
        function ProcessPI(consumApplyJson, payloadForNewPI) {
            blockme();
            if ({!isNewMode} || {!isCloneMode}) {
                NewPIToAWS(consumApplyJson, payloadForNewPI)
            }else {
                UpdatePIToAWS(consumApplyJson, payloadForNewPI)
            }
        }
 
        //Get Sensitive Information
        function getPIPayload(consumApplyJson) {
            let consumApplyPayloadList = [];
            let trialUser = consumApplyJson.Trial_User__c;
            let consumApplyPIData = new Object();
            consumApplyPIData.trialUser = trialUser;
            consumApplyPIData.sfRecordId = '';
            console.log('consumApply PI Data:' + JSON.stringify(consumApplyPIData));
            consumApplyPayloadList.push(consumApplyPIData);
            console.log(JSON.stringify(consumApplyPayloadList));
            return JSON.stringify(consumApplyPayloadList);
        }
 
        //Check Validate Field Value
        function validateFieldValueFormate() {
            return true;
        }
 
        //Get Page Information
        function getConsumApplyInformation() {
            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';
                        if(document.getElementById(vlookUpNodeId)!=null){
                            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++;
                }
            }
            for (let i = 0; i < userVLookUpFields.length; i++) {
                let userVlookUpNodeValue = document.querySelector("[data-id='" + userVLookUpFields[i] + "']").children[1].value;
                console.log('userVlookUpNodeValue:'+userVlookUpNodeValue);
                if(userVlookUpNodeValue!='000000000000000'){
                    result[userVLookUpFields[i]] = userVlookUpNodeValue;
                }               
            }
            result.Consum_Apply_Equipment_Set__c = document.querySelector('[data-id=Consum_Apply_Equipment_Set__c]').textContent;
            console.log(JSON.stringify(result));
            return result;
        }
 
        //Query from AWS
        function QueryConsumApplyFromAWS() {
            AWSService.query(staticResources.queryUrl, '{!AWSDataId}', queryBack, staticResources.token);
        }
 
        //Update Sensitive Information to AWS
        function UpdatePIToAWS(consumApplyJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.NewConsumApplyEquipSetDetailController.saveConsumApply}';
            let obj = JSON.parse(payloadForNewPI);
            obj[0].dataId = '{!AWSDataId}';
            let payloadForNewPIJson = JSON.stringify(obj);
            AWSService.update(staticResources.updateUrl, consumApplyJson, payloadForNewPIJson, controllerSaveMethod, staticResources.token, staticResources.transactionUrl, false, insertOrUpdateBack, redirectCallBack);
        }
 
        //Insert Sensitive Information to AWS
        function NewPIToAWS(consumApplyJson, payloadForNewPI) {
            let controllerSaveMethod = '{!$RemoteAction.NewConsumApplyEquipSetDetailController.saveConsumApply}';
            AWSService.insert(staticResources.newUrl, consumApplyJson, 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 saveConsumApplyProcess(saveMode) {
            redirectMode = saveMode;
            console.log('redirectMode' + redirectMode);
            hiddenErrorMsgNode();
            //1. Get consumApply Information from Form
            let consumApplyJson = getConsumApplyInformation();
            //2. Validate the consumApply 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(consumApplyJson);
            if (checkRequiredFieldMsgResult) {
                alertErrorMessage('{!Input_Required_Field_Msg}' + checkRequiredFieldMsgResult);
                return
            }
            //3. Prepare the payload for New PI API To AWS - To Do
            let payloadForNewPI = getPIPayload(consumApplyJson);
 
            //4. consumApply to AWS 
            ProcessPI(consumApplyJson, payloadForNewPI);
        }
 
        //Alert Error Message
        function alertErrorMessage(errorMsg) {
            let errorMsgNode = document.getElementById("page:form:msgContent");
            errorMsg = '错误:无效数据。' + '\n' + errorMsg;
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'pbError';
            unblockUI();
        }
 
        //Hide Error Message
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:form:msgContent");
            errorMsgNode.innerText = '';
            errorMsgNode.className = '';
        }
    </script>
    <div class="bPageTitle">
        <div class="ptBody">
            <div class="content">
                <img src="/img/s.gif" alt="耗材备品配套一览明细" class="pageTitleIcon" title="耗材备品配套一览明细" />
                <h1 class="pageType">耗材备品配套一览明细编辑
                    <span class="titleSeparatingColon">:</span>
                </h1>
                <h2 class="pageDescription">新建耗材备品配套一览明细</h2>
                <div class="blank">&nbsp;</div>
            </div>
            <div class="links">
                <a href="javascript:openPopupFocusEscapePounds(%27https://help.salesforce.com/apex/htdoor?loc=help&amp;target=consumApplys_edit.htm&amp;section=consumApplys&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">
        <!-- Error Msg-->
        <apex:outputPanel id="errorMsg">
            <apex:pageMessages id="msgContent" escape="false" />
        </apex:outputPanel>
        <apex:pageblock >
            <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">耗材备品配套一览明细编辑</h2>
                            </td>
                            <td class="pbButton" id="topButtonRow" style="pointer-events: none; opacity: 0.4;">
                                <input class="btn" type="Button" value="保存" onclick="saveConsumApplyProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveConsumApplyProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </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="{!Consum_Apply_Equipment_Set_Detail__c[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)&&isNewMode}"
                            required="{!layoutField.isRequired}" />
                        <apex:inputField styleClass="PIBackApi PIBackApi_{!layoutField.fieldAPI}" html-data-id="{!layoutField.fieldAPI}" value="{!Consum_Apply_Equipment_Set_Detail__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="{!Consum_Apply_Equipment_Set_Detail__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>
                //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 consumApply Page:' + {!isNewMode});
                    if (!{!isNewMode}) {
                        blockme();
                        QueryConsumApplyFromAWS();
                    };
                    //document.querySelector("[data-id='OwnerId']").classList.add("disabledbutton");
                    
                    document.getElementById('topButtonRow').style = '';
             document.getElementById('bottomButtonRow').style = '';
                    //zhj 2022/04/11 start
                    // 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 = '';
                    //         }
                    //     }
                    // });
                    //zhj 2022/04/11 end
                });
            </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="saveConsumApplyProcess('Save')" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveConsumApplyProcess('SaveAndNew')" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </apex:pageblock>
 
    </apex:form>
</apex:page>