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
global class OCMManagementProvinceBatch implements Database.Batchable<sObject> {
 
    String query;
    String targetId;
    private BatchIF_Log__c iflog;
    private String errStr;
    private Map<String, OCM_Management_Province__c> mpMap; 
    
    List<String> oppList = new List<String>(); 
    global OCMManagementProvinceBatch() {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }
 
    global OCMManagementProvinceBatch(String oppId) {
        targetId = oppId;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start2\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }
    global OCMManagementProvinceBatch(List<String> oppList) {
        this.oppList = oppList;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'OCMManagementProvinceBatch';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OCMManagementProvinceBatch start3\n';
        iflog.ErrorLog__c = '';
        insert iflog;
    }  
 
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        // 只更新询价【状态1】为"询价"和"注残"的
        List<String> stageList = new List<String>();
        stageList.add('引合');
        stageList.add('注残');
        //办事处ET/ENG担当共享 you 20230222 只更新“注残”,“出荷”,“完了” 
        stageList.add('出荷');
        stageList.add('完了');
        
        // 取得询价对象
        //询价:计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 start
        // query = 'select id, Opportunity_Category__c, Owner.Dept__c, Sales_assistant_name_text__c, Account.OCM_Management_Province_HP__c, OCM_man_province__c, OCM_man_province_no_eng__c from Opportunity ';
        query = 'select id,Ownerid, Opportunity_Category__c, Owner.Dept__c, Sales_assistant_name_text__c, Account.OCM_Management_Province_HP__c, OCM_man_province__c, OCM_man_province_new__c,StageName,SAP_Province__c,Opp_order_Type__c from Opportunity ';
        //询价:计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 end
        
        query += ' where StageName = :stageList ';
        
        if (targetId != null && targetId != '') {
            query += ' and id = :targetId ';
        }
        if(null!= oppList && oppList.size()>0){
            query += ' and Id In :oppList ';
         }
         query += ' order by OCM_man_province_new__c';
        return Database.getQueryLocator(query);
    }
 
       global void execute(Database.BatchableContext BC, List<Opportunity> oppList) {
           // 取得OCM管理省信息
           List<OCM_Management_Province__c> mpList = [select id, Name, GI_assistant__c, SP_assistant__c, Energy_assistant__c,Province__c,ET_DataWindow__c,ET_BusinessWindow__c,ET_Assistant1__c,ET_Assistant2__c,ENG_DataWindow__c,ENG_BusinessWindow__c,ENG_Assistant1__c,ENG_Assistant2__c,ENGShareOpp__c,ETShareOpp__c,ENG_Flag__c,ET_Flag__c from OCM_Management_Province__c];
           mpMap = new Map<String, OCM_Management_Province__c>();
        Map<String, OCM_Management_Province__c> mpshareoppMap = new Map<String, OCM_Management_Province__c>();
           for (OCM_Management_Province__c mp : mpList) {
               mpMap.put(mp.Name, mp);
            mpshareoppMap.put(mp.Province__c, mp);
           }
           // 判断需要更新的询价
           List<Opportunity> updList = new List<Opportunity>();
           for (Opportunity opp : oppList) {
            //询价:计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 start
               // OCM_Management_Province__c mp = mpMap.get(opp.OCM_man_province_no_eng__c);
               OCM_Management_Province__c mp = mpMap.get(opp.OCM_man_province_new__c);
            //询价:计算到全国的询价助理逻辑修正 DB202312159622 cjw 20231212 end
               Id uid = null;
            if(opp.StageName == '注残' || opp.StageName == '引合'){
                if (opp.OCM_man_province__c == '能量') {
                    uid = mp == null ? null : mp.Energy_assistant__c;
                } else if (opp.Opportunity_Category__c == 'GI' || opp.Opportunity_Category__c == 'BF' || opp.Opportunity_Category__c == 'ET') {
                    uid = mp == null ? null : mp.GI_assistant__c;
                } else {
                    uid = mp == null ? null : mp.SP_assistant__c;
                }
                // 询价助理是否有变化
                if (opp.Sales_assistant_name_text__c != uid) {
                    Opportunity upd = new Opportunity(
                        id = opp.Id,
                        Sales_assistant_name_text__c = uid
                    );
                    updList.add(upd);
                }
            }
               
           }
           // 询价更新
           if (updList.size() > 0) {
            Database.SaveResult[] lsr = Database.update(updList, false);
            for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                Database.SaveResult sr = lsr[tIdx];
                if (!sr.isSuccess()) {
                    Database.Error emsg = sr.getErrors()[0];
                    System.debug('=====Error Opp: ' + updList[tIdx].Id + ' msg: ' + emsg);
                }
            }
        }
        //询价共享 根据 省和耗材分类
        //删掉原来的ET/ENG担当,插入新的担当  
        Map<Id, Opportunity>  otmMap = new Map<Id, Opportunity>();
        //新增的询价共享
        List<OpportunityShare> addoppsharlist =new List<OpportunityShare>();
        //需要删除的原担当的共享
        List<OpportunityShare> deleteoppsharlist =new List<OpportunityShare>();
        Set<String> mpset = new Set<String>(); //询价对应省 如贵州 用来限制TMS和IMS得查询数据量(因为处理ims数据时超50001)
        
        for (Opportunity opp : oppList) {
            
            if(opp.StageName == '注残' || opp.StageName == '出荷'|| opp.StageName == '完了'){
                if(null!=opp.Opp_order_Type__c && ''!=opp.Opp_order_Type__c){
                    otmMap.put(opp.Id,opp);  //oppid 担当id
                    mpset.add(opp.OCM_man_province_new__c);
                }
                
            }
        }
        if(!otmMap.isEmpty()){
            // 手动共享不能删除原来已经存在的共享  
            List<OpportunityShare> osList = [select id,UserOrGroupId,OpportunityId from OpportunityShare where OpportunityId in :otmMap.keySet() and OpportunityAccessLevel = 'read' and rowCause = 'Manual'];
            
            Map<Id,list<String>> allmap = new Map<Id,list<String>>();
            
            for(OpportunityShare oppshare : osList){
                list<String> allFSEUserIDList = new list<String>();
                if(otmMap.containsKey(oppshare.OpportunityId)){
                    OCM_Management_Province__c mpshareopp = mpshareoppMap.get(otmMap.get(oppshare.OpportunityId).SAP_Province__c);
                    if(otmMap.get(oppshare.OpportunityId).Opp_order_Type__c=='ET'){
                        if(null!=mpshareopp && null!=mpshareopp.ETShareOpp__c && mpshareopp.ET_Flag__c==true){
                            String[] etnames = mpshareopp.ETShareOpp__c.split(',');
                            for(String etname : etnames) {
                                if (String.isNotBlank(etname)) {
                                allFSEUserIDList.add(etname);//需要删掉的et用户id
                                }
                            }
                        }
                        
                    }else{
                        if(null!=mpshareopp && null!=mpshareopp.ENGShareOpp__c && mpshareopp.ENG_Flag__c==true){
                            String[] engnames = mpshareopp.ENGShareOpp__c.split(',');
                            for(String engname : engnames) {
                                if (String.isNotBlank(engname)) {
                                allFSEUserIDList.add(engname);//需要删掉的eng用户id
                                }
                            }
                        }
                        
                    }
                }
                allmap.put(oppshare.OpportunityId,allFSEUserIDList); 
            }
            
            //List<OpportunityShare> oppsharlist =new List<OpportunityShare>();
            Map<String ,OpportunityShare> oppsharlist =new Map<String ,OpportunityShare>();
            system.debug('====opp==='+otmMap.size());
            for(Id oppid:otmMap.keySet()){
                 Opportunity oppobj=otmMap.get(oppid);//获得当前对象
                 if (mpshareoppMap.containsKey(oppobj.SAP_Province__c)) {
                   OCM_Management_Province__c mpshareopp = mpshareoppMap.get(oppobj.SAP_Province__c);
                   if(null!=oppobj.Opp_order_Type__c && ''!= oppobj.Opp_order_Type__c){
                    //String aa='005C8000000219sIAA,00GC80000001UR7MAM,00GC80000000ujBMAQ,00GC80000002F7pMAE,00GC80000000uj8MAA,00GC80000001USsMAM,00GC80000000v68MAA,00GC80000000ujKMAQ,00GC80000000upQMAQ';
                      if(oppobj.Opp_order_Type__c=='ET'){
                        if(mpshareopp.ET_Flag__c==true || System.Label.OCMManagementProvinceBatchFlag == '0'){
                            if(null!=mpshareopp && null!=mpshareopp.ET_DataWindow__c && !''.equals(mpshareopp.ET_DataWindow__c) && oppobj.Ownerid !=mpshareopp.ET_DataWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ET_DataWindow__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ET_DataWindow__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ET_BusinessWindow__c && !''.equals(mpshareopp.ET_BusinessWindow__c) && oppobj.Ownerid !=mpshareopp.ET_BusinessWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ET_BusinessWindow__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ET_BusinessWindow__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ET_Assistant1__c && !''.equals(mpshareopp.ET_Assistant1__c) && oppobj.Ownerid !=mpshareopp.ET_Assistant1__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ET_Assistant1__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ET_Assistant1__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ET_Assistant2__c && !''.equals(mpshareopp.ET_Assistant2__c) && oppobj.Ownerid !=mpshareopp.ET_Assistant2__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ET_Assistant2__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ET_Assistant2__c;
                                oppsharlist.put(key,oppshare);
                            }
                            system.debug('ET==='+oppsharlist);  
                        }
                        
                      }else{//SP,ENG 
                        if(mpshareopp.ENG_Flag__c==true ||  System.Label.OCMManagementProvinceBatchFlag == '0'){
                            if(null!=mpshareopp && null!=mpshareopp.ENG_DataWindow__c && !''.equals(mpshareopp.ENG_DataWindow__c) && oppobj.Ownerid !=mpshareopp.ENG_DataWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ENG_DataWindow__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ENG_DataWindow__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ENG_BusinessWindow__c && !''.equals(mpshareopp.ENG_BusinessWindow__c) && oppobj.Ownerid !=mpshareopp.ENG_BusinessWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ENG_BusinessWindow__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ENG_BusinessWindow__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ENG_Assistant1__c && !''.equals(mpshareopp.ENG_Assistant1__c) && oppobj.Ownerid !=mpshareopp.ENG_Assistant1__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ENG_Assistant1__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ENG_Assistant1__c;
                                oppsharlist.put(key,oppshare);
                            }
                            if(null!=mpshareopp && null!=mpshareopp.ENG_Assistant2__c && !''.equals(mpshareopp.ENG_Assistant2__c) && oppobj.Ownerid !=mpshareopp.ENG_Assistant2__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = oppid,
                                UserOrGroupId = mpshareopp.ENG_Assistant2__c,
                                RowCause = 'Manual',
                                OpportunityAccessLevel = 'read');
                                //oppsharlist.add(oppshare);
                                String key = oppid +'-' + mpshareopp.ENG_Assistant2__c;
                                oppsharlist.put(key,oppshare);
                            }
                            system.debug('SP==='+oppsharlist);  
                        }
                        
                      }
                   }
                }    
                
            }    
            List<OpportunityShare> DeshList = new List<OpportunityShare>();
            for ( Opportunityshare ops : osList) {
                if (allmap.containsKey(ops.OpportunityId)&& allmap.get(ops.OpportunityId).contains(ops.UserOrGroupId)) {
                    DeshList.add(ops);
                }
            } 
            //询价共享先注释
            // try{        
            //     if (DeshList.size() > 0) delete DeshList;    
            //     system.debug('插入的共享==='+oppsharlist.size()+'=========='+oppsharlist);
            //     if(null!=oppsharlist && oppsharlist.size()>0){
            //         //insert oppsharlist;
            //         insert oppsharlist.values();
            //     }
            // }catch(Exception e){
            //         errStr = e.getMessage()+'\n';
            //         errStr += '询价插入的共享==='+oppsharlist.size()+oppsharlist+'\n';
            //         errStr += '需要删除的共享==='+DeshList.size()+'\n'+DeshList+'\n';
            //         errStr += e.getLineNumber()+'\n';
            // }    
        }
        system.debug('省份信息'+mpset);    
 
    }
 
    global void finish(Database.BatchableContext BC) {
        String tmp = '';
        if (String.isNotBlank(errStr)) {
            tmp = errStr;
        }
        iflog.Log__c += 'OCMManagementProvinceBatch finish()\n';
        iflog.Log__c += '\n OCMManagementProvinceBatch end';
 
        tmp += iflog.ErrorLog__c;
        if (tmp.length() > 60000) {
          tmp = tmp.substring(0, 60000);
          tmp += ' ...have more lines...';
          iflog.ErrorLog__c = tmp;
        }
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 60000) {
          tmp2 = tmp2.substring(0, 60000);
          tmp2 += ' ...have more lines...';
          iflog.Log__c = tmp2;
        }
        
        update iflog;
        if(null!=mpMap && System.Label.OCMManagementProvinceBatchFlag == '1'){  
          Database.executeBatch(new OCMTOTMSShareUserBatch(mpMap),200);
        }
    }
    
    
        
 
}