GWY
2022-04-27 12b7399736e90d33bfe0c2d29917d6f075246e00
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
public with sharing class DataLoadAccountController {
 
    public List<String> StringList {get; set;}
 
    public String  campaignId {get; set;}
 
    public List<CampaignRelationship__c> CRList {get; set;}
 
    public List<AccountContactInfo> ACInfoList {get; set;}
    public Blob contentFile { get; set; }
    public String nameFile { get; set; }
 
    public Boolean errorFlag { get; set; }
    public String errorMessage {get; set;}
 
    public Map<String, List<Contact>> upsertContactMap;
    public Map<String, Account> upsertAccountMap;
    public Map<String,Account> accountMap;
    public Map<String,String> accountIsUpdateMap;
    public Map<String,String> accountInDealerMap;
 
 
    private Integer line_Account_ProductSegment = 0;//分野
    private Integer line_Account_accountName = 1;//客户名
    private Integer line_Account_DivisionName_D = 2;//部门
    private Integer line_Account_approver = 3;//审批人
    private Integer line_Account_Province = 4;//省
    private Integer line_Account_CityD = 5;//市
    private Integer line_Account_Address1D = 6;//客户地址
    private Integer line_Account_PostCodeD = 7;//客户邮编
    private Integer line_Account_Sub_UseD = 8;//客户Sub_Use;
    private Integer line_Account_EnglishNameD = 9;//客户英文名称(IE)
    private Integer line_Account_CustomerSource = 10;//客户来源
    private Integer line_Account_UserType = 11;//用户属性
    private Integer line_Account_TargetCustomer = 12;//客户类型
    private Integer line_Account_Remark = 13;//客户备注
    private Integer line_Contact_LastName = 14;//联系人姓名
    private Integer line_Contact_Address1D = 15;//联系人地址
    private Integer line_Contact_MobilePhoneD = 16;//联系人手机
    private Integer line_Contact_PostcodeD = 17;//联系人邮编
    private Integer line_Contact_Remark = 18;//联系人备注
    private Integer line_nineteen;
 
    public String baseUrl { get; set; }
 
    public DataLoadAccountController() {
 
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0, path.indexOf('/apex'));
        }
        campaignId = System.currentPageReference().getParameters().get('campaignId');
        ACInfoList = new List<AccountContactInfo>();
    }
 
    public PageReference init() {
        ACInfoList = new List<AccountContactInfo>();
        return null;
    }
 
    public PageReference csvRead() {
 
        String strFile = '';
        List<String> listFile = new List<String>();
        errorFlag = false;
        errormessage = null;
 
        List<String> errormessageList = new List<String>();
        Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
        try {
            if (contentFile != null) {
                strFile = contentFile.toString();
                listFile = strFile.split('\n');
            } else {
                errorFlag = true;
                errormessage = '读取内容为空。';
                errormessageList.add(errormessage);
                errormessageMap.put('导入文件异常', errormessageList);
                Pageerrormessage(errormessageMap);
                return null;
            }
        } catch (Exception ex) {
            errorFlag = true;
            errormessage = '读取的文件不是CSV文件或CSV文件的编码不是UTF-8';
            errormessageList.add(errormessage);
            errormessageMap.put('导入文件异常', errormessageList);
            Pageerrormessage(errormessageMap);
            return null;
        }
 
        List<String[]> arrayFile = new List<String[]>();
        String firstline = listFile[0];
        if (firstline.indexOf('客户分野') < 0) {
            errorFlag = true;
            errormessage = '读取内容格式不正确。';
            errormessageList.add(errormessage);
            errormessageMap.put('导入文件异常', errormessageList);
            Pageerrormessage(errormessageMap);
            return null;
        } else {
            String strReplace = '';
            List<String> temp = strFile.split('"');
            for (Integer i = 0; i < temp.size(); i++) {
                if (math.mod(i, 2) == 1) {
                    temp[i] = temp[i].replace(',', '#%&');
                }
                strReplace += temp[i];
            }
            // system.debug('=====strReplace:' + strReplace);
            List<String> listReplace = strReplace.split('\n');
            for (String replace : listReplace) {
                system.debug('=====replace:' + replace);
                if (replace != '\r' && replace.length() > 0) {
                    replace = replace.replace('\r', '');
                    String[] a = replace.split(',', -1);
                    for (Integer i = 0; i < a.size(); i++) {
                        if (a[i].indexOf('#%&') > 0) {
                            a[i] = a[i].replace('#%&', ',');
                        }
                    }
                    // 验证导入的模板有多少列
                    if (a.size() != 19) {
                        errorFlag = true;
                        errormessage = '读取内容格式不正确。Line:' + arrayFile.size();
                        errormessageList.add(errormessage);
                        errormessageMap.put('导入文件异常', errormessageList);
                        Pageerrormessage(errormessageMap);
                        return null;
                    }
                    
                    arrayFile.add(a);
                }
            }
        }
 
        if (arrayFile.size() > 1) {
 
            checkFields(arrayFile);
        }
        
        return null;
    }
 
    public PageReference save() {
        system.debug('upsertAccountMap-----><----' + upsertAccountMap);
 
        Savepoint sp = Database.setSavepoint();
        // try {
            List<CampaignRelationship__c> insertCampaignRelationshipList = new List<CampaignRelationship__c>();
            if (upsertAccountMap != null && upsertAccountMap.size() > 0) {
 
                // 保存客户
                upsert upsertAccountMap.values();
                List<Contact> upsertContactList = new List<Contact>();
                Map<String,Contact> insertContactMap = new Map<String,Contact>();
                for (String accountkey : upsertAccountMap.keySet()) {
                    String productSegment = upsertAccountMap.get(accountkey).ProductSegment__c;
                    String accountId = upsertAccountMap.get(accountkey).Id;
                    if (upsertContactMap != null && upsertContactMap.size() > 0) {
                        if (upsertContactMap.containsKey(accountkey)) {
                            // 给联系人赋值客户Id
                            for (Contact contact : upsertContactMap.get(accountkey)) {
                                if (String.isNotBlank(contact.LastName)) {
                                    contact.CampaignUpsertContact__c = true;
                                    if (String.isBlank(contact.Id)) {
                                        contact.AccountId = accountId;
                                        upsertContactList.add(contact);
                                    } else {
                                        insertContactMap.put(contact.Id, contact);
                                    }
                                    
                                    // upsertContactList.add(contact); 
                                }
                                
                            }
                        }
                    }
 
                    String accountName = upsertAccountMap.get(accountkey).FacilityNameD__c;
                    String divisionName = upsertAccountMap.get(accountkey).DivisionName_D__c;
                    String accountAssemblyName = accountName + divisionName;
                    // 若客户已存在,创建客户-市场活动关系,若客户不存在,那么客户创建完成之后,会在trigger里创建客户-市场活动关系
                    if ( accountMap != null && accountMap.containsKey(accountAssemblyName)) {
                        
                        CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,productSegment);
                        
                        insertCampaignRelationshipList.add(campaignRelationship);
                    }
                    
                }
                
 
                // 保存联系人
                // if (upsertContactMap != null && upsertContactMap.size() > 0) {
                //     // upsert upsertContactMap.values();
                //     Integer Error01 = Integer.valueOf('TEST--->'+upsertContactMap);
                // }
                if (upsertContactList.size() > 0) {
                    upsert upsertContactList;
                }
 
                if (insertContactMap != null && insertContactMap.size() >0) {
                    update insertContactMap.values();
                }
            
            } 
            // 若客户已在代理商下,那么创建客户-市场活动关系
            if (accountInDealerMap != null && accountInDealerMap.size() > 0) {
 
                for (String accountId : accountInDealerMap.keySet()) {
                    CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,accountInDealerMap.get(accountId));
                    insertCampaignRelationshipList.add(campaignRelationship);
                }
            }
 
            // 保存客户-市场活动关系
            if (insertCampaignRelationshipList.size() > 0) {
                insert insertCampaignRelationshipList;
            }
        // } catch (Exception e) {
        //     errorFlag = true;
        //     ApexPages.addMessages(e);
        //     Database.rollback(sp);
        //     return  null;
        // }
        return null;
    }
    // 客户-市场活动关系 赋值
    public CampaignRelationship__c campaignRelationshipAssembly(String accountId,String productSegment){
        CampaignRelationship__c result = new CampaignRelationship__c();
        result.RelationshipAccount__c = accountId;
        result.RelationshipCampaign__c = campaignId;
        result.RelationshipProductSegment__c = productSegment;
        return result;
    }
    // 数据验证及数据拼装
    public void checkFields(List<String[]> arrayFile) {
        Integer no = 1;
        AccountContactInfo ifno = new AccountContactInfo(no);
        // 查找审批人
        Map<String,User> userMap = getUser(arrayFile);
 
        accountMap = new Map<String,Account>();
        // 根据导入文件的客户名称与部门名称以及分野,去系统中查找市场部创建的客户
        accountMap = getAccountMap(arrayFile);
        accountIsUpdateMap = new Map<String,String>();
        // 查找客户下的客户团队是否有代理商用户,借此判断客户是否在代理商下
        accountIsUpdateMap = getAccountTeamMemberList(accountMap);
        // 查找联系人
        Map<String,Contact> contactMap = getContactMap(accountMap);
        // 客户在代理商下
        accountInDealerMap = new Map<String,String>();
 
 
        
        String tem = '';
 
        upsertContactMap = new Map<String, List<Contact>>();
        upsertAccountMap = new Map<String, Account>();
        Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
        for (Integer line = 1; line < arrayFile.size(); line++) {
            List<Contact> countList = new List<Contact>();
            Account account = new Account();
            Contact contact = new Contact();
            // 客户分野不为空
            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {
 
                tem = arrayFile[line][line_Account_ProductSegment];
                String accountName= arrayFile[line][line_Account_accountName];
                String divisionName= arrayFile[line][line_Account_DivisionName_D];
                if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
                    tem += ':' + accountName + divisionName;
                } else {
                    Integer fileNo = line+1;
                    List<String> errormessageList = new List<String>();
                    errormessageList.add( '导入文件第 [ ' + fileNo + ' ] 行 客户名称或部门名称为空,请确认,此条客户与联系人跳过');
                    tem += '-' + fileNo;
                    errormessageMap.put(tem,errormessageList);
                    continue;
                }
                // 验证客户是否符合规则
                if (accountFieldCheck(arrayFile[line], errormessageMap, tem,userMap)) {
 
                    account = accountAssembly(arrayFile[line],userMap);
                    String managementCode  = '';
                    
                    if (accountMap != null && accountMap.size() > 0 ) {
                        String accountId = getAccountId(accountMap,arrayFile[line], errormessageMap, tem);
                        if (String.isNotBlank(accountId)) {
                            account.Id = accountId;
                            
                            String key = accountName + divisionName;
                            managementCode = accountMap.get(key).ManagementCode_F__c;
                        }
                    }
 
                    // 此处需要处理重名客户
                    if (!upsertAccountMap.containsKey(tem)) {
                        // 判断客户是否已在代理商下,在代理商下不更新客户
                        if (accountIsUpdateMap != null && accountIsUpdateMap.size() > 0) {
                            // 客户更新
                            if (String.isNotBlank(account.Id)) {
                                // 判断客户是否已在代理商下,若不在代理商下更新客户基本信息
                                if (!accountIsUpdateMap.containsKey(account.Id)) {
                                    upsertAccountMap.put(tem, account);
                                } else {
                                    
                                    accountInDealerMap.put(account.Id, tem.split(':')[0]);
                                    List<String> errormessageList = new List<String>();
                                    errormessage = '客户名:' + tem.split(':')[1] +divisionName+ ' 客户编码 [ '+managementCode+' ] 已在代理商下;此条客户与联系人不会被更新,仅创建 客户-市场活动关系';
                                    errormessageList.add(errormessage);
                                    errormessageMap.put(tem, errormessageList);
                                    // 若客户在代理商下 ,客户导入页面会显示该客户的信息,但是不会更新客户
                                    // continue;
                                }
                            } else {
                                // 客户新增
                                upsertAccountMap.put(tem, account);
                            }
                            
                        } else {
                            // 客户新增
                            upsertAccountMap.put(tem, account);
                        }
                        
                    } else {
                        List<String> errormessageList = new List<String>();
                        errormessage = '分野:'+ tem.split(':')[0] + ',客户名:' + tem.split(':')[1] + ' 重名,此条客户与联系人跳过';
                        errormessageList.add(errormessage);
                        tem += 'Error';
                        errormessageMap.put(tem, errormessageList);
                        system.debug('tem------>' + tem);
                        continue;
                        
                    }
                    // 判断与客户同一行的联系人字段是否都为空值
                    if (FirstContactIsNull(arrayFile[line])) {
                        ifno = new AccountContactInfo(no, account);
                        ACInfoList.add(ifno);
                        no++;
                    } else {
                        // 检查联系人字段是否有异常
                        if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
                            contact = contactAssembly(arrayFile[line], tem);
                            // 若客户在代理商下 客户导入页面会显示联系人信息,但是不会更新联系人信息
                            if (accountInDealerMap != null && accountInDealerMap.size() > 0 && accountInDealerMap.containsKey(account.Id)) {
                                ifno = new AccountContactInfo(no, account, contact);
                                ACInfoList.add(ifno);
                                no++;
                                continue;
                            }
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
                            countList.add(contact);
                            upsertContactMap.put(tem, countList);
                            ifno = new AccountContactInfo(no, account, contact);
                            ACInfoList.add(ifno);
                            no++;
                        } else {
                            errormessageMap.putAll(errormessageMap);
                        }
                    }
                } else {
                    errormessageMap.putAll(errormessageMap);
                }
 
                system.debug('tem---->' + tem);
            } else {
                if (upsertAccountMap.containsKey(tem)) {
                    if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
                        // 将同一客户下的联系人放到同一个联系人集合中
                        if (upsertContactMap.containsKey(tem)) {
                            contact = contactAssembly(arrayFile[line], tem);
                            account = upsertAccountMap.get(tem);
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
                            List<Contact> contacts = upsertContactMap.get(tem);
                            contacts.add(contact);
                            upsertContactMap.put(tem, contacts);
                            
                            ifno = new AccountContactInfo(no, account, contact);
                            ACInfoList.add(ifno);
                            no++;
                        } else {
                            // 同一客户下的前面的联系人都为空或验证不通过。将剩余符合规则的放入联系人集合中。
                            contact = contactAssembly(arrayFile[line], tem);
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
                            countList.add(contact);
                            upsertContactMap.put(tem, countList);
                            account = upsertAccountMap.get(tem);
                            ifno = new AccountContactInfo(no, account, contact);
                            ACInfoList.add(ifno);
                            no++;
                        }
 
                    } else {
                        errormessageMap.putAll(errormessageMap);
                    }
                }
                
 
            }
        }
        // 异常信息页面展示
        if (errormessageMap != null && errormessageMap.size() > 0) {
            Pageerrormessage(errormessageMap);
        
        }
    }
    // 异常信息
    public void Pageerrormessage(Map<String, List<String>> errormessageMap) {
 
        errorFlag = true;
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '以下数据含有异常信息,请确认!!!'));
        for (String key :errormessageMap.keySet()) {
            if (key.indexOf(':') > 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '客户 '+ key.split(':')[1] + ':'));
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '客户 '+ key + ':'));
            }
            for (String errorm :errormessageMap.get(key)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '--->'  + errorm)); 
            }
            
        }
 
    }
    // 验证与客户同一行的联系人字段是否都为空
    public Boolean FirstContactIsNull(String[] strList){
        Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
        Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
        Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
        Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);
 
        if (contactNameflag && contactAddrflag && contactPhoneflag && contactPostflag) {
            return true;
        }
        return false;
    }
 
 
    // 为联系人字段赋值
    public Contact contactAssembly(String[] strList,String tem) {
 
        Contact result = new Contact();
        result.LastName = strList[line_Contact_LastName];
        result.FirstName = null;
        result.Address1D__c = strList[line_Contact_Address1D];
        result.MobilePhoneD__c = strList[line_Contact_MobilePhoneD];
        result.PostcodeD__c = strList[line_Contact_PostcodeD];
        result.Remark__c = strList[line_Contact_Remark];
        result.ContactStatusD__c = 'Active';
        //result.StatusD__c = 'Pass';
        if (tem.split(':')[0] == 'IE') {
            result.ProductSegmentIE__c = true;
        } else if (tem.split(':')[0] == 'RVI') {    
            result.ProductSegmentRVI__c = true;
        } else if (tem.split(':')[0] == 'NDT') {
            result.ProductSegmentNDT__c = true;
        } else if (tem.split(':')[0] == 'ANI') {
            result.ProductSegmentANI__c = true;
        }  
        
        return result;
    }
    // 为客户字段赋值
    public Account accountAssembly(String[] strList,Map<String,User> userMap) {
 
        Account result = new Account();
        String productSegment = strList[line_Account_ProductSegment];
        result.ProductSegment__c = productSegment;
        result.FacilityNameD__c = strList[line_Account_accountName];
        result.FacilityName__c = strList[line_Account_accountName];
        result.Name = '*';
        result.DivisionName_D__c = strList[line_Account_DivisionName_D];
        String approver = strList[line_Account_approver].replaceAll(' ', '');
        result.DealerSelectOwner__c = userMap.get(approver).Id;
        result.Province__c = strList[line_Account_Province];
        result.CityD__c = strList[line_Account_CityD];
        result.Address1D__c = strList[line_Account_Address1D];
        result.PostCodeD__c = strList[line_Account_PostCodeD];
        String subUse = '';
        if ((productSegment != 'IE') && '汽车'.equals(strList[line_Account_Sub_UseD])) {
            subUse = 'Automotive';
        } else if ('其他'.equals(strList[line_Account_Sub_UseD])){
            subUse = 'Others';
        } else {
            subUse = strList[line_Account_Sub_UseD];
        }
        result.Sub_UseD__c = subUse;
 
        result.AccountCampaign__c = campaignId;
        if ('IE'.equals(productSegment)) {
            result.EnglishNameD__c = strList[line_Account_EnglishNameD];
            result.CustomerSource__c = strList[line_Account_CustomerSource];
            result.UserType__c = strList[line_Account_UserType];
            result.TargetCustomer__c = strList[line_Account_TargetCustomer];
            result.Sub_UseA__c = subUse;
            if(subUse.startsWith('Compo')){
                result.compo_Acc__c = 'COMPO客户';
            }else{
                result.compo_Acc__c = '非COMPO客户';
            }
        }
        
        result.Remark__c = strList[line_Account_Remark];
 
        result.AccountStatusD__c = 'Active';
 
        if (productSegment == 'IE') {
            result.recordTypeId = '01228000000TdF6';
        } else if (productSegment == 'RVI') {
            result.recordTypeId = '01228000000TdFB';
        } else if (productSegment == 'NDT') {
            result.recordTypeId = '01228000000TdFG';
        } else if (productSegment == 'ANI') {
            result.recordTypeId = '01228000000TdFL';
        }
        return result;
    }
    // 获取审批人
    public Map<String,User> getUser(List<String[]> arrayFile){
        Map<String,User> result = new Map<String,User>();
        List<String> approverList = new List<String>();
        //查找审批人是否存在
        for (Integer line = 1; line < arrayFile.size(); line++) {
            //客户分野
            Boolean productSegment = String.isBlank(arrayFile[line][line_Account_ProductSegment]);
            //审批人
            Boolean approver = String.isBlank(arrayFile[line][line_Account_approver]);
            if (!productSegment && !approver) {
                approverList.add(arrayFile[line][line_Account_approver]);
            }
        }
 
        if (approverList.size() > 0) {
 
            List<User> userList = [SELECT id,Name,LastName,FirstName 
                                   FROM User ];
 
            if (userList.size() > 0) {
                for (User user :userList) {
                    String firstName = String.isBlank(user.FirstName) ? '' :user.FirstName;
                    String name = user.LastName + firstName;
                    result.put(name,user);
                }
            }
        }
 
        return result;
    }
    // 导入文件客户字段验证
    public Boolean accountFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem,Map<String,User> userMap) {
        //客户名称
        Boolean dealerNameflag = String.isBlank(strList[line_Account_accountName]);
 
        //部门名称
        Boolean deptNameflag = String.isBlank(strList[line_Account_DivisionName_D]);
        //审批人
        Boolean approverflag = String.isBlank(strList[line_Account_approver]);
        //省
        Boolean provinceflag = String.isBlank(strList[line_Account_Province]);
        //城市
        Boolean cityflag = String.isBlank(strList[line_Account_CityD]);
        //客户地址
        Boolean addressflag = String.isBlank(strList[line_Account_Address1D]);
        //邮编
        Boolean postflag = String.isBlank(strList[line_Account_PostCodeD]);
        //Sub Use
        Boolean sub_Useflag = String.isBlank(strList[line_Account_Sub_UseD]);
        //客户英文名称(IE验证)
        Boolean accountEnglishNameflag = String.isBlank(strList[line_Account_EnglishNameD]);
        //客户来源(IE验证)
        Boolean customerSourceflag = String.isBlank(strList[line_Account_CustomerSource]);
        //用户属性(IE验证)
        Boolean useRattributeflag = String.isBlank(strList[line_Account_UserType]);
        //客户类型(IE验证)
        Boolean targetCustomerflag = String.isBlank(strList[line_Account_TargetCustomer]);
 
        Boolean temflag = true;
        String errormessage = '';
        if (tem.indexOf(':') > 0) {
            errormessage = tem.split(':')[1] + ':';
        } else {
            errormessage = tem;
        }
 
        List<String> errormessageList = new List<String>();
 
        if (approverflag) {
            errormessage += ' 客户审批人不能为空,请确认;\n';
            temflag = false;
        } else {
            //验证审批人是否存在
            String approver = strList[line_Account_approver].replaceAll(' ', '');
 
            if (!userMap.containsKey(approver)){
                errormessage += ' 客户审批人 ['+strList[line_Account_approver]+'] 不存在,请确认;\n';
                temflag = false;
            } 
        }
        if (provinceflag) {
            errormessage += ' 客户省不能为空,请确认;\n';
            temflag = false;
        } else {
            
            Schema.DescribeFieldResult fieldResult = Account.Province__c.getDescribe();
 
            Map<String,String> accountProvinceMap =  getPickListValuesMap(fieldResult);
            String accountProvince = strList[line_Account_Province];
            if (!accountProvinceMap.containsKey(accountProvince)) {
                errormessage += ' 客户省的值异常,[ '+accountProvince+' ]请确认;\n';
                temflag = false;
            }
        }
        if (cityflag) {
            errormessage += ' 客户城市不能为空,请确认;\n';
            temflag = false;
        }
        if (addressflag) {
            errormessage += ' 客户地址不能为空,请确认;\n';
            temflag = false;
        }
        if (postflag) {
            errormessage += ' 客户邮政编码不能为空,请确认;\n';
            temflag = false;
        } else {
            Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
            Matcher mc = pt.matcher(strList[line_Account_PostCodeD]);
            if(!mc.matches()) {
                errormessage += ' 客户邮政编码不是6位数字,[ '+strList[line_Account_PostCodeD]+' ]请确认;\n';
                temflag = false;
            }
        }
        if (sub_Useflag) {
            errormessage += ' Sub Use不能为空,请确认;\n';
            temflag = false;
        } else {
            
            // 判断Sub Use是否符合分野所选值
            String segment = strList[line_Account_ProductSegment];
            String subUse = strList[line_Account_Sub_UseD];
            String key = segment + ':' + subUse;
            if (!SegmentSubUseMap.containsKey(key)) {
                String accountName = strList[line_Account_accountName];
                errormessage += accountName +'- Sub Use [ '+subUse + ' ] 的值无效,请确认;\n';
                temflag = false;
            }
        }
        if (strList[line_Account_ProductSegment] == 'IE') {
            if (accountEnglishNameflag) {
                errormessage += ' 客户的英文名称不能为空,请确认;\n';
                temflag = false;
            }
            if (customerSourceflag) {
                errormessage += ' 客户的客户来源不能为空,请确认;\n';
                temflag = false;
            } else {
                Schema.DescribeFieldResult fieldResult = Account.CustomerSource__c.getDescribe();
 
                Map<String,String> sourceMap =  getPickListValuesMap(fieldResult);
                String customerSource = strList[line_Account_CustomerSource];
                if (!sourceMap.containsKey(customerSource)) {
                    errormessage += ' 客户的客户来源值异常,[ '+customerSource+' ]请确认;\n';
                    temflag = false;
                }
            }
            if (useRattributeflag) {
                errormessage += ' 客户的用户属性不能为空,请确认;\n';
                temflag = false;
            } else {
                Schema.DescribeFieldResult fieldResult = Account.UserType__c.getDescribe();
 
                Map<String,String> userTypeMap =  getPickListValuesMap(fieldResult);
                String userType = strList[line_Account_UserType];
                if (!userTypeMap.containsKey(userType)) {
                    errormessage += ' 客户的用户属性值异常,[ '+userType+' ]请确认;\n';
                    temflag = false;
                }
            }
 
            if (targetCustomerflag) {
                errormessage += ' 客户的客户类型不能为空,请确认;\n';
                temflag = false;
            } else {
                Schema.DescribeFieldResult fieldResult = Account.TargetCustomer__c.getDescribe();
 
                Map<String,String> targetCustomerMap =  getPickListValuesMap(fieldResult);
                String targetCustomer = strList[line_Account_TargetCustomer];
                if (!targetCustomerMap.containsKey(targetCustomer)) {
                    errormessage += ' 客户的客户类型值异常,[ '+targetCustomer+' ]请确认;\n';
                    temflag = false;
                }
            }
 
        }
        if (temflag) {
            return true;
 
        } else {
            errormessageList.add(errormessage);
            errormessageMap.put(tem, errormessageList);
            return temflag;
        }
 
 
    }
    // 获取客户Id
    public String getAccountId(Map<String,Account> accountMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
        List<String> errormessageList = new List<String>();
        if (errormessageMap != null && errormessageMap.size() >0 && errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }
 
        String result = '';
        String accountName = strList[line_Account_accountName];
        String divisionName = strList[line_Account_DivisionName_D];
        String name = accountName + divisionName;
 
        if (accountMap.containsKey(name)) {
            result = accountMap.get(name).Id;
            String managementCode  = accountMap.get(name).ManagementCode_F__c;
            String errormessage = '客户:'+name+' 系统中已存在,客户编码 [ '+managementCode+' ],将更新此客户,请注意;\n';
            errormessageList.add(errormessage);
            errormessageMap.put(tem,errormessageList);
        }
 
 
        
        return result;
 
    }
    // 获取联系人Id
    public String getContactId(Account account, Map<String,Contact> contactMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
        List<String> errormessageList = new List<String>();
        if (errormessageMap != null && errormessageMap.size() >0 &&  errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }
        String result = '';
        String accountName = account.FacilityNameD__c;
        String divisionName = account.DivisionName_D__c;
        String accountAssemblyName = accountName + divisionName;
 
        String contactlastName = strList[line_Contact_LastName].replaceAll(' ', '');
 
        String key = accountAssemblyName + contactlastName;
        if (contactMap.containsKey(key)) {
            result = contactMap.get(key).Id;
            String managementCode  = contactMap.get(key).ManagementCode_F__c;
            String errormessage = '联系人:'+contactlastName+' 系统中已存在,联系人编码 [ '+managementCode+' ],将更新此联系人,请注意;\n';
            errormessageList.add(errormessage);
            errormessageMap.put(tem,errormessageList);
        }
        return result;
    }
    // 获取市场战略部创建的客户
    public Map<String,Account> getAccountMap( List<String[]> arrayFile) {
 
        Map<String,Account> result = new Map<String,Account>();
        List<String> accountNameList = new List<String>();
        String productSegment = '';
        for (Integer line = 1; line < arrayFile.size(); line++) {
            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {
                productSegment = arrayFile[line][line_Account_ProductSegment];
                String accountName = arrayFile[line][line_Account_accountName];
                String divisionName = arrayFile[line][line_Account_DivisionName_D];
                if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
                    String name = accountName + divisionName;
                    accountNameList.add(name);
                }
            }
        }
 
        if (accountNameList != null && accountNameList.size() > 0) {
            
             List<Account> accountList =    [SELECT id,Name,DivisionName_D__c,ProductSegment__c,createddate,OwnerId ,ManagementCode_F__c from Account where MarketingStrategyCreated__c = true AND Name = :accountNameList AND ProductSegment__c = :productSegment];
 
            if ( accountList.size() > 0) {
                for (Account account :accountList) {
                    result.put(account.Name, account);
                }
            }
        }
 
        return result;
    }
    // 查找市场战略部创建的客户下的联系人
    public Map<String,Contact> getContactMap(Map<String,Account> accountMap) {
 
        if (accountMap != null && accountMap.size() > 0) {
 
            Map<String,Contact> result = new Map<String,Contact>();
            List<String> accountIdList = new List<String>(); 
            for (String name : accountMap.keySet()) {
 
                String accountId = accountMap.get(name).Id;
                accountId = accountId.subString(0,15);
                accountIdList.add(accountId);
            }
 
            List<Contact> contactList = [ SELECT Id,ManagementCode_F__c,Name__c,AccountId__c,Account.Name from Contact where AccountId__c In :accountIdList Order by AccountId__c,Id];
 
            if (contactList.size() > 0) {
 
                for (Contact contact :contactList) {
                    String accountNameAndContactName = contact.Account.Name + contact.Name__c;
                    result.put(accountNameAndContactName,contact);
                }
            }
            return result;
        }
 
        return null;
        
    }
 
    // 查找客户下的客户团队中,是否有代理商用户
    public Map<String,String> getAccountTeamMemberList(Map<String,Account> accountMap) {
        
        if (accountMap != null && accountMap.size() > 0) {
            Map<String,String> result = new Map<String,String>();
            List<String> accountIdList = new List<String>(); 
            for (String name : accountMap.keySet()) {
 
                String accountId = accountMap.get(name).Id;
                accountIdList.add(accountId);
            }
 
            List<AccountTeamMember> accountTeamMemberList = [ SELECT Id, AccountId,Account.Name, UserId,User.User_Type__c FROM AccountTeamMember where User.User_Type__c = 'PowerPartner' AND AccountId in :accountIdList];
            if (accountTeamMemberList.size() > 0) {
                for (AccountTeamMember accountTeamMember :accountTeamMemberList) {
                    result.put(accountTeamMember.AccountId,accountTeamMember.UserId);
                }
                
            }
            return result;
        }
 
        return null;
    }
 
    // 验证导入文件的联系人数据
    public Boolean contactFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem) {
 
        Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
        Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
        Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
        Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);
        
        List<String> errormessageList = new List<String>();
        if (errormessageMap != null && errormessageMap.size() > 0 && errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }
        if (contactNameflag && ( !contactAddrflag || !contactPhoneflag || !contactPostflag)) {
            String errormessage = '联系人的姓氏不能为空,请确认;\n';
            errormessageList.add(errormessage);
            errormessageMap.put(tem, errormessageList);
            return false;
        } else if (!contactNameflag) {
            Boolean temflag = true;
            String contactName = strList[line_Contact_LastName];
            String errormessage = contactName + ':';
            if (contactAddrflag) {
                errormessage += ' 联系人地址不能为空,请确认;\n';
                temflag = false;
            }
            if (contactPhoneflag) {
                errormessage += ' 联系人手机不能为空,请确认;\n';
                temflag = false;
            }
            if (contactPostflag) {
                errormessage += ' 联系人邮政编码不能为空,请确认;\n';
                temflag = false;
            } else {
                Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
                Matcher mc = pt.matcher(strList[line_Contact_PostcodeD]);
                if(!mc.matches()) {
                    errormessage += ' 联系人邮政编码不是6位数字,[ '+strList[line_Contact_PostcodeD]+' ]请确认;\n';
                    temflag = false;
                }
            }
 
            if (temflag) {
                return true;
            } else {
                errormessageList.add(errormessage);
                errormessageMap.put(tem, errormessageList);
                return temflag;
            }
 
        } else {
            return false;
        }
 
    }
 
    class AccountContactInfo {
        public Integer lineNo { get; set; }
        public Account accountpage {get; set;}
 
        public Contact contactpage {get; set;}
 
        public AccountContactInfo(Integer line) {
 
        }
        // 客户数据正常但与客户同一行的联系人数据异常
        public AccountContactInfo(Integer line, Account account) {
            lineNo = line;
            accountpage = account;
        }
        // 客户数据与客户同一行的联系人数据都正常
        public AccountContactInfo(Integer line, Account account, Contact contact) {
            lineNo = line;
            accountpage = account;
            contactpage = contact;
        }
    }
    /**
     * 获取一个对象某个选项列表的全部值
     * @Author   XHL
     * @DateTime 2019-09-18
     * @param    fieldResult Schema.DescribeFieldResult fieldResult = Account.Use__c.getDescribe();
     *                       例:获取客户Use字段选项列表的值
     * @return               [description]
     */
    public  Map<String,String> getPickListValuesMap(Schema.DescribeFieldResult fieldResult){
        Map<String,String> pickListValuesMap= new Map<String,String>();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple)
        {
            pickListValuesMap.put(pickListVal.getValue(),pickListVal.getLabel());
        }
        return pickListValuesMap;
    }
 
    // 验证各个分野的sub Use是否符合要求
    private  Map<String, String> SegmentSubUseMap = new Map<String, String> {
        // IE
        'IE:LED' => 'LED',
        'IE:FPD' => 'FPD',
        'IE:半导体' => '半导体',
        'IE:电子部品' => '电子部品',
        'IE:太阳能' => '太阳能',
        'IE:电子类_其他' => '电子类_其他',
        'IE:金属' => '金属',
        'IE:汽车' => '汽车',
        'IE:石油地质' => '石油地质',
        'IE:五金模具' => '五金模具',
        'IE:重工设备' => '重工设备',
        'IE:材料类_其他' => '材料类_其他',
        // ANI
        'ANI:其他' => '其他',
        'ANI:废旧金属' => '废旧金属',
        'ANI:炼钢厂' => '炼钢厂',
        'ANI:PMI-石化行业' => 'PMI-石化行业',
        'ANI:PMI-管道制造' => 'PMI-管道制造',
        'ANI:PMI-金属制造' => 'PMI-金属制造',
        'ANI:PMI-电力' => 'PMI-电力',
        'ANI:RoHS' => 'RoHS',
        'ANI:ELV' => 'ELV',
        'ANI:玩具&皮革' => '玩具&皮革',
        'ANI:贵金属-制造' => '贵金属-制造',
        'ANI:贵金属-回收' => '贵金属-回收',
        'ANI:勘探-政府' => '勘探-政府',
        'ANI:勘探-矿业公司' => '勘探-矿业公司',
        'ANI:Mining-冶炼' => 'Mining-冶炼',
        'ANI:Mining-开采' => 'Mining-开采',
        'ANI:EPA' => 'EPA',
        'ANI:土壤修复' => '土壤修复',
        'ANI:土壤研究' => '土壤研究',
        'ANI:考古&文物' => '考古&文物',
        'ANI:录井' => '录井',
        'ANI:制药' => '制药',
        'ANI:三元催化剂' => '三元催化剂',
        'ANI:Thermal Power' => 'Thermal Power',
        'ANI:Nuclear Power' => 'Nuclear Power',
        'ANI:Wind Power' => 'Wind Power',
        'ANI:Power(other)' => 'Power(other)',
        // NDT
        'NDT:汽车' => '汽车',
        'NDT:Civil Aviation' => 'Civil Aviation',
        'NDT:Security/Defense' => 'Security/Defense',
        'NDT:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
        'NDT:General Manufacturing' => 'General Manufacturing',
        'NDT:Inspection/Service/Rental' => 'Inspection/Service/Rental',
        'NDT:其他' => '其他',
        'NDT:Thermal Power' => 'Thermal Power',
        'NDT:Nuclear Power' => 'Nuclear Power',
        'NDT:Wind Power' => 'Wind Power',
        'NDT:Power(other)' => 'Power(other)',
        // RVI
        'RVI:汽车' => '汽车',
        'RVI:Civil Aviation' => 'Civil Aviation',
        'RVI:Security/Defense' => 'Security/Defense',
        'RVI:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
        'RVI:General Manufacturing' => 'General Manufacturing',
        'RVI:Inspection/Service/Rental' => 'Inspection/Service/Rental',
        'RVI:其他' => '其他',
        'RVI:Thermal Power' => 'Thermal Power',
        'RVI:Nuclear Power' => 'Nuclear Power',
        'RVI:Wind Power' => 'Wind Power',
        'RVI:Power(other)' => 'Power(other)'
    };
 
}