高章伟
2022-02-18 8b5f4c6c281cfa548f92de52c8021e37aa81901e
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<apex:page standardController="Lead" extensions="NewAndEditLeadController">
    <script src="../../soap/ajax/53.0/connection.js" type="text/javascript"></script>
    <script>
        var TestToken = 'eyJhbGciOiJIUzUxMiJ9.eyJjcmVhdGVkIjoxNjQzMDk5NDgyNjA2LCJhcHBpZCI6IjZMeml6Y1JmN2g4eUx4MjgiLCJleHAiOjE2NDM3MDQyODJ9.V_94zxiDwEa1jZpOphw9W4QfjmqqKQcjCZ4z31KsDe7SjCF9sxKSKiZe6rp8ML6-namlVSyzqpTeZQ6NJi88Og';
        var AWSAppId = '6LzizcRf7h8yLx28';
        var AWSAppSecret = 'UkLohQcHNjg164SdRc7gnS4rgu4d7FjINM3mtzRbyTS6IrUP5V';
        var NewLeadURL = 'https://52.83.101.205/api/lead/insert';
        var UpdateLeadURL = '';
        var QueryLeadURL = 'https://52.83.101.205/api/lead/query';
        var TransactionURL = "https://52.83.101.205/api/tx/confirm";
        var VLookUpFields = new Set(['Hospital_Name__c', 'Department_Class__c', 'Contact_Name__c', 'Campaign__c']);
        var LeadIdPage = "https://ocsm--stagefull--c.visualforce.com/apex/NewAndEditLead?RecordType=01210000000QiRa";
        // function ProcessPI(payloadForNewPI) {
        //     let TokenURL = "https://52.83.101.205/api/token/getToken?app_id=" + AWSAppId + "&app_secret=" + AWSAppSecret;
        //     console.log('Get Token Process');
        //     fetch(TokenURL, {
        //         method: 'GET',
        //         mode: 'no-cors',
        //         headers: {
        //             'Content-Type': 'application/json'
        //         }
        //     }).then((data) => {
        //         console.log(data.text())
        //         return data.text()
        //     }).then((awsToken) => {
        //         if({!isNewMode}){
        //             NewPIToAWS(awsToken, payloadForNewPI)
        //         }else{
        //             UpdatePIToAWS(awsToken, payloadForNewPI)
        //         }              
        //     });
        // }
 
        function loadAWSAuthentication() {
            console.log('Get Sesion Session');
            sforce.connection.sessionId = '{!GETSESSIONID()}';
            let awsConfiguration = "SELECT App_Id__c,App_Secret__c,New_Lead_URL__c FROM AWS_Integration_Info__mdt  WHERE DeveloperName = 'AWS_Integration_Configuration'";
            let awsConfigurationResult = sforce.connection.query(awsConfiguration);
            let recordsAWSConfiguration = awsConfigurationResult.getArray("records");
            if (recordsAWSConfiguration && recordsAWSConfiguration.length > 0) {
                recordAWSConfiguration = recordsAWSConfiguration[0];
                AWSAppId = recordAWSConfiguration.App_Id__c;
                AWSAppSecret = recordAWSConfiguration.App_Secret__c;
                NewLeadURL = recordAWSConfiguration.New_Lead_URL__c;
            }
            console.log('AWS Configuration:' + AWSAppId + '----- APP Secret:' + AWSAppSecret);
        }
 
        function getPIPayload(leadJson) {
            let leadPayloadList = [];
            let LastName = leadJson.LastName;
            let Email = leadJson.Email;
            let Phone = leadJson.Phone;
            let leadPIData = new Object();
            leadPIData.lastName = LastName;
            leadPIData.email = Email;
            leadPIData.phone = Phone;
            leadPIData.sfRecordId = '';
            console.log('Lead PI Data:' + leadPIData);
            leadPayloadList.push(leadPIData);
            console.log(JSON.stringify(leadPayloadList));
            return JSON.stringify(leadPayloadList);
        }
 
        function validateFieldValueFormate() {
            let textEmail = "[data-id='Email']";
            let textPhone = "[data-id='Phone']";
            //Email
            let email = document.querySelector(textEmail).value;
            let phone = document.querySelector(textPhone).value;
 
            let regEmail = /^[\w-]{3,12}@[\da-zA-Z]{2,6}\.[a-zA-Z]+$/;
            let regPhone = /^1[3|5|8|7][0-9]\d{4,8}$/;
 
            let emailFormate = regEmail.test(email);
            let phoneFormate = regPhone.test(phone);
 
            console.log(emailFormate);
            console.log(phoneFormate);
 
 
            email.oninput = function () {
                //email
                if (emailFormate) {
                    //phone
                    phone.oninput = function () {
                        if (phoneFormate) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            }
            return true;
        }
 
        function getLeadInformation() {
 
            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 {
                    result[nodelist[index].getAttribute("data-id")] = nodelist[index].value;
                }
            }
            console.log(JSON.stringify(result));
            console.log('lead Number:' + result.Lead_No__c);
            let leadJson = JSON.stringify(result);
            let transId = "11111";
            let AWSDataId = "22222";
 
            // Visualforce.remoting.Manager.invokeAction(
            //     '{!$RemoteAction.NewAndEditLeadController.saveLead}',
            //     leadJson, transId,{!isNewMode},
            //     function (result, event) {
            //         console.log("result: " + result);
            //         window.open('/' + result.recordId, "_self");
            //     },
            //     { escape: true }
            // );
            return result;
 
 
            //第二种
            // let leadJson = {};
            // let fieldApiList = '{!fieldApiListStr}'.substring(1, '{!fieldApiListStr}'.length - 1).replace(/\"/g, "").split(',');
            // for (var i in fieldApiList) {
            //     if(document.querySelector("[data-id=\"" + fieldApiList[i] + "\"]") != null){
            //         leadJson[fieldApiList[i]] = document.querySelector("[data-id=\"" + fieldApiList[i] + "\"]").value;
            //     }else{
            //         leadJson[fieldApiList[i]] = '';
            //     }
            // }
            // return leadJson;
        }
        function QueryLeadFromAWS(awsDataId) {
            fetch(QueryLeadURL + '?dataId=' + awsDataId, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'pi_token': TestToken
                }
            }).then((data) => {
                console.log('data = ' + data);
                document.querySelector("[data-id='LastName']").value = data.object[0].lastName;
                document.querySelector("[data-id='phone']").value = data.object[0].phone;
                document.querySelector("[data-id='email']").value = data.object[0].email;
            })
        }
        function UpdatePIToAWS(awsToken, payloadForNewPI) {
            fetch(UpdateLeadURL, {
                method: 'POST',
                body: payloadForNewPI,
                headers: {
                    'Content-Type': 'application/json',
                    //'token': awsToken
                }
            }).then((data) => { return data.json() }).then((result) => {
                let r = JSON.parse(result);
                console.log('Result from AWS' + r);
                leadJson.lastName = r.object[0].lastName;
                leadJson.phone = r.object[0].phone;
                leadJson.email = r.object[0].email;
                leadJson.Name_Encrypted__c = r.object[0].lastNameEncrypt;
                leadJson.Phone_Encrypted__c = r.object[0].phoneEncrypt;
                leadJson.Email_Encrypted__c = r.object[0].emailEncrypt;
                leadJson.AWS_Data_Id__c = '{!AWSDataId}';
                let transId = result.txId;
                let AWSDataId = r.object[0].dataId;
 
                // Assign the value to NonPII Data Payload
                //7. New NonPII Data To Salesforce
                Visualforce.remoting.Manager.invokeAction(
                    '{!$RemoteAction.NewAndEditLeadController.saveLead}',
                    leadJson, transId, {!isNewMode},
                function (result, event) {
                    if (event.status) {
                        if (result.stauts == 'success') {
                            //get Lead Id from sf backend
                            let leadId = result.recordId;
 
                            //8. Confirm Trans to AWS
                            transParameters = {
                                txId: transId,
                                isSuccess: event.status
                            };
                            fetch(TransactionURL, {
                                method: 'POST',
                                body: JSON.stringify(transParameters),
                                headers: {
                                    'Content-Type': 'application/json',
                                    // 'token': awsToken
                                }
                            }).then((result) => {
                                if (JSON.parse(result).status == 0) {
                                    //9. Redirect to lead Id page.
                                    window.location.href = LeadIdPage;
                                    // let data = {
                                    //     transId:result.txId,
                                    //     dataId:dataId,
                                    //     status:result.status
                                    // }
                                    // return JSON.stringify(data);
                                }
                            })
                            // window.open(LeadIdPage);
                            // console.log(result);
                            // window.location.href = LeadIdPage;
                        } else {
                            //result.stauts == 'fail'
                        }
                    }
                },
                { escape: true }
            );
        }).catch (error => {
            console.log(error);
        });
        }
        function NewPIToAWS(leadJson,awsToken, payloadForNewPI) {
            console.log('Process New PI Data');
            console.log(JSON.stringify(payloadForNewPI));
            fetch(NewLeadURL, {
                method: 'POST',
                body: payloadForNewPI,
                headers: {
                    'Content-Type': 'application/json',
                    'pi_token': awsToken
                }
            }).then((data) => { console.log('data='+data);return data.json() }).then((result) => {
                console.log(result);
                let r = result;
                console.log('Result from AWS' + r);
                console.log('leadJson='+leadJson);
                leadJson.lastName = r.object[0].lastName;
                leadJson.phone = r.object[0].phone;
                leadJson.email = r.object[0].email;
                leadJson.Name_Encrypted__c = r.object[0].lastNameEncrypt;
                leadJson.Phone_Encrypted__c = r.object[0].phoneEncrypt;
                leadJson.Email_Encrypted__c = r.object[0].emailEncrypt;
                leadJson.AWS_Data_Id__c = 'testAWSID';
                let transId = result.txId + '';
                let AWSDataId = r.object[0].dataId;
 
                // Assign the value to NonPII Data Payload
                //7. New NonPII Data To Salesforce
                Visualforce.remoting.Manager.invokeAction(
                    '{!$RemoteAction.NewAndEditLeadController.saveLead}',
                    JSON.stringify(leadJson), transId, {!isNewMode},
                function (result, event) {
                    if (event.status) {
                        console.log('Lead Id from SF Backend:'+JSON.stringify(result));
                        if (result.status == 'success') {
                            //get Lead Id from sf backend
                            let leadId = result.recordId;                           
                            window.open('/'+leadId,'_self');
                            //8. Confirm Trans to AWS
                            // transParameters = {
                            //     txId: transId,
                            //     isSuccess: result.status
                            // };
                            // fetch(TransactionURL, {
                            //     method: 'POST',
                            //     body: JSON.stringify(transParameters),
                            //     headers: {
                            //         'Content-Type': 'application/json',
                            //         'pi_token': TestToken
                            //     }
                            // }).then((result) => {
                            //     if (JSON.parse(result).status == 0) {
                            //         //9. Redirect to lead Id page.
                            //         window.location.href = LeadIdPage;
                            //         // let data = {
                            //         //     transId:result.txId,
                            //         //     dataId:dataId,
                            //         //     status:result.status
                            //         // }
                            //         // return JSON.stringify(data);
                            //     }
                            // })
                            // window.open(LeadIdPage);
                            // console.log(result);
                            // window.location.href = LeadIdPage;
                        } else {
                            //result.stauts == 'fail'
                        }
                    }
                },
                { escape: true }
            );
        }).catch (error => {
            console.log(error);
        });
        }
        function saveLeadProcess() {
            //1. Get Lead Information from Form
            let leadJson = getLeadInformation();
            //2. Validate the Lead 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
            //     alert('邮箱或电话号码格式有误');
            // }
 
            // //3. Prepare the payload for New PI API To AWS - To Do
            let payloadForNewPI = getPIPayload(leadJson);
 
            // //4. Get Authentication Information for AWS
            // loadAWSAuthentication();
 
            // //5. lead to AWS 
            //ProcessPI(payloadForNewPI);
            awsToken = TestToken;
            NewPIToAWS(leadJson,awsToken, payloadForNewPI)
        }
    </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=leads_edit.htm&amp;section=Leads&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 >
        <!-- Error Msg-->
        <apex:pageMessages />
        <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">
                                <input class="btn" type="Button" value="保存" onclick="saveLeadProcess()" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveLeadProcess()" />
                                <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 html-data-id="{!layoutField.fieldAPI}" value="{!Lead[layoutField.fieldAPI]}" rendered="{!not(layoutField.isPlaceHOlder)}"
                            required="{!layoutField.isRequired}" />
                        <apex:pageblocksectionitem rendered="{!layoutField.isPlaceHolder}">
                        </apex:pageblocksectionitem>
                    </apex:repeat>
 
                </apex:pageBlockSection>
            </apex:repeat>
            <script>
                sfdcPage.appendToOnloadQueue(function () {
                    //1. Set Last Name label
                    document.querySelector("[data-id='LastName']").parentNode.parentNode.parentNode.children[2].children[0].innerText = '姓名';
                    //2. Query AWS Data by dataId 
                    console.log('Mode for Lead Page:' + {!isNewMode});
                if (!{!isNewMode}) {
                    //2.1. Query AWS Data by 
                    let leadPIData = QueryLeadFromAWS({!awsDataId});
                        //2.2. Update the value to Front-End
                        //document.querySelector("[data-id='LastName']").value = '234234';
                    }   
                });
            </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">
                                <input class="btn" type="Button" value="保存" onclick="saveLeadProcess()" />
                                <input class="btn" type="Button" value="保存并新建" onclick="saveLeadProcess()" />
                                <apex:commandButton action="{!cancel}" value="取消" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </apex:pageblock>
 
    </apex:form>
</apex:page>