ApiService.java 11.3 KB
package com.erry.iclear.dateInterface.service;

import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.erry.iclear.dateInterface.api.request.Mawb;
import com.erry.iclear.dateInterface.api.request.MawbDetail;
import com.erry.iclear.dateInterface.api.request.ReceiptMessage;
import com.erry.iclear.dateInterface.api.response.TokenResult;
import com.erry.iclear.dateInterface.common.Constants;
import com.erry.iclear.dateInterface.entity.ChmConsignment;
import com.erry.iclear.dateInterface.entity.ChmConsignmentDetail;
import com.erry.iclear.dateInterface.entity.DeclearTask;
import com.erry.iclear.dateInterface.repository.ChmConsignmentRepository;
import com.erry.iclear.dateInterface.repository.DeclearTaskRepository;
import com.erry.iclear.dateInterface.repository.ReceiptMessageRepository;
import com.erry.iclear.dateInterface.util.JsonToJava;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;

/**
 * 调用API接口Service
 * mt
 * 2021年7月28日17:04:27
 */
@Service
@Slf4j
@Transactional(rollbackOn = Exception.class)
public class ApiService {
    @Value("${api.token-info.username}")
    String username;
    @Value("${api.token-info.password}")
    String password;
    @Value("${api.address.token-url}")
    String tokenUrl;
    @Value("${api.address.refresh-token-url}")
    String refreshTokenUrl;
    @Value("${api.address.customs-url}")
    String customsUrl;
    @Value("${api.address.complete-msg-url}")
    String completeMsgUrl;

    @Autowired
    ReceiptMessageRepository receiptMessageRepository;

    @Autowired
    DeclearTaskRepository declearTaskRepository;

    @Autowired
    ChmConsignmentRepository consignmentRepository;

    @Autowired
    ChmConsignmentService consignmentService;

    @Autowired
    ChmConsignmentDetailService consignmentDetailService;

