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
//implements Queueable
public with sharing class NFM511Controller implements Queueable {
 
    public static String status;
    public static String logstr;
 
    private static final String LOG_TYPE = 'NFM511';
 
    // public class NFM511 {
    //     public Gedatas Gedatas;
    // }
 
    public class AllData {
        public Integer code;
        public ZCData data;
        public String message;
    }
 
    public class ZCData {
        public Integer total;
        public Integer current;
        public Integer size;
        public Boolean hitCount;
        public Integer pages;
        public Boolean optimizeCountSql;
        public Boolean searchCount;
        public ListItem[] records;
        public Object[] orders;
    }
 
    public class ListItem {
        public String sfdcCode;        //上传编码
        public String bid;             //标讯 id
        public String title;           //标题
        public String projectNo;       //项目编号
        public String originalUrl;     //原文链接
        public String tenderee;        //归一招标单位
        public String province;        //省
        public String city;            //市
        public String district;        //区
        public String supplier;        //归一中标单位
        public String contractObject;  //标的名称
        public String brand;           //归一品牌名称
        public String brandType;       //品牌类型
        public String speci;           // 归一型号
        public String noticeType ;     //公告类型
        public String progress ;       // 中标进度
        public String oneClass ;       //大类
        public String twoClass ;       //产品线
        public String threeClass ;     //细分品种
        public String hostIf ;         //是否包含主机
        public String fundingSource ;  //资金来源
        public String url ;            //众成链接
 
        public Integer winningDetailId;  //标注结果 id
        public Integer bidQuantity;  //补全数量
        public Decimal bidUnitPrice;  //补全单价
        public Decimal bidTotalPrice ; //补全总价
        public String projectTotalPrice ;  //项目总价
 
        public String createTime ; 
        public String modifyTime ; 
        public String publishTime ; //中标日期
 
        public String projectJudgeId ; //项目id-大包标识 20240105 lt add  project_judge_id
    }
 
    // 日志rowData的Id
    public String logId; 
 
    //取众成数据的开始/结束时间
    public static String startTime; 
    public static String endTime; 
 
    // 无参的构造方法
    public NFM511Controller() {
    }
 
    // 包含Id的构造方法
    public NFM511Controller(String rowdataId) {
        this.logId = rowdataId;
    }
 
    // 包含 开始时间/结束时间 的构造方法
    // 文本格式 'yyyy-MM-dd'
    // public NFM511Controller(String startTime1,String endTime1) {
    //     startTime = startTime1;
    //     endTime = endTime1;
    // }
 
    // 最大值为3,用来作为判断错误的条件(重发三次)
    public static Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
 
    // 开始执行
    public void execute(QueueableContext context) {
 
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmmss');
 
        //1 创建日志
        BatchIF_Log__c rowData = new BatchIF_Log__c();
        System.debug('lt123--logId:'+this.logId);
        if (String.isBlank(this.logId)) {
            rowData.Type__c = 'NFM511';
            rowData.RowDataFlg__c = true;
            rowData.MessageGroupNumber__c = nowStr;
            rowData.retry_cnt__c = 0;
            insert rowData;
        } else {
            rowData.Id = this.logId;
        }
        
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM511';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        insert iflog;
        System.debug('rowDataId: ' + rowData.Id);
        System.debug('iflogId: ' + iflog.Id);
 
        //2 执行接口请求
        NFM511Controller.sendRequest(rowData.Id, iflog.Id);
        
    }
 
    @Future(callout=true)
    public static void sendRequest(String rowDataId, String iflogId) {
        BatchIF_Log__c rowData = [select Id, Name, Log__c, ErrorLog__c, MessageGroupNumber__c, retry_cnt__c
                                  from BatchIF_Log__c where id = :rowDataId ];
        BatchIF_Log__c iflog = [select Id, Name, Log__c, ErrorLog__c, MessageGroupNumber__c, retry_cnt__c
                                  from BatchIF_Log__c where id = :iflogId ];
        BatchIF_Transfer__c tokeninfo = null;
        BatchIF_Transfer__c indexinfo = null;
        Boolean updateToken = false; // 是否更新token
        Boolean doFuture = false; // 是否执行511future
 
        //startTime/EndTime  转送表  start
        // BatchIF_Log__c iflog1 = new BatchIF_Log__c();
        // iflog1.Type__c = 'NFM511Time';
        // iflog1.Log__c = 'timeCtroller start\n';
        // iflog1.ErrorLog__c = '';
        // insert iflog1;
 
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [
                                select Table__c,
                                       Column__c,
                                       External_value__c,
                                       Internal_value__c
                                from BatchIF_Transfer__c
                                where Dropped_Flag__c = false
                                and Table__c = 'NFM511'];
        for (BatchIF_Transfer__c t : transferList) {
        transferMap.put(t.Column__c, t.Internal_value__c);
        }
        System.debug('20231009---transferMap:'+transferMap);
        System.debug('20231009---startTime表:'+transferMap.get('StartTime'));
        System.debug('20231009---EndTime表:'+transferMap.get('EndTime'));
 
        startTime = transferMap.get('StartTime');
        endTime = transferMap.get('EndTime');
        // if (!transferMap.containsKey('StartTime') || !transferMap.containsKey('EndTime')) { 
        //     iflog1.ErrorLog__c += '请检查转送表\n';
        // }
        //startTime/EndTime  转送表  end
 
        Datetime nowDT = Datetime.now();
        Long nowM = Long.valueOf(nowDT.format('yyyyMMddHHmm'));
        Long nowD = Long.valueOf(nowDT.format('yyyyMMdd'));
        System.debug('20231009---startTime:'+startTime);
        System.debug('20231009---endTime:'+endTime);
        String yestoday = String.isBlank(startTime) ? system.now().format('yyyy-MM-dd') + '%2000:00:00' : startTime + '%2000:00:00';
        String totoday = String.isBlank(endTime) ? system.now().format('yyyy-MM-dd') + '%2023:59:55' : endTime + '%2023:59:55';
        System.debug('20231009---yestoday:'+yestoday);
        System.debug('20231009---totoday:'+totoday);
 
        try {
            //1 获得token和当前任务页数数据
            String token;
            String loginNo;
            String systemId;
            String pindex;
            tokeninfo = [Select ID, NFM501_Token__c,LastModifiedDate FROM BatchIF_Transfer__c
                                        Where Table__c = 'NFM511Token' limit 1];
            indexinfo = [Select ID, Internal_Value__c,LastModifiedDate FROM BatchIF_Transfer__c
                                        Where Table__c = 'NFM511GainEndTime' limit 1];
            Long lastModM = tokeninfo == null ? 0 : Long.valueOf(tokeninfo.LastModifiedDate.format('yyyyMMddHHmm'));
            Long lastModD = tokeninfo == null ? 0 : Long.valueOf(tokeninfo.LastModifiedDate.format('yyyyMMdd'));
            String[] tokeninfos = null;
            //2 判断是否要取新token
            if (nowM - lastModM > 8) {
                String tokennew = getZCToken();
                System.debug('token: ' + tokennew);
                Map<String, Object> tr = (Map<String, Object>) JSON.deserializeUntyped(tokennew);
                System.debug('test20231007---tr: ' + tr);
                Map<String, Object> retdata = (Map<String, Object>) tr.get('data');
                String strtokeninfo = (String) retdata.get('access_token') + ';' + retdata.get('loginNo') + ';' + retdata.get('systemId');
                if (tokeninfo == null) {
                    tokeninfo = new BatchIF_Transfer__c();
                    tokeninfo.Table__c = 'NFM511Token';
                }
                tokeninfo.NFM501_Token__c = strtokeninfo;
                updateToken = true;
                tokeninfos = strtokeninfo.split(';');
            } else {
                tokeninfos = tokeninfo.NFM501_Token__c.split(';');
            }
            token = tokeninfos[0];
            loginNo = tokeninfos[1];
            systemId = tokeninfos[2];
            pindex = indexinfo == null || String.isBlank(indexinfo.Internal_Value__c) || (nowD - lastModD > 0) ? '1' : indexinfo.Internal_Value__c;
            // token和页数信息写入执行日志
            iflog.Log__c = 'token: ' + token + '\n';
            iflog.Log__c += 'loginNo: ' + loginNo + '\n';
            iflog.Log__c += 'systemId: ' + systemId + '\n';
            iflog.Log__c += 'pindex: ' + pindex + '\n';
            // 获取数据日志
            String datalog = sendToZCRet(token, loginNo, systemId, pindex, yestoday,totoday);
            rowData.Log__c = datalog;
            AllData metaData = (AllData) JSON.deserializeStrict(datalog, AllData.class);
 
            if (metaData.code == 200) {
                doFuture = true;
                if (metaData.data.pages > Integer.valueOf(pindex)) {
                    System.enqueueJob(new NFM511Controller());
                }
            }
 
            System.debug('lt123-rowData.id:'+rowData.id);
            System.debug('lt123-iflog.id:'+iflog.id);
            // NFM511FutureController.main(rowData.id,iflog.Id,false);
            // System.enqueueJob(new NFM511FutureController(rowData.id),1);
 
            if (indexinfo == null) {
                indexinfo = new BatchIF_Transfer__c();
                indexinfo.Table__c = 'NFM511GainEndTime';
            }
            indexinfo.Internal_Value__c = String.valueOf(Integer.valueOf(pindex) + 1);
        } catch (Exception ex) {
            // Database.rollback(sp);
            System.debug('ex.getlinenumber()------'+ex.getlinenumber());
            iflog.ErrorLog__c = '511抛出异常:' + ex.getMessage() + '\n'
                                + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            rowData.retry_cnt__c += 1;
 
            System.debug('lt123-rowData.retry_cnt__c:'+rowData.retry_cnt__c);
            
            if (rowData.retry_cnt__c == batch_retry_max_cnt) {
                rowData.ErrorLog__c = '511抛出异常:' +
                        ex.getMessage() + '\n' + ex.getStackTraceString()
                        + '\n' + 
                        '错误次数已经超过自动收信设定的最大次数,请手动收信';
            } else {
                // rowData.ErrorLog__c = 'error:' + ex.getMessage() + '\n' + ex.getStackTraceString()
                // + '\n' ;
                System.enqueueJob(new NFM511Controller(rowData.Id), 1);
            }
        } finally {
            update iflog;
            update rowData;
            if (updateToken) {
                upsert tokeninfo;
            }
            upsert indexinfo;
            if (doFuture) {
                NFM511FutureController.main(rowData.id,iflog.Id,false);
            }
        }
    }
 
    // 获得众成token
    public static String getZCToken() {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        HTTPResponse res;
        String resb;
        // System.debug('endpoint: ' + NFMUtil.NFM511_TOKEN_ENDPOINT);
        // System.debug('username: ' + NFMUtil.NFM511_USERNAME);
        // System.debug('password: ' + NFMUtil.NFM511_PASSWORD);
        String url = NFMUtil.NFM511_TOKEN_ENDPOINT;
        url += '?username=' + NFMUtil.NFM511_USERNAME;
        url += '&password=' + NFMUtil.NFM511_PASSWORD;
        System.debug('token url: ' + url);
        req.setMethod('GET');
        req.setEndpoint(url);
        // req.setEndpoint(NFMUtil.NFM511_TOKEN_ENDPOINT);
        // req.setHeader('username', NFMUtil.NFM511_USERNAME);
        // req.setHeader('password', NFMUtil.NFM511_PASSWORD);
        // req.setBody('');
        res = http.send(req);
        resb = res.getBody();
        System.debug('511 get token:' + resb);
 
        return resb;
    }
 
    // 获得众成数据
    public static String sendToZCRet(String token, String loginNo, String systemId, string pageIndex, String updStart, String updEnd) {
 
        // 发送接口
        Http http2 = new Http();
        HttpRequest req2 = new HttpRequest();
        HTTPResponse res2;
        String resb2;
 
        String url = NFMUtil.NFM511_DATA_ENDPOINT;
        url += '?loginNo=' + loginNo;
        url += '&systemId=' + systemId;
        url += '&pageIndex=' + pageIndex;
        url += '&pageSize=10';
        url += '&updateTimeStart=' + updStart;
        url += '&updateTimeEnd=' + updEnd;
        // url += '&updateTimeStart=2023-10-09%2017:44:00';
        // url += '&updateTimeEnd=2023-10-09%2017:45:00';
 
        System.debug('20231009---url:'+url);
 
        req2.setTimeout(110000);
        req2.setMethod('GET');
        req2.setEndpoint(url);
        // req2.setEndpoint(NFMUtil.NFM511_DATA_ENDPOINT);
        req2.setHeader('Authorization', 'Bearer ' + token);
        // req2.setHeader('loginNo', loginNo);
        // req2.setHeader('systemId', systemId);
        // req2.setHeader('Content-Type', 'application/json');
        // req2.setHeader('pageIndex', pageIndex);
        // req2.setHeader('pageSize', '20');
        // req2.setHeader('updateTimeStart', updStart); // 格式 '2023-04-01 00:00:00'
        // req2.setHeader('updateTimeEnd', updEnd);
        // req2.setBody('');
        System.debug('20231009---res2---1:'+res2);
        res2 = http2.send(req2);
        System.debug('20231009---res2--2:'+res2);
        resb2 = res2.getBody();
        System.debug('20231009---resb2:'+resb2);
        return resb2;
    }
   
}