liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
public with sharing class SetPersonalTargetController {
    // 当前期
    public String currentPeriod { get; private set; }
    public String currentPeriodOld;//20210225 ljh WLIG-BV8CHF  add 财年
    // 上年度按钮制御
    public Boolean previousRendered { get; private set; }
    // 下年度按钮制御
    public Boolean nextRendered { get; private set; }
    // 数据集
    public List<DataBean> dataBeans { get; set; }
    // 金额分类
    public List<String> opportunity_category { get; private set; }
    // 是否是过去年度
    public Boolean isPast { get; private set; }
    // 年度変化時セーブかどうか
    public Boolean saveFlg { get; set; }
    // 本部の選択値
    public String salesDpt { get; set; }
    // 職位のチェックボックス
    public List<Position> plist { get; set; }
    // 登陆用户
    public User loginUser { get; set; }
    // checkAll値保持用
    public Boolean checkAll { get; set; }
    // 製品担当の選択値
    public String productUser { get; set; }
    
    // 医院担当 プルダウン
    public static List<SelectOption> productUserOptions { get; private set; }
    static {
        productUserOptions = new List<SelectOption>();
        //wangweipeng      SWAG-C6V8W5        2021/09/16     start
        productUserOptions.add(new SelectOption('', 'All'));
        //wangweipeng      SWAG-C6V8W5        2021/09/16     end
        productUserOptions.add(new SelectOption('医院担当', '医院担当'));
        productUserOptions.add(new SelectOption('医院担当以外', '医院担当以外'));
    }
 
    public SetPersonalTargetController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
    }
 
    // ユーザ数
    public Integer getUserSize() {
        return users.size();
    }
    // 職位数
    public Integer getPSize() {
        return plist.size();
    }
    // 本部プルダウン
    public static List<SelectOption> salesDptOpts { get; private set; }
    public static List<SelectOption>  options;//<DB202303443108 20230410 you start
    
        
    static {
        salesDptOpts = new List<SelectOption>();
        salesDptOpts.add(new SelectOption('', '--无--'));
        salesDptOpts.add(new SelectOption('1.华北', '1.华北'));
        salesDptOpts.add(new SelectOption('2.东北', '2.东北'));
        salesDptOpts.add(new SelectOption('3.西北', '3.西北'));
        salesDptOpts.add(new SelectOption('4.西南', '4.西南'));
        salesDptOpts.add(new SelectOption('5.华东', '5.华东'));
        salesDptOpts.add(new SelectOption('6.华南', '6.华南'));
        
        ////<DB202303443108 20230410 you start  今年还是只显示6大本部,暂时注释
        //options= FixtureUtil.getPlickList('User', 'Dept__c');
        //for (SelectOption op : options) {
        //    if (String.isNotBlank(op.getValue())) {
        //        //if(op.getValue()=='能量事业本部'){
        //        //    salesDptOpts.add(new SelectOption('能量事业本部','7.能量'));
        //        //}else{
        //            salesDptOpts.add(new SelectOption(op.getValue(),op.getValue()));
        //        //}
                
        //    }
        //}
        ////<DB202303443108 20230410 you end
 
    }
 
    // 职种
    public static List<SelectOption> userJobCategorys { get; private set; }
    static {
        // DB202303443108 20230407 you start 职种-->SFDC-职种
        userJobCategorys = new List<SelectOption>();
        userJobCategorys.add(new SelectOption('', '--无--'));
        userJobCategorys.add(new SelectOption('销售推广', '推广'));
        userJobCategorys.add(new SelectOption('销售市场', '营业市场'));
        //userJobCategorys.add(new SelectOption('销售服务', '服务'));
        userJobCategorys.add(new SelectOption('营业助理', '营业助理'));
        userJobCategorys.add(new SelectOption('行政助理', '行政助理'));
        //userJobCategorys.add(new SelectOption('其他', '其他'));
    }
 
    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;
    //  当前月份
    private Integer iMonth;
    //  当前日期
    private Integer iDay;
    //  4月可编辑期限
    private Integer iBuffer;
 
    private RecordType rt;           // 目标的数据类型
    private User[] users;            // 担当人员
    private Map<String, List<Double>> proportion;     // 比重
    private String adminDpt = null;
 
    //2020/06/05 SWAG-BQ7CM9 中间表既存数据 by ljh
    private Map<String, Amount_Major_Product__c> Amount_Major_ProductMap;
 
    
 
    // 既存目标数据
    private Map<String, Opportunity> oppMap;
    private Map<Id, OpportunityLineItem> oliMap;//20200605 add
    // 金额分类
    //private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT','OTH'};
    // 个人目标(SetPersonalTarget):隐藏OTH。
    // CHAN-BBLCYP 20190509 LHJ Start
    //private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT'};
    //private static String[] amountCategory = new String[] {'GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG'};
    // CHAN-BBLCYP 20190509 LHJ End
    // DB202303443108 20230407 you start
    private static String[] amountCategory = new String[] {'GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG1','ENG2'};
    // DB202303443108 20230407 you end
    //CHAN-BDQBLX  20210125 you start
    private List<Amount_Major_Product__c> upsertAMPList ;//= new List<Amount_Major_Product__c>();
    private Map<String, Amount_Major_Product__c> Amount_Major_ProductMap1;
    public Boolean isFlg { get; set; }//判断走哪个查询方法
    public Boolean isFlg1 { get; set; }
    //public Blob csvFileBody {get; set;}
    public string csvAsString {get; set;}
    public String[] csvFileLines {get; set;}
    // DB202303443108 20230407 you start
    //wangweipeng 20210616  新加负责产品分类(兼) 导出导入表头
    //private static String[] titlepage = new String[] {'本部', '省', '角色', '担当', '职位', '负责产品分类(主)', '负责产品分类(兼)','目标类型', 'GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG1', 'ENG2'};
    private static String[] titlepage = new String[] {'本部', '省', '担当', '职位', '负责产品分类(主)', '负责产品分类(兼)','目标类型', 'GI', 'ET', 'BF', 'GS', 'URO', 'GYN', 'ENT', 'ENG1', 'ENG2','备注'};//20230510 ljh
    
    // DB202303443108 20230407 you end
    public Integer detailCountLimit{get;private set;}
    //CHAN-BDQBLX  20210125 you end
 
    // 画面初始化
    public Pagereference init() {
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        //CHAN-BDQBLX  20210125 you start
        Amount_Major_ProductMap1 = new Map<String, Amount_Major_Product__c>();
        upsertAMPList = new List<Amount_Major_Product__c>();
        detailCountLimit = 10000;
        //CHAN-BDQBLX  20210125 you end
        if (month < 4) {
            year -= 1;
        }
        // 初始化
        currentYear = year;
        iYear = year;
        iMonth = month;
        iDay = dateNow.day();
        iBuffer = Integer.valueOf(System.Label.SetPersonalTarget_buffer_day);
        isPast = false;
//        if (month == 3) isPast = true;
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        previousRendered = true;
        nextRendered = true;
        saveFlg = false;
        // 金额分类
        opportunity_category = amountCategory;
 
        // 每月比重
        if (proportion == null) {
            proportion = new Map<String, List<Double>>();
            String strObjectiveProportionGI = System.Label.ObjectiveProportionGI;
            List<String> objectiveProportionGI = strObjectiveProportionGI.split(',');
            List<Double> doubleGI = new List<Double>();
            for (String strGI : objectiveProportionGI) {
                doubleGI.add(Double.valueOf(strGI));
            }
            proportion.put('GI', doubleGI);
 
            String strObjectiveProportionET = System.Label.ObjectiveProportionET;
            List<String> objectiveProportionET = strObjectiveProportionET.split(',');
            List<Double> doubleET = new List<Double>();
            for (String strET : objectiveProportionET) {
                doubleET.add(Double.valueOf(strET));
            }
            proportion.put('ET', doubleET);
 
            String strObjectiveProportionBF = System.Label.ObjectiveProportionBF;
            List<String> objectiveProportionBF = strObjectiveProportionBF.split(',');
            List<Double> doubleBF = new List<Double>();
            for (String strBF : objectiveProportionBF) {
                doubleBF.add(Double.valueOf(strBF));
            }
            proportion.put('BF', doubleBF);
 
            String strObjectiveProportionGS = System.Label.ObjectiveProportionGS;
            List<String> objectiveProportionGS = strObjectiveProportionGS.split(',');
            List<Double> doubleGS = new List<Double>();
            for (String strGS : objectiveProportionGS) {
                doubleGS.add(Double.valueOf(strGS));
            }
            proportion.put('GS', doubleGS);
 
            String strObjectiveProportionURO = System.Label.ObjectiveProportionURO;
            List<String> objectiveProportionURO = strObjectiveProportionURO.split(',');
            List<Double> doubleURO = new List<Double>();
            for (String strURO : objectiveProportionURO) {
                doubleURO.add(Double.valueOf(strURO));
            }
            proportion.put('URO', doubleURO);
 
            String strObjectiveProportionGYN = System.Label.ObjectiveProportionGYN;
            List<String> objectiveProportionGYN = strObjectiveProportionGYN.split(',');
            List<Double> doubleGYN = new List<Double>();
            for (String strGYN : objectiveProportionGYN) {
                doubleGYN.add(Double.valueOf(strGYN));
            }
            proportion.put('GYN', doubleGYN);
 
            String strObjectiveProportionENT = System.Label.ObjectiveProportionENT;
            List<String> objectiveProportionENT = strObjectiveProportionENT.split(',');
            List<Double> doubleENT = new List<Double>();
            for (String strENT : objectiveProportionENT) {
                doubleENT.add(Double.valueOf(strENT));
            }
            proportion.put('ENT', doubleENT);
 
            String strObjectiveProportionOTH = System.Label.ObjectiveProportionOTH;
            List<String> objectiveProportionOTH = strObjectiveProportionOTH.split(',');
            List<Double> doubleOTH = new List<Double>();
            for (String strOTH : objectiveProportionOTH) {
                doubleOTH.add(Double.valueOf(strOTH));
            }
            proportion.put('OTH', doubleOTH);
            // DB202303443108 20230407 you start ENG拆分为ENG1和ENG2
            String strObjectiveProportionENG1 = System.Label.ObjectiveProportionENG;
            List<String> objectiveProportionENG1 = strObjectiveProportionENG1.split(',');
            List<Double> doubleENG1 = new List<Double>();
            for (String strENG1 : objectiveProportionENG1) {
                doubleENG1.add(Double.valueOf(strENG1));
            }
            proportion.put('ENG1', doubleENG1);
 
            String strObjectiveProportionENG2 = System.Label.ObjectiveProportionENG;
            List<String> objectiveProportionENG2 = strObjectiveProportionENG2.split(',');
            List<Double> doubleENG2 = new List<Double>();
            for (String strENG2 : objectiveProportionENG2) {
                doubleENG2.add(Double.valueOf(strENG2));
            }
            proportion.put('ENG2', doubleENG2);
            // DB202303443108 20230407 you end
        }
        // 職位
        if (plist == null) {
            plist = new List<Position>();
            plist.add(new Position('专员', true));  //20220517 lt SWAG-CD28H3
            plist.add(new Position('高级', true));
            plist.add(new Position('主管', true));
            //20220402 lt SWAG-CD28H3 【委托】【期初修改4月6日开始修改】目标录入相关判断修改 start
            // plist.add(new Position('副经理', true));
            // plist.add(new Position('经理', false));
            // plist.add(new Position('副部长', false));
            // plist.add(new Position('部长', false));
            plist.add(new Position('经理级', true));
            plist.add(new Position('总监级', true));
            plist.add(new Position('总裁级', true));
            //20220402 lt SWAG-CD28H3 【委托】【期初修改4月6日开始修改】目标录入相关判断修改 start
        }
 
        // 当前用户信息
        if (loginUser == null) {
            loginUser = [Select Id, Salesdepartment__c,Dept__c, Province__c, ProfileId, SFDCPosition_C__c From User where Id = :Userinfo.getUserId()];
            loginUser.SFDCPosition_C__c = null;
        }
        //adminDpt = loginUser.Dept__c;
        adminDpt = loginUser.Salesdepartment__c;
        if (String.isBlank(adminDpt)
                && (loginUser.ProfileId == System.Label.ProfileId_SystemAdmin
                    || loginUser.ProfileId == System.Label.ProfileId_103
                   )
           ) {
            adminDpt = '5.华东';//'医疗华东营业本部';
        }
 
        //repFlg =adminDpt;
        // province = loginUser.Province__c;
        users = this.getUserList(false, false, true);
        //CHAN-BDQBLX  20210125 you start
        isFlg1=true;
        //CHAN-BDQBLX  20210125 you end
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 数据赋值
        setBean(iYear);
        // 保存成功のメッセージ
        String s = System.currentPageReference().getParameters().get('s');
        if (s == '1') {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '保存成功。'));
        }
        return null;
    }
 
    // 点击上年度
    public void previous() {
        if (saveFlg) {
            this.saveLogic();
        }
 
        iYear -= 1;
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        // 是否是过去数据
        isPast = false;
        if (iYear < currentYear && !(currentYear - iYear == 1 && iMonth == 4 && iDay <= iBuffer)) {
            isPast = true;
        }// else if (iYear == currentYear) {
//            if (Date.today().month() == 3) {
//                isPast = true;
//            }
//        }
        previousRendered = true;
        nextRendered = true;
        // 数据赋值
        setBean(iYear);
    }
 
    // 点击下年度
    public void next() {
        if (saveFlg) {
            this.saveLogic();
        }
 
        iYear += 1;
        //20210225 ljh WLIG-BV8CHF update  财年 start
        //currentPeriod = String.valueOf(iYear - 1867 + 'P');
        currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
        Integer tempiYear = iYear+1;
        currentPeriod = String.valueOf('FY'+tempiYear);
        //20210225 ljh WLIG-BV8CHF update  财年 end
        // 是否是过去数据
        isPast = false;
        if (iYear < currentYear && !(currentYear - iYear == 1 && iMonth == 4 && iDay <= iBuffer)) {
            isPast = true;
        }// else if (iYear == currentYear) {
//            if (Date.today().month() == 3) {
//                isPast = true;
//            }
//        }
        previousRendered = true;
        nextRendered = true;
        // 只显示到现在时间的下一年数据
        if (iYear > currentYear) {
            nextRendered = false;
        }
        // 数据赋值
        setBean(iYear);
    }
 
    // 本部プルダウン変更時の処理、システム管理者専用
    public void searchByDpt() {
        if (saveFlg) {
            this.saveLogic();
        }
        //CHAN-BDQBLX  20210125 you start
        isFlg = true;
        isFlg1=false;
        //CHAN-BDQBLX  20210125 you end
        users = this.getUserList(true, false, false);
        // 数据赋值
        setBean(iYear);
    }
 
    // 省プルダウン変更時の処理
    public void searchByProvince() {
        if (saveFlg) {
            this.saveLogic();
        }
        //CHAN-BDQBLX  20210125 you start
        isFlg = false;
        isFlg1= false;
        //CHAN-BDQBLX  20210125 you end
        users = this.getUserList(false, true, false);
        // 数据赋值
        setBean(iYear);
    }
 
    // 職位変更時の処理
    public void searchByFilter() {
        if (saveFlg) {
            this.saveLogic();
        }
        users = this.getUserList(false, false, false);
        //CHAN-BDQBLX  20210125 you start
        isFlg1=false;
        //CHAN-BDQBLX  20210125 you end
        // 数据赋值
        setBean(iYear);
    }