    /**
     * 获取token信息
     * @return
     * @throws Exception
     */
    public TokenResult getToken() throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("username", this.username);
        map.put("password", this.password);
        HttpConfig config = HttpConfig.custom()
                .url(this.tokenUrl)
                .map(map)
                .encoding("utf-8");
        String tokenJson = HttpClientUtil.post(config);
        TokenResult tokenResult = JsonToJava.parseJson(tokenJson,TokenResult.class);
        return tokenResult;
    }

    /**
     * 刷新token
     * @param token
     * @throws Exception
     */
    public void refreshToken(String token) throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("token", token);
        HttpConfig config = HttpConfig.custom()
                .url(this.refreshTokenUrl)
                .map(map)
                .encoding("utf-8");
        HttpClientUtil.post(config);
    }

    /**
     * 传输海关回执数据
     * @param token
     * @throws Exception
     */
    public void pushCustoms(String token){
        //获取海关回执数据
        List<ReceiptMessage> receiptMessageList = this.receiptMessageRepository.findReceiptMessageList();
        this.sendCustoms(token,receiptMessageList);
    }

    /**
     * 将海关回执数据发送至西门子
     * @param token
     * @param receiptMessageList
     */
    public void sendCustoms(String token ,List<ReceiptMessage> receiptMessageList){
        Header[] headers = HttpHeader.custom()
                .other("Content-Type", "application/json")
                .other("Authorization", token)
                .build();
        List<DeclearTask> declearTaskList = new ArrayList<DeclearTask>();
        receiptMessageList.forEach(d->{
            DeclearTask declearTask = new DeclearTask();
            try {
                //设置ID
                declearTask.setChmsignmentId(BigDecimal.valueOf(d.getId()));
                //推送时间
                declearTask.setPushTime(new Date());
                String objJson = JsonToJava.toJson(d);
                //推送海关回执数据
                HttpConfig config = HttpConfig.custom()
                        .headers(headers)
                        .url(this.customsUrl)
                        .encoding("utf-8")
                        .json(objJson);
                String json = HttpClientUtil.post(config);
                //接口响应时间
                declearTask.setResponseTime(new Date());
                TokenResult tokenResult = JsonToJava.parseJson(json,TokenResult.class);
                if(tokenResult.getErrorcode().equals(Constants.ApiResponseKeys.SUCCESS)){
                    //推送成功,记录推送状态
                    declearTask.setResponseResults(tokenResult.getErrorcode());
                    declearTask.setResponseContent(tokenResult.getErrormessage());
                    declearTaskList.add(declearTask);
                }else if(tokenResult.getErrorcode().equals(Constants.ApiResponseKeys.KEY_10004)){
                    //如果凭证失效,则刷新凭证
                    refreshToken(token);
                }else{
                    //推送失败,记录推送状态
                    declearTask.setResponseResults(tokenResult.getErrorcode());
                    declearTask.setResponseContent(tokenResult.getErrormessage());
                    declearTaskList.add(declearTask);
                    log.info("海关回执推送失败,推送相应码为:"+tokenResult.getErrorcode() + ",推送ID为:" + d.getId());
                }
            }catch(Exception ex){
                //接口响应时间
                declearTask.setResponseTime(new Date());
                declearTask.setResponseResults("99999");
                declearTask.setResponseContent(ex.getMessage());
                declearTaskList.add(declearTask);
                ex.printStackTrace();
            }
        });
        declearTaskList.forEach(declearTask -> {
            //将已经推送完成的回执信息状态修改
            this.receiptMessageRepository.updateDeclearTaskStatus(declearTask.getPushTime(),
                    declearTask.getResponseTime(),
                    declearTask.getResponseResults(),
                    declearTask.getResponseContent(),
                    "2",
                    declearTask.getChmsignmentId().longValue());
        });
    }

    /**
     * 传输完整报文数据
     * @param token
     * @throws Exception
     */
    public void pushMawb(String token){
        try{
            /****************将Export对象转换成西门子交互实体对象****************/
            //查询需要推送数据
            List<Mawb> mawbList = new ArrayList<Mawb>();
            List<DeclearTask> declearTaskList = this.declearTaskRepository.findDeclearTask();
            declearTaskList.forEach(declearTask -> {
                Long consignmentId = declearTask.getChmsignmentId().longValue();
                //查询需要推送运单数据,并且转换
                ChmConsignment consignment = this.consignmentRepository.findChmConsignmentById(consignmentId);
                Mawb mawb = this.consignmentService.convertToChmConsignment(consignment);
                //获取需要推送运单数据,并且转换
                if(consignment.getChmConsignmentDetailList() != null){
                    List<MawbDetail> mawbDetailList = new ArrayList<MawbDetail>();
                    for(int i = 0 ; i < consignment.getChmConsignmentDetailList().size() ; i++){
                        ChmConsignmentDetail detail = consignment.getChmConsignmentDetailList().get(i);
                        MawbDetail mawbDetail = this.consignmentDetailService.convertToChmConsignmentDetail(detail, String.valueOf((i + 1)));
                        mawbDetailList.add(mawbDetail);
                    }
                    mawb.setMawbDetailList(mawbDetailList);
                }
                mawbList.add(mawb);
            });
            this.sendMawb(token,mawbList);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 将完整报文发送至西门子
     * @param token
     * @param mawbList
     */
    public void sendMawb(String token ,List<Mawb> mawbList){
        Header[] headers = HttpHeader.custom()
                .other("Content-Type", "application/json")
                .other("Authorization", token)
                .build();
        List<DeclearTask> declearTaskList = new ArrayList<DeclearTask>();
        mawbList.forEach(d->{
            DeclearTask declearTask = new DeclearTask();
            try {
                //设置ID
                declearTask.setChmsignmentId(BigDecimal.valueOf(d.getId()));
                //推送时间
                declearTask.setPushTime(new Date());
                String objJson = JsonToJava.toJson(d);
                //推送海关回执数据
                HttpConfig config = HttpConfig.custom()
                        .headers(headers)
                        .url(this.completeMsgUrl)
                        .encoding("utf-8")
                        .json(objJson);
                String json = HttpClientUtil.post(config);
                //接口响应时间
                declearTask.setResponseTime(new Date());
                TokenResult tokenResult = JsonToJava.parseJson(json,TokenResult.class);
                if(tokenResult.getErrorcode().equals(Constants.ApiResponseKeys.SUCCESS)){
                    //推送成功,记录推送状态
                    declearTask.setResponseResults(tokenResult.getErrorcode());
                    declearTask.setResponseContent(tokenResult.getErrormessage());
                    declearTaskList.add(declearTask);
                }else if(tokenResult.getErrorcode().equals(Constants.ApiResponseKeys.KEY_10004)){
                    //如果凭证失效,则刷新凭证
                    refreshToken(token);
                }else{
                    //推送失败,记录推送状态
                    declearTask.setResponseResults(tokenResult.getErrorcode());
                    declearTask.setResponseContent(tokenResult.getErrormessage());
                    declearTaskList.add(declearTask);
                    log.info("完整报关单推送失败,推送相应码为:"+tokenResult.getErrorcode() + ",推送ID为:" + d.getId());
                }
            }catch(Exception ex){
                //接口响应时间
                declearTask.setResponseTime(new Date());
                declearTask.setResponseResults("99999");
                declearTask.setResponseContent(ex.getMessage());
                declearTaskList.add(declearTask);
                ex.printStackTrace();
            }
        });
        declearTaskList.forEach(declearTask -> {
            //将已经推送完成的报关单状态修改
            this.receiptMessageRepository.updateDeclearTaskStatus(declearTask.getPushTime(),
                    declearTask.getResponseTime(),
                    declearTask.getResponseResults(),
                    declearTask.getResponseContent(),
                    "1",
                    declearTask.getChmsignmentId().longValue());
        });
    }
}