xinyb
9 天以前 b7ef4bb09e69ba27c29ea06a7f348f753c530a44
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
package com.yc.open.baiwang.controller;
 
import com.alibaba.fastjson.JSON;
import com.baiwang.open.client.BWRestClient;
import com.baiwang.open.client.IBWClient;
import com.baiwang.open.entity.request.OutputBasicinfoGetAuthQrCodeRequest;
import com.baiwang.open.entity.request.OutputFormatQueryQdInvoiceRequest;
import com.baiwang.open.entity.request.OutputInvoiceIssueRequest;
import com.baiwang.open.entity.request.OutputRedinvoiceAddRequest;
import com.baiwang.open.entity.request.node.OutputFormatQueryQdInvoiceData;
import com.baiwang.open.entity.response.OutputBasicinfoGetAuthQrCodeResponse;
import com.baiwang.open.entity.response.OutputFormatQueryQdInvoiceResponse;
import com.baiwang.open.entity.response.OutputInvoiceIssueResponse;
import com.baiwang.open.entity.response.OutputRedinvoiceAddResponse;
import com.baiwang.open.exception.BWOpenException;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.attachment.AttachmentEntity;
import com.yc.entity.attachment.AttachmentWhereEntity;
import com.yc.exception.ApplicationException;
import com.yc.exception.CallBackMessage;
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.open.baiwang.schedule.BaiwangThread;
import com.yc.open.baiwang.schedule.QueryThread;
import com.yc.open.baiwang.service.BaiwangIfc;
import com.yc.open.baiwang.service.QueryEntiy;
import com.yc.open.baiwang.utils.TokenUtils;
import com.yc.open.controller.BaseController;
import com.yc.open.mutual.schedule.GateEntity;
import com.yc.sdk.weixincp.util.UploadFiles;
import com.yc.service.build.type.T_22_Ifc;
import com.yc.service.upload.AttachmentIfc;
import com.yc.utils.SessionKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
/**
 * 百望云相关功能
 */
@RestController
@Slf4j
public class BaiwangController extends BaseController {
    @Autowired
    T_22_Ifc t22ifc;
    @Autowired
    AttachmentIfc attachmentIfc;
 
    @Autowired
    BaiwangIfc baiwangIfc;
    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;
 
