高章伟
2022-02-18 8b5f4c6c281cfa548f92de52c8021e37aa81901e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
public with sharing class SetProductTargetController {
    // 当前期
    public String currentPeriod { get; private set; }
    public String currentPeriodOld;//20210225 WLIG-BV8CHF ljh 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 String target_category { get; set; }
    // 製品プルダウン用
    public Opportunity opp { get; set; }
    public Integer titleSize { get; set; } 
        
    public SetProductTargetController() {
           //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
    }
 
    
    
    // 本部プルダウン
    public static List<SelectOption> salesDptOpts { get; private set; }
    static {
        salesDptOpts = new List<SelectOption>();
        salesDptOpts.add(new SelectOption('0.无','--无--'));
        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.华南'));
        //CHAN-BDQBLX  20210204 ljh update start
        /*salesDptOpts.add(new SelectOption('7.能量-1.华北','7.能量-1.华北'));
        salesDptOpts.add(new SelectOption('7.能量-2.东北','7.能量-2.东北'));
        salesDptOpts.add(new SelectOption('7.能量-3.西北','7.能量-3.西北'));
        salesDptOpts.add(new SelectOption('7.能量-4.西南','7.能量-4.西南'));
        salesDptOpts.add(new SelectOption('7.能量-5.华东','7.能量-5.华东'));
        salesDptOpts.add(new SelectOption('7.能量-6.华南','7.能量-6.华南'));*/
        //CHAN-BDQBLX  20210204 ljh update end
    }
    // 重点目标分类
    public static List<SelectOption> targetOpts { get; private set; }
    static {
        targetOpts = new List<SelectOption>();
        targetOpts.add(new SelectOption('重点产品目标(数量)','重点产品目标(数量)'));
        targetOpts.add(new SelectOption('重点产品目标(金额)','重点产品目标(金额)'));
    }
    
    //  现在年度
    private Integer currentYear;
    //  当前年度
    private Integer iYear;
 
    public User loginUser { get; set; }          // 登陆用户
    private RecordType rt;           // 目标的数据类型
    private Map<String, List<Double>> proportion;    // 比重
    
    private List<String> provinces;
    private Map<String,List<String>> salesDptMap;  //本部-省对应关系
    private Map<String,String> provinceMap;        //省-本部对应关系
 
    private boolean isEng;
    
    //更新用条件
    //private String old_target_category;
    //private String old_important_Key_product_category;
    
    // 既存目标数据
    private Map<String, Opportunity> oppsMap;
    private Map<String, AggregateResult> oliMap;
    //2020/07/08 中间表寄存数据 by ld
    private Map<String,Key_Product_Goals__c> Key_Product_GoalsMap;
    public Key_Product_Goals__c[] Existed_Key_Product_Goals;
    // 金额分类 xiongyl
   // private static String[] amountCategory = new String[] {'GI','ET','BF','GS','URO','GYN','ENT','OTH'};
    public static List<String> amountCategory { get; private set; }
    public static List<ImportantProductCategory__c> pcList { get; private set; }
    public static Map<String, boolean> isCntMap = new Map<String, boolean>();
    public static Map<String,String> NkeyMap= new Map<String,String>();//20210204 CHAN-BDQBLX  ljh add
    static {
        amountCategory = new List<String>();
        pcList = [select depName__c,importantProductGoaIName__c,commodityCode__c,commodityName__c,if_Quantity__c,sort__c from ImportantProductCategory__c order by sort__c];
        for (ImportantProductCategory__c pc : pcList) {
            isCntMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.if_Quantity__c);
            if (pc.depName__c != null) {
                amountCategory.add(pc.commodityName__c + '(' + pc.depName__c + ')' + (pc.if_Quantity__c ? '' : '金额'));
                NkeyMap.put(pc.commodityName__c + '(' + pc.depName__c + ')' + (pc.if_Quantity__c ? '' : '金额'),pc.importantProductGoaIName__c + '_' + pc.depName__c);//CHAN-BDQBLX  20210204 ljh add
            }else {
                amountCategory.add(pc.commodityName__c + (pc.if_Quantity__c ? '' : '金额'));
                NkeyMap.put(pc.commodityName__c + (pc.if_Quantity__c ? '' : '金额'),pc.importantProductGoaIName__c + '_' + pc.depName__c);//CHAN-BDQBLX  20210204 ljh add
            }
        }
    }
    
    // 重点製品API名マップ
    public static Map<String, String> impProductApiMap = new Map<String, String> {
        '重点产品01' => 'Important_product1__c',
        '重点产品02' => 'Important_product2__c',
        '重点产品03' => 'Important_product3__c',
        '重点产品04' => 'Important_product4__c',
        '重点产品05' => 'Important_product5__c',
        '重点产品06' => 'Important_product6__c',
        '重点产品07' => 'Important_product7__c',
        '重点产品08' => 'Important_product8__c',
        '重点产品09' => 'Important_product9__c',
        '重点产品10' => 'Important_product10__c',
        '重点产品11' => 'Important_product11__c',
        '重点产品12' => 'Important_product12__c',
        '重点产品13' => 'Important_product13__c',
        '重点产品14' => 'Important_product14__c',
        '重点产品15' => 'Important_product15__c',
        '重点产品16' => 'Important_product16__c',
        '重点产品17' => 'Important_product17__c',
        '重点产品18' => 'Important_product18__c',
        '重点产品19' => 'Important_product19__c',
        '重点产品20' => 'Important_product20__c',
        '重点产品21' => 'Important_product21__c',
        '重点产品22' => 'Important_product22__c',
        '重点产品23' => 'Important_product23__c',
        '重点产品24' => 'Important_product24__c',
        '重点产品25' => 'Important_product25__c',
        '重点产品26' => 'Important_product26__c',
        '重点产品27' => 'Important_product27__c',
        '重点产品28' => 'Important_product28__c',
        '重点产品29' => 'Important_product29__c',
        '重点产品30' => 'Important_product30__c',
        '重点产品31' => 'Important_product31__c'
    };
    public static List<SelectOption> impProductOptions { get; private set; }
    static {
        impProductOptions = new List<SelectOption>();
        impProductOptions.add(new SelectOption('重点产品01', Product2.Important_product1__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品02', Product2.Important_product2__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品03', Product2.Important_product3__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品04', Product2.Important_product4__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品05', Product2.Important_product5__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品06', Product2.Important_product6__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品07', Product2.Important_product7__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品08', Product2.Important_product8__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品09', Product2.Important_product9__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品10', Product2.Important_product10__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品11', Product2.Important_product11__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品12', Product2.Important_product12__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品13', Product2.Important_product13__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品14', Product2.Important_product14__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品15', Product2.Important_product15__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品16', Product2.Important_product16__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品17', Product2.Important_product17__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品18', Product2.Important_product18__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品19', Product2.Important_product19__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品20', Product2.Important_product20__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品21', Product2.Important_product21__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品22', Product2.Important_product22__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品23', Product2.Important_product23__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品24', Product2.Important_product24__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品25', Product2.Important_product25__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品26', Product2.Important_product26__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品27', Product2.Important_product27__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品28', Product2.Important_product28__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品29', Product2.Important_product29__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品30', Product2.Important_product30__c.getDescribe().getlabel()));
        impProductOptions.add(new SelectOption('重点产品31', Product2.Important_product31__c.getDescribe().getlabel()));
    }
    //CHAN-BDQBLX  20210204 ljh start
    private List<Key_Product_Goals__c> upsertKPGList;
    private Map<String, Key_Product_Goals__c> Key_Product_GoalsMap1;
    public string csvAsString {get; set;}
    public String[] csvFileLines {get; set;}
    private static List<String> titlepage = new List<String>{'销售本部', '省', '担当'};
    public Integer detailCountLimit{get;private set;}
    //CHAN-BDQBLX  20210204 ljh end
    // 画面初始化
    public Pagereference init() {
        // 现在时间
        Date dateNow = Date.today();
        Integer year = dateNow.year();
        Integer month = dateNow.month();
        //CHAN-BDQBLX  20210204 LJH start
        Key_Product_GoalsMap1 = new Map<String, Key_Product_Goals__c>();
        upsertKPGList = new List<Key_Product_Goals__c>();
        detailCountLimit = 10000;
        //CHAN-BDQBLX  20210204 LJH end
        if (month < 4) {
            year -= 1;
        }
        // 初始化
        opp = new Opportunity();
        // xiongyl 修改后初始化的时候取得的是22种产品对应的数据
        //opp.Important_Key_product_category__c = '重点产品01';
        
        currentYear = year;
        iYear = year;
        isPast = false;
        // 20200304 开放管理员权限 Start
        //if (month == 3) isPast = true;
        if (month == 3 && UserInfo.getProfileId() != System.Label.ProfileId_SystemAdmin) isPast = true;
        // 20200304 开放管理员权限 End
        //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;
        target_category = '省重点产品目标';
        titleSize = pcList.size();
        
        //old_target_category = target_category;
        //old_important_Key_product_category = opp.Important_Key_product_category__c;
        
        // 金额分类
        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);
 
            String strObjectiveProportionENG = System.Label.ObjectiveProportionENG;
            List<String> objectiveProportionENG = strObjectiveProportionENG.split(',');
            List<Double> doubleENG = new List<Double>();
            for (String strENG : objectiveProportionENG) {
                doubleENG.add(Double.valueOf(strENG));
            }
            proportion.put('ENG', doubleENG);
        }
        // 当前用户信息
        if (loginUser == null) {
            loginUser = [Select Id, Salesdepartment__c, ProfileId From User where Id = :Userinfo.getUserId()];
        }
        
        getsalesDptMap();
        //salesDpt = '0.无';
        salesDpt = '1.华北';
        provinces = new List<String>();
        provinces = salesDptMap.get(salesDpt);
 
        isEng = false;
        
        // 目标的数据类型
        if (rt == null) {
            rt = [select Id from RecordType where SobjectType = 'Opportunity' and IsActive = true and DeveloperName = 'Target'];
        }
        // 数据赋值
        setBean(iYear);
 
        return null;
    }
    
    //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
    private boolean checkCurrentDate(){
        boolean dateResult = true;
        Date today = Date.today();
        Date date415 = Date.newInstance(today.year(), 4, 
            Integer.valueOf(System.Label.SetPersonalTarget_buffer_day));
 
        if(iYear >= currentYear -1 && today <= date415 )
            dateResult = false;
        return dateResult;
    }
    //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
    
    // 点击上年度
    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;
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
        if (iYear < currentYear && checkCurrentDate()) {
            isPast = true;
        }
 
        // else if (iYear == currentYear) {
        //    if (Date.today().month() == 3) {
        //        isPast = true;
        //    }
        //}
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
        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;
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 start
        if (iYear < currentYear && checkCurrentDate()) {
            isPast = true;
        }  
        //else if (iYear == currentYear) {
        //    if (Date.today().month() == 3) {
        //        isPast = true;
        //    }
        //}
         //SWAG-BB48QB 判断当前时间是否是4月15日之后 end
        previousRendered = true;
        nextRendered = true;
        // 只显示到现在时间的下一年数据
        if (iYear > currentYear) {
            nextRendered = false;
        }
        // 数据赋值
        setBean(iYear);
    }
    
    // 本部プルダウン変更時の処理
    public void searchByDpt() {
        if (saveFlg) {
            this.saveLogic();
        }
        //CHAN-BDQBLX  20210220 ljh update start
        /*Map<String, String> engMap = new Map<String, String>();
        engMap.put('7.能量-1.华北','7.能量-1.华北');
        engMap.put('7.能量-2.东北','7.能量-2.东北');
        engMap.put('7.能量-3.西北','7.能量-3.西北');
        engMap.put('7.能量-4.西南','7.能量-4.西南');
        engMap.put('7.能量-5.华东','7.能量-5.华东');
        engMap.put('7.能量-6.华南','7.能量-6.华南');
        if (engMap.containsKey(salesDpt)) {
            isEng = true;
        } else {
            isEng = false;
        }*/
        //CHAN-BDQBLX  20210220 ljh update end
        provinces = new List<String>();
        provinces = salesDptMap.get(salesDpt);
        opp.SAP_Province__c = null;
        //CHAN-BDQBLX  20210207 ljh update start
        //if (salesDpt != '0.无') {
            // 数据赋值
            setBean(iYear);
        //}
        //CHAN-BDQBLX  20210207 ljh update end
    }
    
    // 省プルダウン変更時の処理
    public void searchByProvince() {
        if (saveFlg) {
            this.saveLogic();
        }
 
        provinces = new List<String>();
        salesDpt = '0.无';
        if (opp.SAP_Province__c == null) {
            provinces = salesDptMap.get(salesDpt);
        } else {
            provinces.add(opp.SAP_Province__c);
        }
 
        isEng = false;
 
        // 数据赋值
        setBean(iYear);
    }
    
    // 重点目標分類変更時の処理
    public void searchByCategory() {
        if (saveFlg) {
            this.saveLogic();
        }
        //old_target_category = target_category;
        // 数据赋值
        setBean(iYear);
    }
    
    // 重点製品変更時の処理
    public void searchByImpKey() {
        if (saveFlg) {
            this.saveLogic();
        }
        //old_important_Key_product_category = opp.Important_Key_product_category__c;
        // 数据赋值
        setBean(iYear);
    }
    //CHAN-BDQBLX  20210204 ljh start 导入出方法 start
    //导出方法
    public Pagereference exportBycsv() {
        setBean(iYear);
        return page.SetProductTargetcvs;                 
    }
    //导入方法
    public PageReference importCSVFile() {
        try {
            String csvData = ApexPages.currentPage().getParameters().get('csvData');
            // 将内容转换成为中文
            if(!Test.isRunningTest()){
                //csvAsString = bitToString(csvFileBody, 'gb2312');
                csvAsString = csvData;
            }            
            // 拆成每一行
            csvFileLines = csvAsString.split('\n');
            Boolean ValFlag = false;
            String exportByVal = '';
            ApexPages.Message successMsg = new ApexPages.Message(ApexPages.severity.INFO, '');
            // 需要根据情况来解析,查看表头是否一致
            if(opportunity_category !=null && opportunity_category.size()>0){
                titlepage.addAll(opportunity_category);
            }
            String target_Source1 = 'SalesTarget';
            String salesDpt1;
            if (csvFileLines.size() > 0) {
                string[] titlecsv = csvFileLines[0].trim().split(',');
                System.debug('==titlepage=='+titlepage);
                System.debug('==titlecsv=='+titlecsv);
                if(titlecsv[0].split(':').size()>=2){
                    if (titlecsv[0].split(':')[1].contains('能量')) {
                        target_Source1 = 'EngTarget';
                    }
                    /**
                    salesDpt = titlecsv[0].split(':')[1];
                    if(titlecsv[0].split(':').size()==3){
                        opp.SAP_Province__c = titlecsv[0].split(':')[2];
                    }else{
                        opp.SAP_Province__c = null;
                    }
                    **/
                    titlecsv[0] = titlecsv[0].split(':')[0];                    
                }                
                for (integer j = 0; j < titlecsv.size(); j++) {
                    if (!titlepage.contains(titlecsv[j])) {
                        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>();//省份
                for (Integer i = 1; i < csvFileLines.size(); i++) {
                    string[] csvRecordData = csvFileLines[i].split(',');
                    if (csvRecordData.size() > 0) {
                        String bu = csvRecordData[0].replace(' ', '');
                        String sf = csvRecordData[1].replace(' ', '');
                        String dandang = csvRecordData[2].replace(' ', '');
                        if(String.isNotBlank(dandang)){
                            UserInfoList.add(dandang);//根据 担当查user     
                        }
                        szMap.put(bu+'_'+ sf + '_'+dandang, csvRecordData);
                        sfs.add(sf);//把省份放进去 
                    }
                }
                if (null != sfs && sfs.size() > 0) {
                    this.getKey_Product_Goals(sfs);//根据省份年份,获取当前系统中已经存在得数据 放到map中 
                }
                List<User> userList  = new List<User>();
                if (null != UserInfoList && UserInfoList.size() > 0) {
                    userList = this.getUserList(UserInfoList);//返回用户得一些信息
                }
                Map<String, User> userMap = new Map<String, User>();
                for (User userl : userList) {
                    userMap.put(userl.Alias, userl);
                }                
                upsertKPGList = new List<Key_Product_Goals__c>();//初始化,解决重复导入数据 id重复得问题
                for (String key : szMap.keySet()) {
                    //取用户的Id
                    String userid = '';
                    String key_shengfen=key.split('_')[1];//省份
                    String key_dandang= '';
                    if(key.split('_').size()>=3){
                         key_dandang=key.split('_')[2];//把担当取出来
                    }
                    if (userMap.containskey(key_dandang)) {
                        userid = userMap.get(key_dandang).Id;
                    } else {
                        System.debug('==key==='+key);
                        //用户不存在要提醒
                        continue;
                    }
                    System.debug('==userid:'+userid);
                    //String key = dataBean.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                // pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                   //--------
                    List<String> csvRecordData = szMap.get(key);
                    Key_Product_Goals__c upsertKPG = new Key_Product_Goals__c();
                    Integer tI = amountCategory.size()+3;//数字3取决于导入的cvs重点产品前的个数
                    System.debug('amountCategory.size():'+amountCategory.size());
                    for(Integer i = 3;i<tI;i++){
                        Integer  Num_Of_OPD;
                        if(String.isNotBlank(csvRecordData[i])){
                            if(i==(tI-1)){
                                Num_Of_OPD = Integer.valueOf(csvRecordData[i].trim());
                            }else{
                                Num_Of_OPD = Integer.valueOf(csvRecordData[i]);
                            }
                        }
 
                        String nkey = csvRecordData[1] + '_' + target_category + '_' +NkeyMap.get(amountCategory[i-3])+'_'+target_Source1;
                        DataSplicing(Num_Of_OPD,nkey,target_Source1,csvRecordData,Key_Product_GoalsMap1,userid);
                    }
                }
                if(null!=upsertKPGList && upsertKPGList.size()>0){
                    upsert upsertKPGList;
                }
                /**
                provinces = new List<String>();
                if (salesDpt != null && opp.SAP_Province__c != null && salesDpt == '0.无' && opp.SAP_Province__c != '0.无') {
                    provinces.add(opp.SAP_Province__c);
                } else {
                    provinces = salesDptMap.get(salesDpt);
                }
                **/
                // 数据赋值
                setBean(iYear);
                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;
    }
    // 最终得数据处理,
    private void DataSplicing(Integer NumOfOPD, String key,String target_Source,List<String> csvRecordData, Map<String, Key_Product_Goals__c> nmpMap,String userId) {//去进行最终数据得插入,更新或删除操作
        Key_Product_Goals__c upsertKPG = new Key_Product_Goals__c();
        Key_Product_Goals__c Key_Product_Goals = Key_Product_GoalsMap.get(key);  
        if (nmpMap.containskey(key)) {
            upsertKPG = nmpMap.get(key);
            if (NumOfOPD > 0) {
                if(NumOfOPD != upsertKPG.Num_Of_OPD__c){
                    upsertKPG.Num_Of_OPD__c = NumOfOPD;
                    upsertKPG.Owner_System__c = userId;
                    upsertKPG.Is_Processing__c = true;
                    upsertKPGList.add(upsertKPG);
                    //更新
                }
                
            } else {
                //不用删除了,允许 数据是空的存在
                upsertKPG.Num_Of_OPD__c = null;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Owner_System__c = userId;
                upsertKPGList.add(upsertKPG);
            }
        } else {
            if (NumOfOPD > 0) {
                upsertKPG.Num_Of_OPD__c = NumOfOPD;
                upsertKPG.key__c = key;
                upsertKPG.Owner_System__c = userId;
                upsertKPG.SAP_Province__c = csvRecordData[1];
                upsertKPG.Department__c = csvRecordData[0];
                upsertKPG.iYear__c = iYear;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Target_Source__c = target_Source;
                upsertKPGList.add(upsertKPG);
            } else {
                //允许 数据是空的存在
                upsertKPG.Num_Of_OPD__c = null;
                upsertKPG.key__c = key;
                upsertKPG.Owner_System__c = userId;
                upsertKPG.SAP_Province__c = csvRecordData[1];
                upsertKPG.Department__c = csvRecordData[0];
                upsertKPG.iYear__c = iYear;
                upsertKPG.Is_Processing__c = true;
                upsertKPG.Target_Source__c = target_Source;
                upsertKPGList.add(upsertKPG);
            }
        }
    }
    private void getKey_Product_Goals(Set<String> sfs) {//根据省份年份,获取当前系统中已经存在得数据
        Key_Product_GoalsMap1 = new Map<String, Key_Product_Goals__c>();
 
        list<Key_Product_Goals__c> Existed_Key_Product_Goals = [select key__c, Num_Of_OPD__c, Owner_System__c,
                                      Is_Processing__c, iYear__c from Key_Product_Goals__c where iYear__c = : iYear and SAP_Province__c in :sfs];
        for (Key_Product_Goals__c Key_Product_Goals : Existed_Key_Product_Goals ) {
            if (String.isBlank(Key_Product_Goals.key__c)) {
                continue;
            }
            Key_Product_GoalsMap1.put(Key_Product_Goals.key__c, Key_Product_Goals);
        }
    }
    private List<User> getUserList(List<String> UserInfoList) {
        String soql = 'select Id,Alias from User where IsActive = true'
                      + ' and (Alias IN :UserInfoList'+' OR Id IN :UserInfoList '
                      +') order by Salesdepartment__c, Province__c';
        System.debug('==soql==' + soql);
        return Database.query(soql);
    }
    //CHAN-BDQBLX  20210204 ljh start 导入出方法 end
    // 点击保存按钮
    public Pagereference saveBtn() {
        boolean rs = saveLogic();
        setBean(iYear);
        if (rs) {
            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/07/08 从中间表获取既有数据
    private boolean getKey_Product_Goalsmap() {
        Key_Product_GoalsMap = new Map<String,Key_Product_Goals__c>();
 
        Existed_Key_Product_Goals = [select id, key__c,Num_Of_OPD__c,Department__c,SAP_Province__c,Owner_System__c,iYear__c
                                                                FROM Key_Product_Goals__c where iYear__c = : iYear ];
        
        if (Existed_Key_Product_Goals.size() <= 0) {
            return false;
        }
 
        // 将所数据存入map中
        for ( Key_Product_Goals__c Key_Product_Goal : Existed_Key_Product_Goals ){
            if (String.isBlank(Key_Product_Goal.key__c)) {
                continue;
            }
            Key_Product_GoalsMap.put(Key_Product_Goal.key__c,Key_Product_Goal);
        }
 
        return true;
    }
    
    //获取本部-省对应关系
    private void getsalesDptMap() {
        salesDptMap = new Map<String,List<String>>();
        
        List<String> provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河南省');
        provinceList.add('河北省');
        provinceList.add('山西省');
        provinceList.add('内蒙古');
        provinceList.add('山东省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('甘肃省');
        provinceList.add('新疆自治区');
        provinceList.add('辽宁省');
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        provinceList.add('安徽省');
        provinceList.add('江西省');
        provinceList.add('广东省');
        provinceList.add('广西自治区');
        provinceList.add('海南省');
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        provinceList.add('深圳市');
        provinceList.add('大连市');
        provinceList.add('青岛市');
        salesDptMap.put('0.无',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河北省');
        provinceList.add('内蒙古');
        provinceList.add('山东省');
        provinceList.add('青岛市');
        salesDptMap.put('1.华北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('辽宁省');
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('大连市');
        salesDptMap.put('2.东北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('河南省');
        provinceList.add('山西省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('甘肃省');
        provinceList.add('新疆自治区');
        salesDptMap.put('3.西北',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        provinceList.add('安徽省');
        provinceList.add('江西省');
        salesDptMap.put('5.华东',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('广东省');
        provinceList.add('广西自治区');
        provinceList.add('海南省');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        provinceList.add('深圳市');
        salesDptMap.put('6.华南',provinceList);
        
        provinceList = new List<String>();
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        salesDptMap.put('4.西南',provinceList);
        //CHAN-BDQBLX  20210204 ljh update start
        /*provinceList = new List<String>();
        provinceList.add('北京市');
        provinceList.add('天津市');
        provinceList.add('河北省');
        provinceList.add('山东省');
        provinceList.add('河南省');
        salesDptMap.put('7.能量-1.华北',provinceList);
 
        provinceList = new List<String>();
        provinceList.add('黑龙江省');
        provinceList.add('吉林省');
        provinceList.add('辽宁省');
        provinceList.add('大连市');
        provinceList.add('内蒙古');
        salesDptMap.put('7.能量-2.东北',provinceList);
 
        provinceList = new List<String>();
        provinceList.add('山西省');
        provinceList.add('陕西省');
        provinceList.add('青海省');
        provinceList.add('宁夏自治区');
        provinceList.add('新疆自治区');
        provinceList.add('甘肃省');
        salesDptMap.put('7.能量-3.西北',provinceList);
 
        provinceList = new List<String>();
        provinceList.add('四川省');
        provinceList.add('重庆市');
        provinceList.add('云南省');
        provinceList.add('贵州省');
        provinceList.add('西藏自治区');
        salesDptMap.put('7.能量-4.西南',provinceList);
 
        provinceList = new List<String>();
        provinceList.add('上海市');
        provinceList.add('江苏省');
        provinceList.add('江西省');
        provinceList.add('安徽省');
        provinceList.add('浙江省');
        provinceList.add('福建省');
        salesDptMap.put('7.能量-5.华东',provinceList);
 
        provinceList = new List<String>();
        provinceList.add('广东省');
        provinceList.add('深圳市');
        provinceList.add('海南省');
        provinceList.add('广西自治区');
        provinceList.add('湖北省');
        provinceList.add('湖南省');
        salesDptMap.put('7.能量-6.华南',provinceList);*/
        //CHAN-BDQBLX  20210204 ljh update end
        provinceMap = new Map<string,string>();
        
        provinceMap.put('北京市','1.华北');
        provinceMap.put('天津市','1.华北');
        provinceMap.put('河北省','1.华北');
        provinceMap.put('内蒙古','1.华北');
        provinceMap.put('山东省','1.华北');
        provinceMap.put('青岛市','1.华北');
        
        provinceMap.put('辽宁省','2.东北');
        provinceMap.put('黑龙江省','2.东北');
        provinceMap.put('吉林省','2.东北');
        provinceMap.put('大连市','2.东北');
        
        provinceMap.put('河南省','3.西北');
        provinceMap.put('山西省','3.西北');
        provinceMap.put('陕西省','3.西北');
        provinceMap.put('青海省','3.西北');
        provinceMap.put('宁夏自治区','3.西北');
        provinceMap.put('甘肃省','3.西北');
        provinceMap.put('新疆自治区','3.西北');
        
        provinceMap.put('上海市','5.华东');
        provinceMap.put('江苏省','5.华东');
        provinceMap.put('浙江省','5.华东');
        provinceMap.put('福建省','5.华东');
        provinceMap.put('安徽省','5.华东');
        provinceMap.put('江西省','5.华东');
        
        provinceMap.put('广东省','6.华南');
        provinceMap.put('广西自治区','6.华南');
        provinceMap.put('海南省','6.华南');
        provinceMap.put('湖北省','6.华南');
        provinceMap.put('湖南省','6.华南');
        provinceMap.put('深圳市','6.华南');
        
        provinceMap.put('四川省','4.西南');
        provinceMap.put('重庆市','4.西南');
        provinceMap.put('云南省','4.西南');
        provinceMap.put('贵州省','4.西南');
        provinceMap.put('西藏自治区','4.西南');
    }
    
    // 数据赋值
    private void setBean(Integer year) {
        String target_Source = 'SalesTarget';
        if (isEng == true) {
            target_Source = 'EngTarget';
        }
        // 取得当前年度目标数据
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Proportion__c, Opportunity_Category__c, CloseDate,
                        Target_category__c, Important_Key_product_category__c,
                        SAP_Province__c, Owner_System__c,Owner_System__r.Name, Target_Source__c
                 from Opportunity
                where Target_category__c = :target_category
                  // xionyl去掉重点产品名称的查询条件
                 // and Important_Key_product_category__c = :opp.Important_Key_product_category__c
                  and RecordTypeId = :rt.Id
                  //20210225 ljh WLIG-BV8CHF update  财年 start
                  //and OCM_Target_period__c = :currentPeriod
                  and OCM_Target_period__c = :currentPeriodOld
                  //20210225 ljh WLIG-BV8CHF update  财年 end
                  and SAP_Province__c in :provinces
                  and Target_Source__c = :target_Source];
        // 当前年度没有数据时,显示信息
        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) {
                isPast = true;
            } else if (iYear == currentYear) {
                if (Date.today().month() == 3) {
                    isPast = true;
                }
            }
            // 今表示しているデータを再取得
            setBean(iYear);
            return;
        }
        oppsMap = new Map<String, Opportunity>();
        for (Opportunity opp : opportunitys) {
            if (opp.OwnerId != null && opp.CloseDate != null){
                String key = opp.SAP_Province__c + '_' + opp.Target_category__c + '_' + opp.Important_Key_product_category__c
                           + '_' + opp.Opportunity_Category__c + '_' + String.valueOf(opp.CloseDate);
                oppsMap.put(key, opp);
            }
        }
 
        // 2020/07/08 读取中间寄存表 by ld
        getKey_Product_Goalsmap();
        
        AggregateResult[] opportunityLineItems = [select OpportunityId,SUM(NumberOfObjective__c) sum_n,SUM(Objective__c) sum_o from OpportunityLineItem where OpportunityId in :opportunitys group by OpportunityId];
        oliMap = new Map<String, AggregateResult>();
        for (AggregateResult oli : opportunityLineItems) {
            oliMap.put((String) oli.get('OpportunityId'), oli);
        }
        
        List<String> UserId = new List<String>();//CHAN-BDQBLX 20210205 ljh add
        //建立数据集
        dataBeans = new List<DataBean>();
        for (String pro : provinces) {
            DataBean dataBean = new DataBean(provinceMap.get(pro), pro, oppsMap, iYear, target_category, oliMap, pcList);
 
            // 2020/07/10 与既有中间表数据进行对比 by ld start
            for (Integer j = 0; j < pcList.size(); j++) {
                ImportantProductCategory__c pc = pcList[j];
                String key = dataBean.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                 pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                // String key = dataBean.opportunity.SAP_Province__c + '_' + amountCategory[j];
                if (Key_Product_GoalsMap.containsKey(key)){
                    Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                    dataBean.opportunity.Owner_System__c = Key_Product_Goal.Owner_System__c;
                    dataBean.amount[j].Num_Of_OPD__c = Key_Product_Goal.Num_Of_OPD__c;
                    //CHAN-BDQBLX  20210204 ljh start 
                    UserId.add(Key_Product_Goal.Owner_System__c);
                    //CHAN-BDQBLX  20210204 ljh end
                }
            }
            // 2020/07/10 与既有中间表数据进行对比 by ld end
            dataBeans.add(dataBean);
        }
        //CHAN-BDQBLX  20210204 ljh start
        List<User> userList  = new List<User>();
        Map<String,String> userIdAMap  = new Map<String,String>();
        if (null != UserId && UserId.size() > 0) {
            userList = this.getUserList(UserId);//返回用户得一些信息
        }
        for(User u:userList){
            userIdAMap.put(u.Id,u.Alias);
        }
        for(dataBean db:dataBeans){
            //System.debug('==='+db);
            if(userIdAMap.containsKey(db.opportunity.Owner_System__c)){
                db.ownername = userIdAMap.get(db.opportunity.Owner_System__c);
            }
        }
        //CHAN-BDQBLX  20210204 ljh end
    }
    
    // 是否删除整行数据
    private boolean isDelete(DataBean db) {
        if (db.opportunity.Owner_System__c == null) {
            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);
                // 按金额分类顺序处理
                for (Integer j = 0; j < pcList.size(); j++) {
                    ImportantProductCategory__c pc = pcList[j];
                    // 数据检索Key
                    String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + opp.Important_Key_product_category__c + '_' + pc.depName__c + '_' + sTagetDay;
                    if (oppsMap.containskey(key)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 実際の保存ロジック
    /*private boolean saveLogic() {
        List<Opportunity> insertList = new List<Opportunity>();
        List<Opportunity> updateList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
 
        List<Key_Product_Goals__c> InsertKey_Product_Goals = new list<Key_Product_Goals__c>();
        List<Key_Product_Goals__c> UpdateKey_Product_Goals = new list<Key_Product_Goals__c>();
 
        String target_Source = 'SalesTarget';
        if (isEng == true) {
            target_Source = 'EngTarget';
        }
 
        Savepoint sp = Database.setSavepoint();
        try {
            Map<String, Decimal> oppAmount = new Map<String, Decimal>();
            Map<String,String> saveAmountCategoryMap = new Map<String,String>();
 
            System.debug(dataBeans+'6666');
            
            for (Integer d = 0; d < dataBeans.size(); d++) {
                DataBean db = dataBeans[d];
                System.debug(db+'7777');
                // 寄存数据比例值是否变化
                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 (ImportantProductCategory__c pc : pcList){
                        // 数据检索Key
                        String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + sTargetDay;
                        
                        Opportunity opp = new Opportunity();
                        // 每月数据赋值                       
                        if (oppsMap.containskey(key)) {
                            opp = oppsMap.get(key);
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            if (opp.Proportion__c != proportion.get(depName)[i]) {
                                proportionChanged = true;
                                break;
                             }
                        }
                    }
                    if (proportionChanged) {
                        break;
                    }
                }
                if (db.isChanged == '0' && !proportionChanged) {
                    continue;
                }
                User u = new User();
                if (db.opportunity.Owner_System__c == null) {
                    if (isDelete(db) == false) {
                        continue;
                    }
                }
                // 一年分成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);
                    // 按金额分类顺序处理
                    for (Integer j = 0; j < pcList.size(); j++){
                        ImportantProductCategory__c pc = pcList[j];
                        // 数据检索Key
                        String key = db.opportunity.SAP_Province__c + '_' + target_category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + sTagetDay;
                        
                        Opportunity newopp = new Opportunity();
                        // 每月数据赋值                        
                        if (oppsMap.containskey(key)) {
                            newopp = oppsMap.get(key);
                            if (db.opportunity.Owner_System__c == null || db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                                deleteList.add(newopp);
                                continue;
                            }
                            newopp.OwnerId = db.opportunity.Owner_System__c;
                            newopp.Owner_System__c = db.opportunity.Owner_System__c;
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            newopp.Proportion__c = proportion.get(depName)[i];
                            newopp.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            oppAmount.put(newopp.Id, db.amount[j].Num_Of_OPD__c);
                            updateList.add(newopp);
 
                            if (!saveAmountCategoryMap.containskey(pc.importantProductGoaIName__c + '_' + pc.depName__c)) {
                                saveAmountCategoryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.importantProductGoaIName__c + '_' + pc.depName__c);
                            }
                        } else {
                            if (db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                                continue;
                            }
                            newopp.Name = db.opportunity.SAP_Province__c + ' ' + pc.importantProductGoaIName__c;
                            
                            newopp.StageName = '目標';
                            newopp.OwnerId = db.opportunity.Owner_System__c;
                            // トリガをスルーのため、ここでやります
                            newopp.Owner_System__c = db.opportunity.Owner_System__c;
                            
                            newopp.Opportunity_Category__c = pc.depName__c;
                            String depName = (pc.depName__c == null || pc.depName__c == '') ? 'GI' : pc.depName__c;
                            newopp.Proportion__c = proportion.get(depName)[i];
                            newopp.CloseDate = tagetDay;
                            newopp.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            newopp.Target_category__c = target_category;
                            newopp.Important_Key_product_category__c = pc.importantProductGoaIName__c;
                            newopp.SAP_Province__c = db.opportunity.SAP_Province__c;
                            newopp.RecordTypeId = rt.Id;
                            newopp.OCM_Target_period__c = currentPeriod;
                            newopp.Target_Source__c = target_Source;
                            
                            insertList.add(newopp);
                            
                            if (!saveAmountCategoryMap.containskey(pc.importantProductGoaIName__c + '_' + pc.depName__c)) {
                                saveAmountCategoryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pc.importantProductGoaIName__c + '_' + pc.depName__c);
                            }
                        }
                    }
                }
                // 数据库限制小于10000条
                if (insertList.size() + updateList.size() + deleteList.size() >= 4000) {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '操作数据量过大,截止至' + db.opportunity.SAP_Province__c + '的数据操作完成,之后的数据请再次输入并保存。'));
                    break;
                }
            }
            // トリガをスルー
            StaticParameter.EscapeOpportunityBefUpdTrigger = true;
            StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
            StaticParameter.EscapeSyncOpportunityTrigger = true;
            StaticParameter.EscapeNFM001Trigger = true;
            StaticParameter.EscapeNFM001AgencyContractTrigger = true;
            StaticParameter.EscapeNFM007Trigger = true;
    
            // 更新数据库
            if (insertList.size() > 0) {
                insert insertList;
                
                Map<String,PricebookEntry> pricebookEntryMap = new Map<String,PricebookEntry>();
                // 製品を検索
                for (ImportantProductCategory__c pc : pcList){
                    String dep = pc.depName__c;
                    Map<String, String> impmap = getImpProductMap(dep);
                    String soql = 'select Id from PricebookEntry' + 
                                  ' where IsActive = true ' + 
                                  '   and Product2.' + impProductApiMap.get(pc.importantProductGoaIName__c) + ' = true';
                    if (dep != null && dep.length() > 0) {
                          soql += '   and Product2.' + impmap.get(pc.importantProductGoaIName__c) + ' = true';
                    }
                          soql += '   and CurrencyIsoCode = \'CNY\' limit 1';
                    System.debug(soql);
                    
                    List<PricebookEntry> pbes = Database.query(soql);
                    if (pbes.size() < 1) {
                        Database.rollback(sp);
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '在产品(价格表)里找不到' + pc.importantProductGoaIName__c + '-' + dep));
                        return false;
                    }
                    
                    pricebookEntryMap.put(pc.importantProductGoaIName__c + '_' + pc.depName__c, pbes[0]);  
                }
                // 商談新規後、商談商品作成
                List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
                for (Opportunity insOpp : [select Id, Amount,Num_Of_OPD__c,Important_Key_product_category__c,Opportunity_Category__c,Objective__c from Opportunity where Id in :insertList]) {
                    oli.add(new OpportunityLineItem(
                        OpportunityId = insOpp.Id,
                        PricebookEntryId = pricebookEntryMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c).Id,
                        Quantity = isCntMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c) == false ? 1 : insOpp.Num_Of_OPD__c,
                        UnitPrice = isCntMap.get(insOpp.Important_Key_product_category__c + '_' + insOpp.Opportunity_Category__c) == false ? insOpp.Num_Of_OPD__c : 0
                    ));
                }
                insert oli;
            }
            
            if (updateList.size() > 0) {
                update updateList;
                
                List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
                for (OpportunityLineItem updOli : [select Id, OpportunityId, Opportunity.Important_Key_product_category__c, Opportunity.Opportunity_Category__c from OpportunityLineItem where OpportunityId in : updateList]) {
                    updOli.UnitPrice = isCntMap.get(updOli.Opportunity.Important_Key_product_category__c + '_' + updOli.Opportunity.Opportunity_Category__c) == false ? oppAmount.get(updOli.OpportunityId) : 0;
                    updOli.Quantity = isCntMap.get(updOli.Opportunity.Important_Key_product_category__c + '_' + updOli.Opportunity.Opportunity_Category__c) == false ? 1 : oppAmount.get(updOli.OpportunityId);
                    oli.add(updOli);
                }
                update oli;
            }
            
            if (deleteList.size() > 0) delete deleteList;
            
            return true;
            
        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage() + '|' + e.getLineNumber()));
            return false;
        }
    }*/
 
    public Pagereference UpdateBtn() {
        system.debug('=====UpdateBtn-1');
        boolean rs = saveLogic();
        setBean(iYear);
        Database.executeBatch(new SetProductTargetBatch(), 10);
        if (rs) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, '反映到目标成功'));
        }
        return null;
    }
 
    private Boolean saveLogic() {
        List<Opportunity> insertList = new List<Opportunity>();
        List<Opportunity> updateList = new List<Opportunity>();
        List<Opportunity> deleteList = new List<Opportunity>();
        Savepoint sp = Database.setSavepoint();
        try {
            List<Key_Product_Goals__c> InsertKey_Product_Goals = new list<Key_Product_Goals__c>();
            List<Key_Product_Goals__c> UpdateKey_Product_Goals = new list<Key_Product_Goals__c>();
            // 只处理当前本部数据
 
            String target_Source = 'SalesTarget';
            if (isEng == true) {
                target_Source = 'EngTarget';
            }
 
            for (Integer d = 0; d < dataBeans.size(); d++){
                DataBean db = dataBeans[d];
                system.debug('db+++++++ ' + db);
                if(String.isBlank(db.Opportunity.Owner_System__c))continue;
                for (Integer j = 0; j < amountCategory.size(); j++) {
                    ImportantProductCategory__c pc = pcList[j];
                        // 数据检索Key
                    String key = db.Opportunity.SAP_Province__c + '_' + target_category + '_' +
                                 pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + target_Source;
                    //     // String key = db.Opportunity.SAP_Province__c + '_' + amountCategory[j];
                    // if(String.isNotBlank(db.Opportunity.Owner_System__c)){
                    if(Key_Product_GoalsMap.containsKey(key)) {
                        //临时表已经有了
                        Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                        if(Key_Product_Goal.Num_Of_OPD__c == db.amount[j].Num_Of_OPD__c) {
                            continue;
                        }else {
                            Key_Product_Goal.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                            Key_Product_Goal.Department__c = db.department;
                            Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                            Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                            Key_Product_Goal.iYear__c = iYear;
                            Key_Product_Goal.Is_Processing__c = true;
                            Key_Product_Goal.Target_Source__c = target_Source;
                            UpdateKey_Product_Goals.add(Key_Product_Goal);
                        }
                    }else {
                        if (db.amount[j].Num_Of_OPD__c == null || db.amount[j].Num_Of_OPD__c == 0) {
                            continue;
                        }
                        Key_Product_Goals__c Key_Product_Goal = new Key_Product_Goals__c();
                        Key_Product_Goal.key__c = key;
                        Key_Product_Goal.Num_Of_OPD__c = db.amount[j].Num_Of_OPD__c;
                        Key_Product_Goal.Department__c = db.department;
                        Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                        Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                        Key_Product_Goal.iYear__c = iYear;
                        Key_Product_Goal.Is_Processing__c = true;
                        Key_Product_Goal.Target_Source__c = target_Source;
                        InsertKey_Product_Goals.add(Key_Product_Goal);
                    }
 
                    // }else {
                    //     if(Key_Product_GoalsMap.containsKey(key)) {
                    //         //临时表已经有了
                    //         Key_Product_Goals__c Key_Product_Goal = Key_Product_GoalsMap.get(key);
                    //         if(Key_Product_Goal.Num_Of_OPD__c == db.amount[j].Num_Of_OPD__c) {
                    //             continue;
                    //         }else {  
                    //             Key_Product_Goal.Num_Of_OPD__c = 0;
                    //             Key_Product_Goal.Department__c = db.department;
                    //             Key_Product_Goal.SAP_Province__c = db.Opportunity.SAP_Province__c;
                    //             Key_Product_Goal.Owner_System__c = db.Opportunity.Owner_System__c;
                    //             Key_Product_Goal.iYear__c = iYear;
                    //             Key_Product_Goal.Is_Processing__c = true;
                    //             UpdateKey_Product_Goals.add(Key_Product_Goal);
                    //         }
                    //     }
                    //     continue;
                    // }
                }
            }
 
            if(InsertKey_Product_Goals.size() > 0) {
                insert InsertKey_Product_Goals;
            }
            if(UpdateKey_Product_Goals.size() > 0) {
                update UpdateKey_Product_Goals;
            }
            return true;
        } catch (Exception e) {
            system.debug('=====saveLogic-e' + e.getMessage());
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getLineNumber() + ':' + e.getMessage()));
            return false;
        }
    }
    
    private Map<String, String> getImpProductMap(String ac) {
        Map<String, String> impmap = new Map<String, String> {
            '重点产品01' => 'Important_Rroduct_1' + ac +'__c',
            '重点产品02' => 'Important_Rroduct_2' + ac +'__c',
            '重点产品03' => 'Important_Rroduct_3' + ac +'__c',
            '重点产品04' => 'Important_Rroduct_4' + ac +'__c',
            '重点产品05' => 'Important_Rroduct_5' + ac +'__c',
            '重点产品06' => 'Important_Rroduct_6' + ac +'__c',
            '重点产品07' => 'Important_Rroduct_7' + ac +'__c',
            '重点产品08' => 'Important_Rroduct_8' + ac +'__c',
            '重点产品09' => 'Important_Rroduct_9' + ac +'__c',
            '重点产品10' => 'Important_Rroduct_10' + ac +'__c',
            '重点产品11' => 'Important_Rroduct_11' + ac +'__c',
            '重点产品12' => 'Important_Rroduct_12' + ac +'__c',
            '重点产品13' => 'Important_Rroduct_13' + ac +'__c',
            '重点产品14' => 'Important_Rroduct_14' + ac +'__c',
            '重点产品15' => 'Important_Rroduct_15' + ac +'__c',
            '重点产品16' => 'Important_Rroduct_16' + ac +'__c',
            '重点产品17' => 'Important_Rroduct_17' + ac +'__c',
            '重点产品18' => 'Important_Rroduct_18' + ac +'__c',
            '重点产品19' => 'Important_Rroduct_19' + ac +'__c',
            '重点产品20' => 'Important_Rroduct_20' + ac +'__c',
            '重点产品21' => 'Important_Rroduct_21' + ac +'__c',
            '重点产品22' => 'Important_Rroduct_22' + ac +'__c',
            '重点产品23' => 'Important_Rroduct_23' + ac +'__c',
            '重点产品24' => 'Important_Rroduct_24' + ac +'__c',
            '重点产品25' => 'Important_Rroduct_25' + ac +'__c',
            '重点产品26' => 'Important_Rroduct_26' + ac +'__c',
            '重点产品27' => 'Important_Rroduct_27' + ac +'__c',
            '重点产品28' => 'Important_Rroduct_28' + ac +'__c',
            '重点产品29' => 'Important_Rroduct_29' + ac +'__c',
            '重点产品30' => 'Important_Rroduct_30' + ac +'__c',
            '重点产品31' => 'Important_Rroduct_31' + ac +'__c'
        };
        return impmap;
    }
    
    // 数据类
    class DataBean {
        // 担当者信息
        public Opportunity opportunity { get; set; }
        // 总金额,画面用
        public Opportunity[] amount { get; set; }
        // 本部表示用
        public String department { get; private set; }
        // 是否变化 0:无 1:有
        public String isChanged { get; set; }
        //CHAN-BDQBLX  20210204 ljh start  导出用name
        public String ownername { get; private set; }
        //CHAN-BDQBLX  20210204 ljh end
        // 构造方法
        DataBean(String salesDpt, String province, Map<String, Opportunity> oppMap, Integer iYear, String category, Map<String, AggregateResult> oliMap, List<ImportantProductCategory__c> pcList2) {
            this.opportunity = new Opportunity();
            this.amount = new List<Opportunity>();
            this.opportunity.SAP_Province__c = province;
            this.department = salesDpt;
            this.isChanged = '0';
 
            // 按金额分类,查找数据,并设值
            //List<ImportantProductCategory__c> pcList2 = [select depName__c,importantProductGoaIName__c,commodityCode__c,commodityName__c,if_Quantity__c,sort__c from ImportantProductCategory__c order by sort__c];
            for (Integer i = 0; i < pcList2.size(); i++) {
                ImportantProductCategory__c pc = pcList2[i];  
                Opportunity a = new Opportunity();
                a.Opportunity_Category__c = pc.depName__c;
                Decimal amountSum = 0.0;
                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 = this.opportunity.SAP_Province__c + '_' + category + '_' + pc.importantProductGoaIName__c + '_' + pc.depName__c + '_' + strY + '-' + strM + '-01';
                    if (oppMap.containskey(key)) {
                        if (oppMap.get(key).Owner_System__c != null) {
                            this.opportunity.Owner_System__c = oppMap.get(key).Owner_System__c;
                        }
                        //a.Amount = oppMap.get(key).Amount;
                        if (isCntMap.get(pc.importantProductGoaIName__c + '_' + pc.depName__c) == false) {
                            amountSum += oliMap.get(oppMap.get(key).Id).get('sum_o') == null ? 0 : (Decimal) oliMap.get(oppMap.get(key).Id).get('sum_o');
                        } else {
                            amountSum += oliMap.get(oppMap.get(key).Id).get('sum_n') == null ? 0 : (Decimal) oliMap.get(oppMap.get(key).Id).get('sum_n');
                        }
                    }
                }
                
                if (amountSum > 0) {
                    if (category == '重点产品目标(金额)') {
                        amountSum = amountSum.setScale(2);
                        a.Amount = amountSum;
                    } else {
                        amountSum = amountSum.round();
                        a.Num_Of_OPD__c = amountSum;
                    }
                }  
                  
                this.amount.add(a);
            }
        }
    }
}