//CHAN-BDQBLX  20210125 you start 导出方法
    public Pagereference exportBycsv() {
        system.debug('isFlg==' + isFlg);
        boolflag(isFlg1,isFlg);//判断执行哪个查询得方法
 
        system.debug('进来了');
        return page.SetPersonalTargetcsv;
    }
    //导入方法
    public PageReference importCSVFile() {
 
         try {
            String csvData = ApexPages.currentPage().getParameters().get('csvData');
            // 将内容转换成为中文
            if(!Test.isRunningTest()){
                //csvAsString = bitToString(csvFileBody, 'gb2312');
                csvAsString = csvData;
                system.debug('==csvAsString=='+csvAsString);
            }            
            // 拆成每一行
            csvFileLines = csvAsString.split('\n');
            system.debug(csvFileLines.size());
            Boolean ValFlag = false;
            String exportByVal = '';
            ApexPages.Message successMsg = new ApexPages.Message(ApexPages.severity.INFO, '');
            // 需要根据情况来解析,查看表头是否一致
            if (csvFileLines.size() > 0) {
                string[] titlecsv = csvFileLines[0].trim().split(',');//
                system.debug(titlecsv + '==titlepage==' + titlepage);
                for (integer j = 0; j < titlecsv.size(); j++) {
                    // 20230515 ljh lightning模式导出有空格 start
                    // if (!titlepage.contains(titlecsv[j])) {
                    if (!titlepage.contains(titlecsv[j].trim())) {
                    // 20230515 ljh lightning模式导出有空格 end
                        system.debug('表头不一致得列===' + titlecsv[j]);
                        ValFlag = true;
                        exportByVal = '表头不一致,请严格按照导出模板填写';
                        break;
                    }
                }
 
            }
            if (ValFlag) {
                successMsg = new ApexPages.Message(ApexPages.severity.INFO, exportByVal);
                ApexPages.addMessage(successMsg);
 
            } else {
                List<String> UserInfoList = new List<String>();
                Map<String, List<String>> szMap = new Map<String, List<String>>();
                Set<String> sfs = new Set<String>();//省份
                Set<String> bus = new Set<String>();//本部
                Set<String> zws = new Set<String>();//职位
                Set<String> yydds = new Set<String>();//医院担当
                Set<String> zzs = new Set<String>();//职种
 
                for (Integer i = 1; i < csvFileLines.size(); i++) {
                    System.debug('zheli472:'+csvFileLines[i]);
                    // 20230515 ljh 千分位 start
                    String p = '\"([^\"]*)\"' ;
                    Pattern PP = Pattern.compile(p);
                    Matcher matcher=PP.matcher(csvFileLines[i]);
                    while(matcher.find())
                    {
                        String old = matcher.group(0);
                        String repNew = matcher.group(0).replaceAll(',','').trim();
                        csvFileLines[i] = csvFileLines[i].replace(old,repNew);   
                    }
                    // 20230515 ljh 千分位 end
                    string[] csvRecordData = csvFileLines[i].split(',');
                    if (csvRecordData.size() > 0) {
                        String bu = csvRecordData[0].replace(' ', '');//本部
                        String sf = csvRecordData[1].replace(' ', '');//省
                        //隐藏角色
                        //String dandang = csvRecordData[3].replace(' ', '');//担当
                        //String zw = csvRecordData[4].replace(' ', '');//通用职级
                        String dandang = csvRecordData[2].replace(' ', '');//担当
                        String zw = csvRecordData[3].replace(' ', '');//通用职级
                        String key_flg = (bu + sf + dandang + zw).replaceAll('"', '');
                        UserInfoList.add(key_flg);
                        szMap.put(key_flg, csvRecordData);
                        sfs.add(sf);//把省份放进去
                        bus.add(bu);//本部
                        zws.add(zw);//职位
 
                    }
                }
                if (null != sfs && sfs.size() > 0) {
                    this.getAmount_Major_Product(sfs);//根据省份年份,获取当前系统中已经存在得数据 放到map中
                    
                }
                List<User> userList  = new List<User>();
                System.debug('==UserInfoList=='+UserInfoList);
                if (null != UserInfoList && UserInfoList.size() > 0) {
                    userList = this.getUserList(UserInfoList);//返回用户得一些信息
                }
                Map<String, User> userMap = new Map<String, User>();
                for (User userl : userList) {
                    yydds.add(userl.Sales_Speciality__c);//医院担当
                    zzs.add(userl.SFDCPosition_C__c);//职种
                    userMap.put(userl.UserInfos__c, userl);
 
                }
                /**
                角色隐藏暂时注释
                Integer Target_Number = 7;//目标类型
                Integer GI_Number = 8;
                Integer ET_Number = 9;
                Integer BF_Number = 10;
                Integer GS_Number = 11;
                Integer URO_Number = 12;
                Integer GYN_Number = 13;
                Integer ENT_Number = 14;
                // DB202303443108 20230407 you start
                Integer ENG1_Number = 15;
                Integer ENG2_Number = 16;
                // DB202303443108 20230407 you end
                **/
                Integer Target_Number = 6;//目标类型
                Integer GI_Number = 7;
                Integer ET_Number = 8;
                Integer BF_Number = 9;
                Integer GS_Number = 10;
                Integer URO_Number = 11;
                Integer GYN_Number = 12;
                Integer ENT_Number = 13;
                // DB202303443108 20230407 you start
                Integer ENG1_Number = 14;
                Integer ENG2_Number = 15;
                // DB202303443108 20230407 you end
                Integer Remarks_Number = 16;//20230510 ljh
                upsertAMPList = new List<Amount_Major_Product__c>();//初始化,解决重复导入数据 id重复得问题
                for (String key : szMap.keySet()) {
                    //取用户的Id
                    String userid = '';
                    User userinfors=new User();
                    if (userMap.containskey(key)) {
                        userid = userMap.get(key).Id;
                        userinfors = userMap.get(key);
                    } else {
                        System.debug('==key==='+key);
                        //用户不存在要提醒
                        continue;
                    }
                    
                    
                    List<String> csvRecordData = szMap.get(key);
                    Amount_Major_Product__c upsertAMP = new Amount_Major_Product__c();
 
                    String Target_Type = String.isNotBlank(csvRecordData[Target_Number]) && String.isNotBlank(csvRecordData[Target_Number].replaceAll('"', '')) ? String.valueof(csvRecordData[Target_Number].replaceAll('"', '')) : '';
                    // 20230510 ljh start
                    String remarks  = String.isNotBlank(csvRecordData[Remarks_Number]) && String.isNotBlank(csvRecordData[Remarks_Number].replaceAll('"', '')) ? String.valueof(csvRecordData[Remarks_Number].replaceAll('"', '')) : ''; 
                    // 20230510 ljh start
                    //获取导入数量
                    // 20230515 ljh 千分位 start
                    // Decimal GI_Amount = String.isNotBlank(csvRecordData[GI_Number]) && String.isNotBlank(csvRecordData[GI_Number].replaceAll('"', '')) ? Decimal.valueof(csvRecordData[GI_Number].replaceAll('"', '')) : 0.00;
                    Decimal GI_Amount = String.isNotBlank(csvRecordData[GI_Number]) && String.isNotBlank(csvRecordData[GI_Number].replaceAll('"', '')) ? Decimal.valueof(csvRecordData[GI_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end 
                    DataSplicing(GI_Amount,userid + '_GI',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    
                    // 20230515 ljh 千分位 start
                    // Decimal ET_Amount = String.isNotBlank(csvRecordData[ET_Number]) && String.isNotBlank(csvRecordData[ET_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[ET_Number].replaceAll('"', '')) : 0.00;
                    Decimal ET_Amount = String.isNotBlank(csvRecordData[ET_Number]) && String.isNotBlank(csvRecordData[ET_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[ET_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(ET_Amount,userid + '_ET',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    
                    // 20230515 ljh 千分位 start
                    // Decimal BF_Amount = String.isNotBlank(csvRecordData[BF_Number]) && String.isNotBlank(csvRecordData[BF_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[BF_Number].replaceAll('"', '')) : 0.00;
                    Decimal BF_Amount = String.isNotBlank(csvRecordData[BF_Number]) && String.isNotBlank(csvRecordData[BF_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[BF_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(BF_Amount,userid + '_BF',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    
                    // 20230515 ljh 千分位 start
                    // Decimal GS_Amount = String.isNotBlank(csvRecordData[GS_Number]) && String.isNotBlank(csvRecordData[GS_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[GS_Number].replaceAll('"', '')) : 0.00;
                    Decimal GS_Amount = String.isNotBlank(csvRecordData[GS_Number]) && String.isNotBlank(csvRecordData[GS_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[GS_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(GS_Amount,userid + '_GS',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    // 20230515 ljh 千分位 start
                    // Decimal URO_Amount = String.isNotBlank(csvRecordData[URO_Number]) && String.isNotBlank(csvRecordData[URO_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[URO_Number].replaceAll('"', '')) : 0.00;
                    Decimal URO_Amount = String.isNotBlank(csvRecordData[URO_Number]) && String.isNotBlank(csvRecordData[URO_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[URO_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(URO_Amount,userid + '_URO',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    // 20230515 ljh 千分位 start
                    // Decimal GYN_Amount = String.isNotBlank(csvRecordData[GYN_Number]) && String.isNotBlank(csvRecordData[GYN_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[GYN_Number].replaceAll('"', '')) : 0.00;
                    Decimal GYN_Amount = String.isNotBlank(csvRecordData[GYN_Number]) && String.isNotBlank(csvRecordData[GYN_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[GYN_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(GYN_Amount,userid + '_GYN',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    // 20230515 ljh 千分位 start
                    // Decimal ENT_Amount = String.isNotBlank(csvRecordData[ENT_Number]) && String.isNotBlank(csvRecordData[ENT_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[ENT_Number].replaceAll('"', '')) : 0.00;
                    Decimal ENT_Amount = String.isNotBlank(csvRecordData[ENT_Number]) && String.isNotBlank(csvRecordData[ENT_Number].replaceAll('"', '')) ? Decimal.valueOf(csvRecordData[ENT_Number].replaceAll('"', '').trim()) : 0.00;
                    // 20230515 ljh 千分位 end
                    DataSplicing(ENT_Amount,userid + '_ENT',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
                    system.debug('ENG1_Number--->'+csvRecordData[ENG1_Number]);
                    //因为最后一列数据有空格,所以加.trim()
                    // DB202303443108 20230407 you start
                    Decimal ENG1_Amount = String.isNotBlank(csvRecordData[ENG1_Number]) && String.isNotBlank(csvRecordData[ENG1_Number].replaceAll('"', ''))? Decimal.valueOf(csvRecordData[ENG1_Number].replaceAll('"', '').trim()) : 0.00;
                    // Decimal.valueOf(String str)
                    DataSplicing(ENG1_Amount,userid + '_ENG1',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
 
                    Decimal ENG2_Amount = String.isNotBlank(csvRecordData[ENG2_Number]) && String.isNotBlank(csvRecordData[ENG2_Number].replaceAll('"', ''))? Decimal.valueOf(csvRecordData[ENG2_Number].replaceAll('"', '').trim()) : 0.00;
                    DataSplicing(ENG2_Amount,userid + '_ENG2',Amount_Major_ProductMap1,userinfors,Target_Type,remarks);
 
                    // DB202303443108 20230407 you end
                    
 
 
                    //拼接Key
                }
 
                if(null!=upsertAMPList && upsertAMPList.size()>0){
                    upsert upsertAMPList;
                }
                
                system.debug('==UserInfoList==' + UserInfoList + '==' + userList);
                boolflag(isFlg1,isFlg);
                    
                successMsg = new ApexPages.Message(ApexPages.severity.INFO, '导入成功');
                ApexPages.addMessage(successMsg);
            }
 
 
 
 
         } catch (Exception e) {
             ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e.getMessage());
             ApexPages.addMessage(errorMessage);
         }
        return null;
    }
    // 最终得数据处理,
    // 20230510 ljh start
    // private void DataSplicing(Decimal amount, String key, Map<String, Amount_Major_Product__c> ampMap,User userinfors,String Target_Type) {//去进行最终数据得插入,更新或删除操作
    private void DataSplicing(Decimal amount, String key, Map<String, Amount_Major_Product__c> ampMap,User userinfors,String Target_Type,String remarks) {//去进行最终数据得插入,更新或删除操作
    // 20230510 ljh end 
        Amount_Major_Product__c upsertAMP = new Amount_Major_Product__c();
        Amount_Major_Product__c Amount_Major_Product = Amount_Major_ProductMap.get(key);   
        //system.debug('==amount=='+amount+'==key=='+key+'==ampMap=='+ampMap+'==userinfors=='+userinfors+'==Target_Type=='+Target_Type+'\n');
        if (ampMap.containskey(key)) {
            upsertAMP = ampMap.get(key);
            if (amount > 0) {
                // 20230510 ljh update start
                // if(amount!=upsertAMP.Amount__c){
                if(amount!=upsertAMP.Amount__c || Target_Type!=upsertAMP.TargetType__c ||remarks!=upsertAMP.remarks__c){
                // 20230510 ljh update end
                    upsertAMP.Amount__c = amount;
                    upsertAMP.Use_Start_Date__c = userinfors.Use_Start_Date__c;
                    upsertAMP.Is_Processing__c = true;
                    upsertAMP.TargetType__c = Target_Type;
                    upsertAMP.remarks__c = remarks;// 20230510 ljh
                    upsertAMPList.add(upsertAMP);
                    //更新
                }
                
            } else {
                //不用删除了,允许 数据是空的存在
                upsertAMP.Amount__c = null;
                upsertAMP.Is_Processing__c = true;
                upsertAMP.TargetType__c = Target_Type;// 20230510 ljh
                upsertAMP.remarks__c = remarks;// 20230510 ljh
                upsertAMPList.add(upsertAMP);
            }
        } else {
            if (amount > 0) {
                upsertAMP.Amount__c = amount;
                upsertAMP.key__c = key;
                upsertAMP.user_Alias__c = userinfors.Alias;
                upsertAMP.SAP_Province__c = userinfors.Province__c;
                upsertAMP.Use_Start_Date__c = userinfors.Use_Start_Date__c;
                upsertAMP.iYear__c = iYear;
                upsertAMP.Is_Processing__c = true;
                upsertAMP.TargetType__c = Target_Type; 
                upsertAMP.remarks__c = remarks;// 20230510 ljh
                upsertAMPList.add(upsertAMP);
            } else {
                //允许 数据是空的存在
                upsertAMP.Amount__c = null;
                upsertAMP.key__c = key;
                upsertAMP.user_Alias__c = userinfors.Alias;
                upsertAMP.SAP_Province__c = userinfors.Province__c;
                upsertAMP.Use_Start_Date__c = userinfors.Use_Start_Date__c;
                upsertAMP.iYear__c = iYear;
                upsertAMP.Is_Processing__c = true;
                upsertAMP.TargetType__c = Target_Type;
                upsertAMP.remarks__c = remarks;// 20230510 ljh
                upsertAMPList.add(upsertAMP);
            }
        }
 
    }
 
 
 
    private void getAmount_Major_Product(Set<String> sfs) {//根据省份年份,获取当前系统中已经存在得数据
        Amount_Major_ProductMap1 = new Map<String, Amount_Major_Product__c>();
 
        list<Amount_Major_Product__c> Existed_Amount_Major_Products = [select key__c, Amount__c, user_Alias__c,
                                      Is_Processing__c, iYear__c,TargetType__c,remarks__c from Amount_Major_Product__c where iYear__c = : iYear and SAP_Province__c in :sfs];
        //system.debug('Existed_Amount_Major_Products' + Existed_Amount_Major_Products);
 
        for ( Amount_Major_Product__c Amount_Major_Product : Existed_Amount_Major_Products ) {
            if (String.isBlank(Amount_Major_Product.key__c)) {
                continue;
            }
 
            Amount_Major_ProductMap1.put(Amount_Major_Product.key__c, Amount_Major_Product);
 
        }
    }
    private List<User> getUserList(List<String> UserInfoList) {//根据上传文件中得本部,省份,担当,职位 得到了user 信息
        String soql = 'select Id, UserInfos__c, Salesdepartment__c,Dept__c, Province__c, Alias, Product_specialist_incharge_product__c,Responsible_for_Products_Concurrently__c, Use_Start_Date__c,'
                      + ' ProfileId, Profile.Name, UserRoleId, UserRole.Name, Sales_Speciality__c, HR_Post__c,SFDCPosition_C__c'
                      + ' from User where IsActive = true and Test_staff__c = false and UserType = \'Standard\' '
                      + ' and Salesdepartment__c <> \'7.能量\' '
                      + ' and UserInfos__c IN :UserInfoList order by Salesdepartment__c, Province__c';
        System.debug('==soql==' + soql);
        return Database.query(soql);
    }
    private void boolflag(Boolean isFlg1, Boolean isFlg) {//判断走哪个查询方法,进行导出数据
        if(isFlg1!=null && isFlg1){
            system.debug('初始化');
            users = this.getUserList(false, false, true);
        }else if (isFlg != null && isFlg) {
            system.debug('进1');
            users = this.getUserList(true, false, false);
        } else if ( isFlg != null && !isFlg) {
            system.debug('进2');
            users = this.getUserList(false, true, false);
        } else {
            system.debug('进3');
            users = this.getUserList(false, false, false);
        }
        // 数据赋值
        setBean(iYear);
    }
    /**
    以前是这样写,现在改成在js里面处理 中文乱码得问题
    csvAsString = bitToString(csvFileBody, 'gb2312');
    public static String bitToString(Blob input, String inCharset) {
        //转换成16进制
        String hex = EncodingUtil.convertToHex(input);
        //一个String类型两个字节 32位(bit),则一个String长度应该为两个16进制的长度,所以此处向右平移一个单位,即除以2
        //向右平移一个单位在正数情况下等同于除以2,负数情况下不等
        //eg 9  00001001  >>1 00000100   结果为49
        final Integer bytesCount = hex.length() >> 1;
        // //声明String数组,长度为16进制转换成字符串的长度1
        String[] bytes = new String[bytesCount];
        for (Integer i = 0; i < bytesCount; ++i) {
            //将相邻两位的16进制字符串放在一个String中
            bytes[i] =  hex.mid(i << 1, 2);
        }
        //解码成指定charset的字符串
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
 
    }
    **/
//CHAN-BDQBLX  20210125 you end
    // 点击保存按钮
    public Pagereference saveBtn() {
        this.saveLogic();
        PageReference ref = new Pagereference('/apex/SetPersonalTarget?s=1');
        ref.setRedirect(true);
        return ref;
    }
    /** 20220613 WLIG-CER9NQ you 页面中拿掉改成batch执行
    // 2020/06/05 SWAG-BQ7CM9 点击更新按钮 by ljh
    public Pagereference UpdateBtn() {
        system.debug('=====UpdateBtn-1');
        Boolean rs =  saveLogic();
        setBean(iYear);
        Id execBTId =  Database.executeBatch(new SetPersonalTargetBatch(), 20);
        system.debug('===execBTId===' + execBTId);
        if (rs && String.isNotBlank(execBTId)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '反映到目标成功'));
        }
        return null;
    }
    **/
    // 点击返回按钮
    public Pagereference backBtn() {
        // HOMEに戻る
        PageReference ref = new Pagereference('/home/home.jsp');
        ref.setRedirect(true);
        return ref;
    }
    // 2020/06/05 SWAG-BQ7CM9 从中间表获取既有数据,并以key__c为key存入map中 by ljh
    //String key = opp.OwnerId + '_' + opp.Opportunity_Category__c ;
    private boolean getAmount_Major_Productmap() {
        Amount_Major_ProductMap = new Map<String, Amount_Major_Product__c>();
        if (getUserSize() == 0) {
            return false;
        }
 
        list<Amount_Major_Product__c> Existed_Amount_Major_Products = [select key__c, Amount__c, user_Alias__c,
                                      Is_Processing__c, iYear__c,TargetType__c,remarks__c from Amount_Major_Product__c where iYear__c = : iYear ];
        //system.debug('iYear===' + iYear);
        if (Existed_Amount_Major_Products.size() <= 0 ) {
            return false;
        }
        for ( Amount_Major_Product__c Amount_Major_Product : Existed_Amount_Major_Products ) {
            if (String.isBlank(Amount_Major_Product.key__c)) {
                continue;
            }
            // 2020/06/05 SWAG-BQ7CM9  仅获取当前用户数据存入map中  start by ljh
            boolean flag = false;
            for (User user : users) {
                if (user.Alias.equals(Amount_Major_Product.user_Alias__c)) {
                    flag = true;
                    break;
                }
            }
            //system.debug('==flag=='+flag);
            if (flag) {
                Amount_Major_ProductMap.put(Amount_Major_Product.key__c, Amount_Major_Product);
            }
            // 2020/06/05 SWAG-BQ7CM9  仅获取当前用户数据存入map中  start by ljh
        }
        //ApexPages.addmessage(new ApexPages.message('aa'));
        //'Amount_Major_ProductMap' + Amount_Major_ProductMap.keySet()
        //system.debug(Amount_Major_ProductMap+'Existed_Amount_Major_Products==' + Amount_Major_ProductMap.keySet());
        return true;
    }
 
    // ユーザの検索
    private List<User> getUserList(Boolean searchByDpt, Boolean searchByProvince, Boolean defaultSearch) {
        system.debug('进来了');
        String soql = 'select Id, Salesdepartment__c,Dept__c, Province__c, Alias, Product_specialist_incharge_product__c,Responsible_for_Products_Concurrently__c, Use_Start_Date__c,'
                      + ' ProfileId, Profile.Name, UserRoleId, UserRole.Name, Sales_Speciality__c, HR_Post__c'
                      + ' from User where IsActive = true and Test_staff__c = false and UserType = \'Standard\' '
                      // CHAN-BBLCYP 20190509 LHJ Start
                      + ' and Salesdepartment__c <> \'7.能量\' ';
        // CHAN-BBLCYP 20190509 LHJ End
        
        //wangweipeng      SWAG-C6V8W5        2021/09/16     start
        /*if (String.isBlank(productUser) || productUser == '医院担当') {
            soql += ' and Sales_Speciality__c = \'医院担当\'';
        } else {
            soql += ' and Sales_Speciality__c <> \'医院担当\'';
        }*/
        if (productUser == '医院担当') {
            soql += ' and Sales_Speciality__c = \'医院担当\'';
        } else if(productUser == '医院担当以外') {
            soql += ' and Sales_Speciality__c <> \'医院担当\'';
        }
        //wangweipeng      SWAG-C6V8W5        2021/09/16     end
        
        // 职种
        if (defaultSearch || String.isBlank(loginUser.SFDCPosition_C__c)) {
            soql += ' and (SFDCPosition_C__c = \'销售推广\' or SFDCPosition_C__c = \'销售市场\' or SFDCPosition_C__c = \'营业助理\' or SFDCPosition_C__c = \'行政助理\')';// or SFDCPosition_C__c = \'销售服务\' or SFDCPosition_C__c = \'其他\'
        } else {
            soql += ' and SFDCPosition_C__c = \'' + loginUser.SFDCPosition_C__c + '\'';
        }
        // 本部にて検索の場合、省を無視
        if (searchByDpt) {
            loginUser.Province__c = null;
            // 省にて検索の場合、本部を無視
        } else if (searchByProvince) {
            salesDpt = null;
            // 職位にて検索の場合
        } else {}
        system.debug('==defaultSearch==' + defaultSearch + '==本部==' + searchByDpt + '==salesDpt=本部=' + salesDpt + '==省==' + searchByProvince + '==loginUser.Province__c==' + loginUser.Province__c + '==adminDpt==' + adminDpt);
        if (!String.isBlank(salesDpt)) {
            soql += ' and Salesdepartment__c = \'' + salesDpt + '\'';
        }
        if (!String.isBlank(loginUser.Province__c)) {
            soql += ' and Province__c = \'' + loginUser.Province__c + '\'';
        }
        if (String.isBlank(salesDpt) && String.isBlank(loginUser.Province__c)) {
            soql += ' and Salesdepartment__c = \'' + adminDpt + '\'';
        }
        if(String.isBlank(salesDpt) ){
            soql += ' and (Salesdepartment__c = \'1.华北\' or Salesdepartment__c = \'2.东北\' or Salesdepartment__c = \'3.西北\' or Salesdepartment__c = \'4.西南\' or Salesdepartment__c = \'5.华东\' or Salesdepartment__c = \'6.华南\')';
        }
        if (searchByProvince) {
            salesDpt = adminDpt;
        }
       
 
        // 職位条件
        List<String> positionNames = new List<String>();
        String s1 = '经理';
        String s2 = '总监';
        String s3 = '总裁';
        for (Position p : plist) {
            if (p.check) {
                //positionNames.add(p.positionName);
                //20220406 lt SWAG-CD28H3 【委托】【期初修改4月6日开始修改】目标录入相关判断修改 start
                //20220517 lt SWAG-CD28H3  注释
                if(p.positionName == '高级'){
                    positionNames.add('高级专员');
                }else{
                    positionNames.add(p.positionName);
                }
                // if(p.positionName == '经理级'){
                //     positionNames.add('副经理');
                //     positionNames.add('经理');
                // }
                // if(p.positionName == '总监级'){
                //     positionNames.add('副部长');
                //     positionNames.add('部长');
                //     positionNames.add('总监');
                // }
                //20220406 lt SWAG-CD28H3 【委托】【期初修改4月6日开始修改】目标录入相关判断修改end
            }
        }
        if (positionNames.size() > 0) {
            
            soql += ' and (';
            for (Integer i = 0; i < positionNames.size(); i++) {
                if (i == positionNames.size() - 1) {
                    //20220517 lt SWAG-CD28H3 Start
                    if(positionNames[i] != '经理级' && positionNames[i] != '总监级' && positionNames[i] != '总裁级'){
                        soql += ' HR_Post__c = \'' + positionNames[i] + '\'';
                    }
                    else if(positionNames[i] == '经理级'){
                        soql += ' HR_Post__c like \'%' + s1 + '%\'';
                    }
                    else if(positionNames[i] == '总监级'){
                        soql += ' HR_Post__c like \'%' + s2 + '%\'';
                    }
                    //20220517 lt SWAG-CD28H3 End
                    else if(positionNames[i] == '总裁级'){
                        soql += ' HR_Post__c like \'%' + s3 + '%\'';
                    }
                } else {
                    //20220517 lt SWAG-CD28H3 Start
                    if(positionNames[i] != '经理级' && positionNames[i] != '总监级' && positionNames[i] != '总裁级'){
                        soql += ' HR_Post__c = \'' + positionNames[i] + '\' or';
                    }
                    else if(positionNames[i] == '经理级'){
                        soql += ' HR_Post__c like \'%' + s1 + '%\' or';
                    }
                    else if(positionNames[i] == '总监级'){
                        soql += ' HR_Post__c like \'%' + s2 + '%\' or';
                    }
                    //20220517 lt SWAG-CD28H3 End
                    else if(positionNames[i] == '总裁级'){
                        soql += ' HR_Post__c like \'%' + s3 + '%\' or';
                    }
                }
            }
            soql += ')';
        }
        soql += ' order by Salesdepartment__c, Province__c, UserRole.Name';
        System.debug('**********123'+soql);
        return Database.query(soql);
    }
 
    // 数据赋值
    private void setBean(Integer year) {
        // 取得当前年度目标数据
        //Opportunity[] opportunitys = ControllerUtil.oppSelectForPersonTaget(rt.Id, users, currentPeriod);
        // OLY_OCM-202
        Opportunity[] opportunitys = [select
                                      Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                                      Amount, Objective__c, Target_category__c,
                                      SAP_Province__c, RecordTypeId, OCM_Target_period__c,TargetType__c,remarks__c
                                      from Opportunity
                                      where Target_category__c = '担当目标'
                                              and RecordTypeId = :rt.Id
                                                      and OwnerId in :users
                                                      //20210225 ljh WLIG-BV8CHF update  财年 start
                                                      //and OCM_Target_period__c = :currentPeriod];
                                                      and OCM_Target_period__c = :currentPeriodOld];
                                                      //20210225 ljh WLIG-BV8CHF update  财年 end
        //--------------20200605 ljh add start ------
        /*list<Amount_Major_Product__c> Existed_Amount_Major_Products = [select key__c, Amount__c, user_Alias__c,
                                   Is_Processing__c, iYear__c from Amount_Major_Product__c where iYear__c = : iYear ];*/
        //--------------20200605 ljh end start ------
        // 当前年度没有数据时,显示信息
        //&& opportunitys.size() <= 0   Existed_Amount_Major_Products.size()<=0
        system.debug('==currentPeriodOld=='+currentPeriodOld);
        if (opportunitys.size() <= 0  && isPast && iYear < currentYear) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, '没有上年度的数据。');
            ApexPages.addMessage(msg);
            previousRendered = false;
            iYear += 1;
            //20210225 ljh WLIG-BV8CHF update  财年 start
            //currentPeriod = String.valueOf(iYear - 1867 + 'P');
            currentPeriodOld = String.valueOf(iYear - 1867 + 'P');
            Integer tempiYear = iYear+1;
            currentPeriod = String.valueOf('FY'+tempiYear);
            //20210225 ljh WLIG-BV8CHF update  财年 end
            isPast = false;
            if (iYear < currentYear && !(currentYear - iYear == 1 && iMonth == 4 && iDay <= iBuffer)) {
                isPast = true;
            }// else if (iYear == currentYear) {
//                if (Date.today().month() == 3) {
//                    isPast = true;
//                }
//            }
            // 今表示しているデータを再取得
            setBean(iYear);
            return;
        }
        // 保存当前年度所有既存目标数据
        oppMap = new Map<String, Opportunity>();
        for (Opportunity opp : opportunitys) {
            if (opp.OwnerId != null && opp.Opportunity_Category__c != null && opp.CloseDate != null) {
                //  目标 key : OwnerId + _ + Opportunity_Category__c + _ + CloseDate(yyyy-mm-dd)
                String key = opp.OwnerId + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppMap.put(key, opp);
            }
        }
        // 2020/06/05 SWAG-BQ7CM9 读取中间既存表 by ljh
        getAmount_Major_Productmap();
 
        // 建立数据集
        dataBeans = new List<DataBean>();
        for (Integer u = 0; u < users.size(); u++) {
            DataBean dataBean = new DataBean(users[u], oppMap, iYear);
            // 2020/06/05 SWAG-BQ7CM9 与既有中间表数据进行对比,然后更新至visualforce page by ljh start
            // 数据检索Key
            for (Integer j = 0; j < amountCategory.size(); j++) {
                String key = users[u].Id + '_' + amountCategory[j] ;
                if (Amount_Major_ProductMap.containsKey(key)) {
 
                    Amount_Major_Product__c Amount_Major_Product = Amount_Major_ProductMap.get(key);
                    dataBean.amount[j].Amount = Amount_Major_Product.Amount__c;
                    //dataBean.opportunity.TargetType__c = Amount_Major_Product.TargetType__c;
                    dataBean.opportunity.TargetType__c = String.isNotBlank(Amount_Major_Product.TargetType__c) ? Amount_Major_Product.TargetType__c : '个人';
                    system.debug(Amount_Major_ProductMap.get(key)+'==key====='+key+'==='+Amount_Major_Product.Amount__c+'=='+Amount_Major_Product.TargetType__c);
                    dataBean.opportunity.remarks__c = Amount_Major_Product.remarks__c;// 20230510 ljh start
                } else {
                    dataBean.opportunity.TargetType__c = '个人'; 
                    // dataBean.amount[j].Amount = null;
                    dataBean.opportunity.remarks__c = '';// 20230510 ljh start
                }
                
            }
            // 2020/06/05 SWAG-BQ7CM9 与既有中间表数据进行对比,然后更新至visualforce page by ljh end
            dataBeans.add(dataBean);
        }
        system.debug('==dataBeans=='+dataBeans);
    }
 
    // 実際の保存ロジック
    /*private void saveLogic() {
        List<Opportunity> saveList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        // 只处理当前本部数据
        for (Integer d = 0; d < dataBeans.size(); d++) {
            DataBean db = dataBeans[d];
 
            // 寄存数据比例值是否变化
            Boolean proportionChanged = false;
            for (Integer i = 0; i < 12; i++) {
                Integer y = iYear;
                Integer m = 4 + i;
                if (m > 12) {
                    y += 1;
                    m -= 12;
                }
                String syear = String.valueOf(y);
                String smonth = String.valueOf(m);
                if (m < 10) {
                    smonth = '0' + smonth;
                }
                String sTargetDay = syear + '-' + smonth + '-01';
                // 按金额分类顺序处理
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    String amountC = amountCategory[j];
                    // 数据检索Key
                    String key = db.user.Id + '_' + amountC + '_' + sTargetDay;
                    // 每月数据赋值
                    Opportunity opp = new Opportunity();
                    if (oppMap.containskey(key)) {
                        opp = oppMap.get(key);
                        if (opp.Proportion__c != proportion.get(amountC)[i]) {
                            proportionChanged = true;
                            break;
                        }
                    }
                }
                if (proportionChanged) {
                    break;
                }
            }
            if (db.isChanged == '0' && !proportionChanged) {
                continue;
            }
            // 使用开始后目标金额补正系数计算
            //Decimal proportionSum = 0.0;
            Map<String, Decimal> proportionSumMap = new Map<String, Decimal>();
            for (Integer j = 0; j < amountCategory.size(); j++) {
                String amountC = amountCategory[j];
                proportionSumMap.put(amountC, 0.0);
            }
            for (Integer i = 0; i < 12; i++) {
                Integer y = iYear;
                Integer m = 4 + i;
                if (m > 12) {
                    y += 1;
                    m -= 12;
                }
                String syear = String.valueOf(y);
                String smonth = String.valueOf(m);
                if (m < 10) {
                    smonth = '0' + smonth;
                }
                String sTagetDay = syear + '-' + smonth + '-01';
                Date tagetDay = Date.valueOf(sTagetDay);
                if (db.user.Use_Start_Date__c < tagetDay) {
                    //proportionSum += proportion.get(amountC)[i];
                    for (Integer j = 0; j < amountCategory.size(); j++) {
                        String amountC = amountCategory[j];
                        proportionSumMap.put(amountC, proportionSumMap.get(amountC) + proportion.get(amountC)[i]);
                    }
                }
            }
            //proportionSum = proportionSum / 100;
            for (Integer j = 0; j < amountCategory.size(); j++) {
                String amountC = amountCategory[j];
                proportionSumMap.put(amountC, proportionSumMap.get(amountC) / 100);
            }
            // 一年分成12条数据
            for (Integer i = 0; i < 12; i++) {
                Integer y = iYear;
                Integer m = 4 + i;
                if (m > 12) {
                    y += 1;
                    m -= 12;
                }
                String syear = String.valueOf(y);
                String smonth = String.valueOf(m);
                if (m < 10) {
                    smonth = '0' + smonth;
                }
                String sTagetDay = syear + '-' + smonth + '-01';
                Date tagetDay = Date.valueOf(sTagetDay);
                if (db.user.Use_Start_Date__c >= tagetDay) {
                    // 使用開始当月 及び 開始前 は目標を登録しない,无视。
                    continue;
                }
                // 按金额分类顺序处理
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    String amountC = amountCategory[j];
                    // 数据检索Key
                    String key = db.user.Id + '_' + amountC + '_' + sTagetDay;
                    // 每月数据赋值
                    Opportunity opp = new Opportunity();
                    if (oppMap.containskey(key)) {
                        opp = oppMap.get(key);
                        if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                            deleteList.add(opp);
                            continue;
                        }
                        opp.Proportion__c = proportion.get(amountC)[i];
                        opp.Amount = db.amount[j].Amount / proportionSumMap.get(amountC);
                    } else {
                        if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                            continue;
                        }
                        opp.Name = db.user.Alias + ' 担当目标';
                        opp.StageName = '目標';
                        opp.OwnerId = db.user.Id;
                        // トリガをスルーのため、ここでやります
                        opp.Owner_System__c = db.user.Id;
                        opp.Opportunity_Category__c = amountC;
                        opp.Proportion__c = proportion.get(amountC)[i];
                        opp.CloseDate = tagetDay;
                        opp.Amount = db.amount[j].Amount / proportionSumMap.get(amountC);
                        opp.Target_category__c = '担当目标';
                        opp.SAP_Province__c = db.user.Province__c;
                        opp.RecordTypeId = rt.Id;
                        opp.OCM_Target_period__c = currentPeriod;
                    }
                    // 加入保存列表
                    saveList.add(opp);
                }
            }
            // 数据库限制小于10000条
            if (saveList.size() + deleteList.size() >= 4000) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '操作数据量过大,截止至' + db.user.Alias + '的数据操作完成,之后的数据请再次输入并保存。'));
                break;
            }
        }
        // トリガをスルー
        StaticParameter.EscapeOpportunityBefUpdTrigger = true;
        StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
        StaticParameter.EscapeNFM007Trigger = true;
 
        // 更新数据库
        if (saveList.size() > 0) upsert saveList;
        if (deleteList.size() > 0) delete deleteList;
 
 
 
    }*/
    private Boolean saveLogic() {
        List<Opportunity> saveList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
 
        list<Amount_Major_Product__c> InsertAmount_Major_Products = new list<Amount_Major_Product__c>();
        list<Amount_Major_Product__c> UpdateAmount_Major_Products = new list<Amount_Major_Product__c>();
        // 只处理当前本部数据
 
        //system.debug('===dataBeans==='+dataBeans);
        for (Integer d = 0; d < dataBeans.size(); d++) {
            DataBean db = dataBeans[d];
            for (Integer j = 0; j < amountCategory.size(); j++) {
                // 数据检索Key
                string key = db.user.Id + '_' + amountCategory[j];
                if (Amount_Major_ProductMap.containsKey(key)) {
                    //临时表已经有了
                    Amount_Major_Product__c Amount_Major_Product = Amount_Major_ProductMap.get(key);
                    // 20230510 ljh start
                    // if (Amount_Major_Product.Amount__c == db.amount[j].Amount) {
                    if (Amount_Major_Product.Amount__c == db.amount[j].Amount && Amount_Major_Product.TargetType__c == db.opportunity.TargetType__c && Amount_Major_Product.remarks__c == db.opportunity.remarks__c) {
                    // 20230510 ljh end
                        continue;
                    } else {
                        Amount_Major_Product.Amount__c = db.amount[j].Amount;
                        Amount_Major_Product.TargetType__c = db.opportunity.TargetType__c;
                        Amount_Major_Product.remarks__c = db.opportunity.remarks__c; // 20230510 ljh 
                        Amount_Major_Product.user_Alias__c = db.user.Alias;
                        Amount_Major_Product.SAP_Province__c = db.user.Province__c;
                        Amount_Major_Product.Use_Start_Date__c = db.user.Use_Start_Date__c;
                        Amount_Major_Product.iYear__c = iYear;
                        Amount_Major_Product.Is_Processing__c = true;
                        UpdateAmount_Major_Products.add(Amount_Major_Product);
                    }
 
                } else {
 
                    /*if (db.amount[j].Amount == null) {
                    //if (db.amount[j].Amount == null || db.amount[j].Amount == 0) {
                        continue;
                    }else{*/
                    //临时表里没有分  执行和没有执行
                    // 金额是否发生变化
                    Boolean proportionChanged = false;
                    for (Integer i = 0; i < 12; i++) {
                        Integer y = iYear;
                        Integer m = 4 + i;
                        if (m > 12) {
                            y += 1;
                            m -= 12;
                        }
                        String syear = String.valueOf(y);
                        String smonth = String.valueOf(m);
                        if (m < 10) {
                            smonth = '0' + smonth;
                        }
                        String sTargetDay = syear + '-' + smonth + '-01';
                        String amountC = amountCategory[j];
                        String keyOpp = db.user.Id + '_' + amountC + '_' + sTargetDay;
                        Opportunity opp = new Opportunity();
                        if (oppMap.containskey(keyOpp)) {
                            opp = oppMap.get(keyOpp);
                            //if (opp.Proportion__c != proportion.get(amountC)[i]) {
                            // 20230510 ljh start
                            // if (opp.Amount != db.amount[j].Amount) {
                            if (opp.Amount != db.amount[j].Amount || opp.TargetType__c != db.opportunity.TargetType__c || opp.remarks__c != db.opportunity.remarks__c) {
                            // 20230510 ljh end
                                proportionChanged = true;
                                break;
                            }
                        } else {
                            // 20230510 ljh start
                            // if (db.amount[j].Amount != null) {
                            if (db.amount[j].Amount != null || db.opportunity.TargetType__c != null || db.opportunity.remarks__c != null) {
                            // 20230510 ljh end
                                proportionChanged = true;
                                break;
                            }
 
                        }
                    }
                    system.debug('===proportionChanged===' + proportionChanged);
                    if (proportionChanged) {
                        Amount_Major_Product__c Amount_Major_Product = new Amount_Major_Product__c();
                        Amount_Major_Product.key__c = key;
                        Amount_Major_Product.Amount__c = db.amount[j].Amount;
                        Amount_Major_Product.TargetType__c = db.opportunity.TargetType__c;
                        Amount_Major_Product.remarks__c = db.opportunity.remarks__c; // 20230510 ljh 
                        Amount_Major_Product.user_Alias__c = db.user.Alias;
                        Amount_Major_Product.SAP_Province__c = db.user.Province__c;
                        Amount_Major_Product.Use_Start_Date__c = db.user.Use_Start_Date__c;
                        Amount_Major_Product.iYear__c = iYear;
                        Amount_Major_Product.Is_Processing__c = true;
                        InsertAmount_Major_Products.add(Amount_Major_Product);
                    }
                    //}
                }
            }
        }
        if ( InsertAmount_Major_Products.size() > 0 ) {
            insert InsertAmount_Major_Products;
        }
        if ( UpdateAmount_Major_Products.size() > 0 ) {
            update UpdateAmount_Major_Products;
        }
        return true;
    }
 
    // 数据类
    class DataBean {
        // 担当者信息
        public User user { get; private set; }
        // 总金额,画面用
        public Opportunity[] amount { get; set; }
        // 是否变化 0:无 1:有
        public String isChanged { get; set; }
        //目标类型
        public Opportunity opportunity { get; set; }
 
        // 20230510 ljh start
        // 备注
        public String remarks { get; set; }
        // 20230510 ljh end
        // 构造方法
        DataBean(User user, Map<String, Opportunity> oppMap, Integer iYear) {
            this.user = user;
            this.amount = new List<Opportunity>();
            this.isChanged = '0';
            this.opportunity = new Opportunity();
            this.opportunity.TargetType__c = '个人';
            this.remarks = ''; // 20230510 ljh add
            // 按金额分类,查找数据,并设值
            for (Integer i = 0; i < amountCategory.size(); i++) {
                String amountC = amountCategory[i];
                Opportunity a = new Opportunity();
                a.Opportunity_Category__c = amountC;
                Decimal amountSum = 0.0;
                // 2020/06/05 SWAG-BQ7CM9 从Opportunity赋值到vf page上 by ljh start
                for (Integer j = 0; j < 12; j++) {
                    Integer y = iYear;
                    Integer m = 4 + j;
                    if (m > 12) {
                        y += 1;
                        m -= 12;
                    }
                    String strY = String.valueOf(y);
                    String strM = String.valueOf(m);
                    if (strM.length() < 2) {
                        strM = '0' + strM;
                    }
                    String key = user.Id + '_' + amountC + '_' + strY + '-' + strM + '-01';
                    if (oppMap.containskey(key)) {
                        //a.Amount = oppMap.get(key).Amount;
                        amountSum += oppMap.get(key).Objective__c == null ? 0 : oppMap.get(key).Objective__c;
                        this.opportunity.TargetType__c = oppMap.get(key).TargetType__c;
                        this.opportunity.remarks__c = oppMap.get(key).remarks__c;// 20230510 ljh start
                    }else{
                        this.opportunity.TargetType__c = '个人'; 
                        this.opportunity.remarks__c = ''; // 20230510 ljh start
                    }
                }
                if (amountSum > 0) {
                    amountSum = amountSum.setScale(2);
                    a.Amount = amountSum;
                }
                // 2020/06/05 SWAG-BQ7CM9 从Opportunity赋值到vf page上 by ljh end
                this.amount.add(a);
            }
        }
    }
 
    // 職位チェックボックスリスト作成
    class Position {
        public String positionName { get; private set; }
        public Boolean check { get; set; }
 
        public Position(String positionName, Boolean flg) {
            this.positionName = positionName;
            this.check = flg;
        }
    }
}