    /**
     * 刷新刷脸认证二维码
     *
     * @return
     */
    @RequestMapping(value = "/baiwang/refreshQrcode.do")
    public @ResponseBody Object refreshQrcode(@RequestBody FaceSwipingEntry entry, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            IBWClient client = new BWRestClient(TokenUtils.url, TokenUtils.appKey, TokenUtils.appSecret); // 初始化一个客户端
            String token = TokenUtils.getToken();
            request.setAttribute("doccode", entry.getDoccode());
            request.setAttribute("invoiceType", entry.getInvoiceType());
            request.setAttribute("funclinkFormid",entry.getFunclinkFormid());
            confrimFace(client, entry.getTaxNo(), token, request, response, callBackMessage);
            callBackMessage.sendSuccessMessage("刷新成功");
            return callBackMessage.toJSONObject();
        } catch (BWOpenException e) {
            callBackMessage.sendErrorMessage(e.getSubMessage());
            return callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(ex.getMessage());
            return callBackMessage.toJSONObject();
        }
    }
 
    /**
     * 刷脸认证回调状态
     *
     * @return
     */
    @RequestMapping(value = "/baiwang/confirmFaceSwiping.do")
    public @ResponseBody Object confirmFaceSwiping(@RequestBody FaceSwipingEntry entry, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            IBWClient client = new BWRestClient(TokenUtils.url, TokenUtils.appKey, TokenUtils.appSecret); // 初始化一个客户端
            String token = TokenUtils.getToken();
            //循环执行是否扫码成功,成功则发通知关闭页面并且提示成功
            threadPoolExecutor.execute(new BaiwangThread(client, token, entry, request.getSession()));
            callBackMessage.sendSuccessMessage("成功");
            return  callBackMessage.toJSONObject();
        } catch (BWOpenException e) {
            callBackMessage.sendErrorMessage(e.getSubMessage());
            return  callBackMessage.toJSONObject();
        } catch (Exception ex) {
            callBackMessage.sendErrorMessage(ex.getMessage());
            return  callBackMessage.toJSONObject();
        }
    }
 
    /**
     * 生成电子发票
     *
     * @return
     */
    @RequestMapping(value = "/baiwang/einvoice.do")
    public @ResponseBody Object einvoice(HttpServletRequest request, HttpServletResponse response) {
 
        CallBackMessage callBackMessage = new CallBackMessage();
        IBWClient client = null;
        String token = null;
        String funclinkFormid = null;
        GateEntity entity = new GateEntity();
        String taxNo = null;
        Integer invoiceType = -1;//发票类型
        try {
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
            Map<String, String> map = null;
            try {
                SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());//切换数据源
                map = t22ifc.getParamMap(request);
            } catch (Exception e) {
                e.printStackTrace();
               callBackMessage.sendErrorMessage(this.getErrorMsg(e));
                return callBackMessage.toJSONObject();
            } finally {
                SpObserver.setDBtoInstance();
            }
            String docCode = null;//单号
            if (map != null) {
                docCode = map.get("doccode");
                if (StringUtils.isNotBlank(map.get("invoiceType"))) {
                    invoiceType = new Integer(map.get("invoiceType"));
                } else {
                    callBackMessage.sendErrorMessage("invoiceType参数没传");
                    return callBackMessage.toJSONObject();
                }
            }
            if (docCode == null) {
                callBackMessage.sendErrorMessage("docCode参数没传");
                return callBackMessage.toJSONObject();
            }
            funclinkFormid = request.getParameter("formid");//功能链接功能号,返回给前端在刷脸成功后自动再次执行使用
            entity.setFormid(150504);
            entity.setDbid(dataSourceEntity.getDbId() + "");
            entity.setDocCode(docCode);
            entity.setUserCode(request.getSession().getAttribute(SessionKey.USERCODE) + "");
            entity.setUserName(request.getSession().getAttribute(SessionKey.USER_NAME) + "");
            client = new BWRestClient(TokenUtils.url, TokenUtils.appKey, TokenUtils.appSecret); // 初始化一个客户端
            token = TokenUtils.getToken();
            if (invoiceType == 0) {
                //--蓝字发票
                OutputInvoiceIssueRequest einvoiceInfo = this.baiwangIfc.getEinvoiceInfo(entity);
                //---------star 测试代码------
          /* int  errorCode = -1008;
            client = new BWRestClient(TokenUtils.url, TokenUtils.appKey, TokenUtils.appSecret); // 初始化一个客户端
            token = TokenUtils.getToken();
            request.setAttribute("doccode", entity.getDocCode());
            request.setAttribute("invoiceType", invoiceType);
            request.setAttribute("funclinkFormid",funclinkFormid);
            confrimFace(client, einvoiceInfo.getTaxNo(), token, request, response, callBackMessage);
        callBackMessage.sendErrorMessage("errorMsg", errorCode);
        return callBackMessage.toJSONObject();*/
                //-----end---------
                if (einvoiceInfo != null) {
                    taxNo = einvoiceInfo.getTaxNo();
                    OutputInvoiceIssueResponse issue = client.outputInvoice().issue(einvoiceInfo, token);
                    //log.info("msg:" + JSON.toJSONString(issue));
                    //1--记录日志
                    baiwangIfc.sendLog(entity, issue);
                    if (!issue.isSuccess()) {
                        //失败
                        callBackMessage.sendErrorMessage(issue.getErrorResponse().getSubMessage());
                        return callBackMessage.toJSONObject();
                    }
                    //-------成功
                    //2---更新状态
                    baiwangIfc.updateStatus(entity, issue);
                    threadPoolExecutor.execute(new QueryThread(client, token, issue.getResponse().getSuccess().get(0).getInvoiceNo(), einvoiceInfo.getTaxNo(), entity, request.getSession(), this, baiwangIfc));
                    callBackMessage.setData("成功");
                    callBackMessage.setMemo("生成成功!正在下载电子发票,稍候手动刷新界面显示发票附件").sendSuccessMessageByDefault();
                    return callBackMessage.toJSONObject();
                } else {
                    callBackMessage.sendErrorMessage(String.format("%s没有所需要推送数据", entity.getDocCode()));
                    return callBackMessage.toJSONObject();
                }
            } else {
                //--红字发票
                OutputRedinvoiceAddRequest readEinvoiceInfo = this.baiwangIfc.getRedEinvoiceInfo(entity);
                if (readEinvoiceInfo != null) {
                    taxNo = readEinvoiceInfo.getTaxNo();
                    OutputRedinvoiceAddResponse issue = client.outputRedinvoice().add(readEinvoiceInfo, token);
                    //log.info("msg:" + JSON.toJSONString(issue));
                    if (!issue.isSuccess()) {
                        //失败
                        callBackMessage.sendErrorMessage(issue.getErrorResponse().getSubMessage());
                        return callBackMessage.toJSONObject();
                    }
                    //-------成功
                    //1--记录日志
                    baiwangIfc.sendRedLog(entity, issue);
                    //2---更新状态
                    baiwangIfc.updateRedStatus(entity, issue);
                    threadPoolExecutor.execute(new QueryThread(client, token, issue.getResponse().get(0).getRedInvoiceNo(), readEinvoiceInfo.getTaxNo(), entity, request.getSession(), this, baiwangIfc));
                    callBackMessage.setData("成功");
                    callBackMessage.setMemo("生成成功!正在下载电子发票,稍候手动刷新界面显示发票附件").sendSuccessMessageByDefault();
                    return callBackMessage.toJSONObject();
                } else {
                    callBackMessage.sendErrorMessage(String.format("%s没有所需要推送数据", entity.getDocCode()));
                    return callBackMessage.toJSONObject();
                }
            }
        } catch (BWOpenException ex) {
            ex.printStackTrace();
            int errorCode = -1;
            String errorMsg = ex.getSubMessage();
            if ("70031".equals(ex.getSubCode())) {
                //未登录或登录失效
                Map map = new HashMap();
                map.put("url", TokenUtils.LOGIN_URL);
                errorCode = -1007;
                errorMsg = "【" + ex.getSubMessage() + "】点击【确定】按钮在弹出的百望云平台重新登录,成功后关闭弹窗然后再次执行生成电子发票操作";
                callBackMessage.setInfo(map);
            } else if ("70045".equals(ex.getSubCode())) {
                //刷脸验证,生成二维码图片给税局APP扫码
                errorCode = -1008;
                request.setAttribute("doccode", entity.getDocCode());
                request.setAttribute("invoiceType", invoiceType);
                request.setAttribute("funclinkFormid", funclinkFormid);
                confrimFace(client, taxNo, token, request, response, callBackMessage);
            }
            callBackMessage.sendErrorMessage(errorMsg, errorCode);
            return callBackMessage.toJSONObject();
        } catch (Exception e) {
            callBackMessage.sendErrorMessage(e.getMessage());
            return callBackMessage.toJSONObject();
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
    @RequestMapping(value = "/baiwang/download.do")
    private @ResponseBody Object downLoadEinvoiceFile(HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        try {
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(request);
            SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());//切换数据源
            Map<String, String> map = null;
            try {
                map = t22ifc.getParamMap(request);
            } catch (Exception e) {
                e.printStackTrace();
                callBackMessage.sendErrorMessage(this.getErrorMsg(e));
                return callBackMessage.toJSONObject();
            }
            String docCode = null;//单号
            Integer invoiceType = -1;//发票类型
            if (map != null) {
                docCode = map.get("doccode");
                invoiceType = new Integer(map.get("invoiceType"));
            }
            if (docCode == null) {
                callBackMessage.sendErrorMessage("单号不能为空");
                return callBackMessage.toJSONObject();
            }
            if (invoiceType == -1) {
                callBackMessage.sendErrorMessage("发票类型不能为空");
                return callBackMessage.toJSONObject();
            }
            GateEntity entity = new GateEntity();
            entity.setDocCode(docCode);
            QueryEntiy einvoiceInfo = this.baiwangIfc.getEinvoiceInfo(docCode, invoiceType);
            if (einvoiceInfo != null) {
                BWRestClient client = new BWRestClient(TokenUtils.url, TokenUtils.appKey, TokenUtils.appSecret); // 初始化一个客户端
                String token = TokenUtils.getToken();
                OutputFormatQueryQdInvoiceRequest query = new OutputFormatQueryQdInvoiceRequest();
                OutputFormatQueryQdInvoiceData data = new OutputFormatQueryQdInvoiceData();
                data.setInvoiceNo(einvoiceInfo.getInvoiceNo());
                query.setData(data);
                query.setTaxNo(einvoiceInfo.getTaxNo());
                OutputFormatQueryQdInvoiceResponse outputFormatQueryQdInvoiceResponse = client.outputFormat().queryQdInvoice(query,
                        token);
                log.info("msg:" + JSON.toJSONString(outputFormatQueryQdInvoiceResponse));
                if (!outputFormatQueryQdInvoiceResponse.isSuccess()) {
                    //失败
                    throw new ApplicationException(outputFormatQueryQdInvoiceResponse.getErrorResponse().getSubMessage());
 
                }
                String fielid = "InvoiceFile";//附件字段
                String unid = this.saveAttachment(outputFormatQueryQdInvoiceResponse, entity, fielid);
                //--更新状态
                baiwangIfc.updateByAttachment(entity, unid, fielid, outputFormatQueryQdInvoiceResponse, einvoiceInfo.getInvoiceNo());
            }
            callBackMessage.setData("成功");
            callBackMessage.setMemo("刷新成功").sendSuccessMessageByDefault();
            return callBackMessage.toJSONObject();
        }catch (Exception ex) {
            ex.printStackTrace();
            callBackMessage.sendErrorMessage(ex.getMessage());
            return callBackMessage.toJSONObject();
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
    private void confrimFace(IBWClient client, String taxNo, String token, HttpServletRequest request, HttpServletResponse response, CallBackMessage callBackMessage) {
        try {
            OutputBasicinfoGetAuthQrCodeRequest qrCodeRequest = new OutputBasicinfoGetAuthQrCodeRequest();
            qrCodeRequest.setTaxNo(taxNo);
            OutputBasicinfoGetAuthQrCodeResponse qrCodeResponse = client.outputBasicinfo().getAuthQrCode(qrCodeRequest, token);
            if (!qrCodeResponse.isSuccess()) {
                //失败
                callBackMessage.sendErrorMessage(qrCodeResponse.getErrorResponse().getSubMessage());
                this.print(response, JSON.toJSONString(callBackMessage.toJSONObject()));
                return;
            }
            Map map = new HashMap();
            map.put("qrCode", qrCodeResponse.getResponse().get(0).getQrCode());
            map.put("authId", qrCodeResponse.getResponse().get(0).getAuthId());
            map.put("taxNo", taxNo);
            map.put("doccode", request.getAttribute("doccode"));//传多一个单号,实现扫码成功自动执行生成电子发票操作
            map.put("invoiceType", request.getAttribute("invoiceType"));//发票类型
            map.put("funclinkFormid", request.getAttribute("funclinkFormid"));//传多一个功能链接功能号
            map.put("taxUserName", request.getSession().getAttribute(SessionKey.USER_TELE_PHONE) + "");//要用手机号做扫码认证,不能用账号
            callBackMessage.setInfo(map);
        }catch (Exception e){
            callBackMessage.sendErrorMessage(e.getMessage());
            this.print(response, JSON.toJSONString(callBackMessage.toJSONObject()));
        }
    }
 
    private byte[] getAttachment(String imageHostUrl) throws IOException {
        URL url = new URL(imageHostUrl);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据,以二进制封装得到数据,具有通用性
        byte[] bytes = FileCopyUtils.copyToByteArray(inStream);
        conn.disconnect();
        return bytes;
    }
 
    public String saveAttachment(OutputFormatQueryQdInvoiceResponse response, GateEntity entity, String fieldId) throws Exception {
        if (response == null)
            return "";
        String uuid = UUID.randomUUID().toString().toUpperCase();
        String seqString = "";
        //存在附件需要处理
        String url = response.getResponse().getPdfUrl();
        //源文件二进制
        AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
        byte[] orgBinaryimages = getAttachment(url);
        com.yc.entity.attachment.AttachmentEntity attachmentEntity = new AttachmentEntity();
        attachmentEntity.setUnid(uuid);
        attachmentEntity.setSeq(null);
        attachmentEntity.setFormId(entity.getFormid());
        attachmentEntity.setDoccode(entity.getDocCode());
        attachmentEntity.setFieldId(fieldId);
        attachmentEntity.setRowId(null);
        attachmentEntity.setPhysicalFile(null);
        attachmentEntity.setPhysicalPath(null);
        attachmentEntity.setOriginalFileName(entity.getDocCode() + ".pdf");
        attachmentEntity.setFileType("pdf");
        attachmentEntity.setFileSize(new Long(orgBinaryimages.length));
        attachmentEntity.setAuthorCode(entity.getUserCode());
        attachmentEntity.setAuthorName(entity.getUserName());
        UploadFiles uploadFiles = new UploadFiles();
        uploadFiles.setOrgBinaryimages(orgBinaryimages);
        uploadFiles.setSmallBinaryimages(orgBinaryimages);
        AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment(uploadFiles, attachmentEntity, "2");
        seqString += attachmentWhereEntity.getSeq();
        return uuid + ";" + seqString;
    }
}