package com.dxhy.erp.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.ConfigurerInfo;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.RespStatusEnum;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.exception.OrderReceiveException;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.Base64Encoding;
import com.dxhy.common.utils.GzipUtils;
import com.dxhy.common.utils.TripleDesUtil;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.entity.V5.CheckResult;
import com.dxhy.erp.entity.V5.DxhyInterfaceRequest;
import com.dxhy.erp.entity.V5.DxhyInterfaceResponse;
import com.dxhy.erp.model.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.*;
import com.dxhy.erp.utils.HmacSHA1Util;
import com.dxhy.erp.utils.JsonUtils;
import com.dxhy.erp.utils.OpenApiUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaMethodTooLong")
@RestController
@RequestMapping("/invoice")
@Slf4j
public class InterfaceController extends AbstractController {

    private static final String LOGGER_MSG = "(进项平台对外接口)";

    @Resource
    private AuthStatusService authStatusService;
    @Resource
    private GatherService gatherService;
    @Resource
    private SignDataService signDataService;
    @Resource
    private CheckIpBlocAppidService checkIpBlocAppidService;
    @Resource
    private CheckDataService checkDataService;
    @Resource
    private OrderService orderService;
    @Resource
    private InvoiceAuthService invoiceAuthService;
    @Resource
    private ApplyStatService applyStatService;
    @Resource
    private TaxCurrentService taxCurrentService;
    @Resource
    private InvoicePoolService invoicePoolService;
    @Resource
    private MryxInterfaceService mryxInterfaceService;
    @Resource
    private CustomspcService customspcService;
    @Resource
    private IFEService feService;
    @Resource
    private IYaBaoService yaBaoService;
    @Resource
    private TDxRecordInvoiceOutService tDxRecordInvoiceOutService;
    @Resource
    private RiskStatisticsService riskStatisticsService;
    @Resource
    SysDeptDao sysDeptDao;
    @Resource
    TDxInvoiceReimburseService tDxInvoiceReimburseService;
    @Resource
    private DeclareService declareService;
    @Value("${erp.checkIp}")
    private boolean checkIp;
    @Resource
    private IReceiptOutService iReceiptOutService;
    @Resource
    private VoucherRecordService voucherRecordService;
    @Resource
    private BaseIReceiptInvoiceService baseIReceiptInvoiceService;
    @Value("${erp.ipUrl}")
    private String ipUrl;
    @Resource
    private RequestRecordService requestRecordService;

    /**
     * 
     * @description 统一SDK对外接口版本V5
     * @author Allen 
     * @updateTime 2021/12/20 16:34
     * @param 
     */
    @ApiOperation(value = "业务系统接口入口", notes = "业务系统接口入口")
    @RequestMapping(path = "/jxpt/api/{version}/{interfaceName}", method = {RequestMethod.POST, RequestMethod.GET})
    public String jxptApiV5(HttpServletRequest request, HttpServletResponse response,
                            @PathVariable("version") String version,
                            @PathVariable("interfaceName") String interfaceName,
                            @ApiParam(name = "requestParam", value = "业务报文", required = true) @RequestBody String content) {
        log.info("{} SDK对外接口请求，version：{}，interfaceName:{},content:{},请求url={}",LOGGER_MSG,version,interfaceName,content,request.getRequestURL().toString());
        DxhyInterfaceResponse dxhyInterfaceResponse = new DxhyInterfaceResponse(RespStatusEnum.FAIL2);
        long startTime = System.currentTimeMillis();
        try {
            request.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            DxhyInterfaceRequest dxhyInterfaceRequest = JsonUtils.getInstance().parseObject(content, DxhyInterfaceRequest.class);
            if (ObjectUtil.isNull(dxhyInterfaceRequest)) {
                log.info("请求入参为空");
                throw new OrderReceiveException(RespStatusEnum.FAIL1.getCode(), RespStatusEnum.FAIL1.getDescribe());
            }

            /**
             * 校验接口入参是否为空
             */
            CheckResult result = checkInterfaceParamV5(version, interfaceName, dxhyInterfaceRequest.getSecretId(), dxhyInterfaceRequest.getDataExchangeId(),
                    dxhyInterfaceRequest.getSignature(), dxhyInterfaceRequest.getEncryptCode(), dxhyInterfaceRequest.getZipCode(), dxhyInterfaceRequest.getContent());
            if (!ConfigurerInfo.SUCCSSCODE.equals(result.getCode())) {
                log.info("请求参数有误");
                throw new OrderReceiveException(result.getCode(), result.getMsg());
            }
            long begin1 = System.currentTimeMillis();

            String secretKey = getSecretKey(dxhyInterfaceRequest.getSecretId());

            /**
             * 鉴权
             */
            result = authV5(version+"/"+interfaceName,request, dxhyInterfaceRequest,secretKey);
            long end1 = System.currentTimeMillis();
            log.debug("{}鉴权耗时{}毫秒", LOGGER_MSG, end1 - begin1);
            if (!ConfigurerInfo.SUCCSSCODE.equals(result.getCode())) {
                log.error("{},鉴权未通过", LOGGER_MSG);
                throw new OrderReceiveException(result.getCode(), result.getMsg());
            }

            //解密
            String commonDecrypt2 = commonDecrypt(dxhyInterfaceRequest.getZipCode(), dxhyInterfaceRequest.getEncryptCode(), dxhyInterfaceRequest.getContent(), secretKey);
            log.debug("{}解密日志：{}", LOGGER_MSG, commonDecrypt2);
            String returnJsonString = "";
            long start = System.currentTimeMillis();

            //组织老接口对象，兼容新接口
            GlobalInfo globalInfo = getGlobalInfo(dxhyInterfaceRequest.getDataExchangeId(),interfaceName);
            //组织鉴权对象
            Authorize authorize = getAuthorize(dxhyInterfaceRequest.getSignature(),dxhyInterfaceRequest.getSecretId());
            //组织全局报文
            Map<String, String> requestParam = getRequestParam(globalInfo,authorize,commonDecrypt2);
            InterfaceCode interfaceCode = new InterfaceCode();
            //调用业务处理逻辑方法
            if (ConfigurerInfo.INTERFACE_VERSION_V5.equals(version)) {
                returnJsonString = routeRequet(globalInfo, requestParam, request, response, authorize);
                //处理老版本接口出参
                interfaceCode = builResponseMessage(returnJsonString);
            } else {
                log.error("{},不支持的版本号", LOGGER_MSG);
                throw new OrderReceiveException(RespStatusEnum.CHECK_VERSION_ERROR.getCode(), RespStatusEnum.CHECK_VERSION_ERROR.getDescribe());
            }
            long end = System.currentTimeMillis();
            log.debug("{}接口:{},请求耗时:{}-------返回", LOGGER_MSG, interfaceName, end - start,returnJsonString);
            if (interfaceCode.getReturnStateInfo().getReturnCode().equals("0000")) {
                /**
                 * 加密响应消息
                 */
                returnJsonString = Base64Encoding.decodeToString(interfaceCode.getData());
                String data = "";
                if(!StrUtil.isBlank(returnJsonString)){
                    data = commonEncrypt(dxhyInterfaceRequest.getZipCode(), dxhyInterfaceRequest.getEncryptCode(), returnJsonString,secretKey);
                }
                dxhyInterfaceResponse.setReturnCode(RespStatusEnum.SUCCESS.getCode());
                dxhyInterfaceResponse.setReturnMessage(RespStatusEnum.SUCCESS1.getDescribe());
                dxhyInterfaceResponse.setDataExchangeId(dxhyInterfaceRequest.getDataExchangeId());
                dxhyInterfaceResponse.setEncryptCode(dxhyInterfaceRequest.getEncryptCode());
                dxhyInterfaceResponse.setZipCode(dxhyInterfaceRequest.getZipCode());
                dxhyInterfaceResponse.setContent(data);
            }else {
                dxhyInterfaceResponse.setReturnCode(interfaceCode.getReturnStateInfo().getReturnCode());
                dxhyInterfaceResponse.setReturnMessage(interfaceCode.getReturnStateInfo().getReturnMessage());
            }

        } catch (OrderReceiveException e) {
            log.error("{},接口请求数据出现异常,异常原因为:{}", LOGGER_MSG, e);
            dxhyInterfaceResponse.setReturnCode(e.getCode());
            dxhyInterfaceResponse.setReturnMessage(e.getMessage());

        } catch (Exception e) {
            log.error("{},接口请求数据出现异常,异常原因为:{}", LOGGER_MSG, e);
            dxhyInterfaceResponse.setReturnCode(RespStatusEnum.FAIL.getCode());
            dxhyInterfaceResponse.setReturnMessage(RespStatusEnum.FAIL.getDescribe());
        }
        String result = JsonUtils.getInstance().toJsonString(dxhyInterfaceResponse);
        long endTime = System.currentTimeMillis();
        log.info("{},接口:{}调用成功,耗时:{},返回数据:{}", LOGGER_MSG, interfaceName, endTime - startTime, result);
        return result;
    }

    private String getSecretKey(String secretId) throws OrderReceiveException {
        //获取secretkey
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String secretKey = sysDeptDao.getSecretKey(secretId);
        log.debug("{}通过secretId:{},获取的对应的secretKey:{}", LOGGER_MSG, secretId, secretKey);
        if (StringUtils.isBlank(secretKey)) {
            log.error("{},获取的对应的secretKey失败", LOGGER_MSG);
            throw new OrderReceiveException(RespStatusEnum.CHECK_GET_SECRETKEY_ERROR.getCode(), RespStatusEnum.CHECK_GET_SECRETKEY_ERROR.getDescribe());
        }
        return secretKey;
    }


    private InterfaceCode builResponseMessage(String returnJsonString) {
        InterfaceCode interfaceCode = JsonUtils.getInstance().fromJson(returnJsonString, InterfaceCode.class);
//        returnJsonString = Base64Encoding.decodeToString(interfaceCode.getData());
        return interfaceCode;
    }

    private Map<String,String> getRequestParam(GlobalInfo globalInfo, Authorize authorize, String commonDecrypt2) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("globalInfo", JsonUtils.getInstance().toJsonString(globalInfo));
        requestParam.put("authorize", JsonUtils.getInstance().toJsonString(authorize));
        requestParam.put("data", commonDecrypt2);
        return requestParam;
    }

    private Authorize getAuthorize(String signature, String secretId) {
        Authorize authorize = new Authorize();
        authorize.setAppSec(signature);
        authorize.setAppSecId(secretId);
        return authorize;
    }

    private GlobalInfo getGlobalInfo(String dataExchangeId, String interfaceName) {
        GlobalInfo globalInfo = new GlobalInfo();
        globalInfo.setAppId("JXFP");//appId固定JXFP
        globalInfo.setVersion("v5");//v5
        globalInfo.setEnterpriseCode(null);//设为空，无用
        globalInfo.setDataExchangeId(dataExchangeId);
        globalInfo.setInterfaceCode(interfaceName);
        return globalInfo;
    }

    private String commonEncrypt(String zipCode, String encryptCode, String content,String secretKey) {
        String result = "";
        byte[] de = content.getBytes();
        // 加密
        if (ConfigurerInfo.ENCRYPTCODE_1.equals(encryptCode)) {
            // 截取秘钥
            String password = secretKey.substring(0, ConfigurerInfo.PASSWORD_SIZE);
            try {
                // 加密
                de = TripleDesUtil.encryptMode(password, de);
            } catch (Exception e) {
                log.error("{}3DES加密出现异常:{}", LOGGER_MSG, e);
                return result;
            }
        }
        if (ConfigurerInfo.ZIPCODE_1.equals(zipCode)) {
            // 压缩
            try {
                de = GzipUtils.compress(de);
            } catch (Exception e) {
                log.error("{}GZIP压缩出现异常:{}", LOGGER_MSG, e);
                return result;
            }
        }
        try {
            result = Base64Encoding.encodeToString(de);
        } catch (Exception e) {
            log.error("{}base64压缩出现异常:{}", LOGGER_MSG, e);
            return result;
        }
        return result;
    }

    private CheckResult authV5(String url,HttpServletRequest request, DxhyInterfaceRequest dxhyInterfaceRequest,String secretKey) {
        CheckResult checkResult = new CheckResult(RespStatusEnum.AUTHFAIL);
        String reqUrl = request.getRequestURL().toString();
        if (reqUrl.contains(ConfigureConstant.STRING_WH)) {
            reqUrl = reqUrl.substring(ConfigureConstant.INT_0, reqUrl.indexOf(ConfigureConstant.STRING_WH));
        }

        log.debug("{}请求路径:{}", LOGGER_MSG, reqUrl);

        //获取鉴权URL
//        String signUrl = getAuthUrl(reqUrl, request.getMethod());
        String signUrl = ipUrl+url+"?";
        TreeMap<String, String> sortMap = new TreeMap<>();
        sortMap.put(ConfigurerInfo.SECRETID, dxhyInterfaceRequest.getSecretId());
        sortMap.put(ConfigurerInfo.DATA_EXCHANGE_ID, dxhyInterfaceRequest.getDataExchangeId());
        sortMap.put(ConfigurerInfo.ENCRYPTCODE, dxhyInterfaceRequest.getEncryptCode());
        sortMap.put(ConfigurerInfo.ZIPCODE, dxhyInterfaceRequest.getZipCode());
        sortMap.put(ConfigurerInfo.CONTENT, dxhyInterfaceRequest.getContent());

        String localSign = HmacSHA1Util.genSign(signUrl, sortMap, secretKey);
        String reqSign = dxhyInterfaceRequest.getSignature();
        log.debug("{}生成的本地签名值为local:{}，请求签名值:{}", LOGGER_MSG, localSign, reqSign);
        if (StrUtil.isNotBlank(localSign) && StrUtil.isNotBlank(reqSign)) {
            if (localSign.equals(reqSign)) {
                checkResult = new CheckResult(RespStatusEnum.SUCCESS);
            } else {
                log.error("{}鉴权失败.请求鉴权值为:{},计算后鉴权值为:{}", LOGGER_MSG, reqSign, localSign);
            }
        } else {
            log.error("{}鉴权失败.请求鉴权值和计算后鉴权值为空", LOGGER_MSG);
        }
        return checkResult;
    }

    public String commonDecrypt(String zipCode, String encryptCode, String content,String secretKey) {
        String result = "";
        byte[] de = content.getBytes();
        try {
            de = Base64Encoding.decode(de);
        } catch (Exception e) {
            log.error("{}base64解密出现异常:{}", LOGGER_MSG, e);
            return result;
        }
        if (ConfigurerInfo.ZIPCODE_1.equals(zipCode)) {
            // 解压缩
            try {
                de = GzipUtils.decompress(de);
            } catch (Exception e) {
                log.error("{}解压缩出现异常:{}", LOGGER_MSG, e);
                return result;
            }
        }
        //解密
        if (ConfigurerInfo.ENCRYPTCODE_1.equals(encryptCode)) {
            // 截取秘钥
            String password = secretKey.substring(0, ConfigurerInfo.PASSWORD_SIZE);
            try {
                // 解密
                de = TripleDesUtil.decryptMode(password, de);
            } catch (Exception e) {
                log.error("{}3DES解密出现异常:{}", LOGGER_MSG, e);
                return result;
            }
        }
        if (de != null) {
            result = new String(de, StandardCharsets.UTF_8);
        }
        return result;
    }

    /**
     * 拼接url
     *
     * @param reqUrl
     * @return
     */
    private static String getAuthUrl(String reqUrl, String method) {
        if (reqUrl.split(ConfigureConstant.STRING_COLON).length > ConfigureConstant.INT_2) {
            String one = reqUrl.split(ConfigureConstant.STRING_COLON)[1];
            String two = reqUrl.split(ConfigureConstant.STRING_COLON)[2];
            //支持带端口数据的返回
            if (two.indexOf(ConfigureConstant.STRING_SLASH_LINE) > 0) {
                reqUrl = one.replaceAll("//", "") + ConfigureConstant.STRING_COLON + two;
            } else {
                reqUrl = one.replaceAll("//", "") + two.substring(two.indexOf(ConfigureConstant.STRING_SLASH_LINE));
            }
        } else if (reqUrl.split(ConfigureConstant.STRING_COLON).length == ConfigureConstant.INT_2) {
            String one = reqUrl.split(ConfigureConstant.STRING_COLON)[1];
            reqUrl = one.contains("//") ? one.replaceAll("//", "") : reqUrl;
        }
        return method + reqUrl + "?";
    }
    
    private CheckResult checkInterfaceParamV5(String interfaceVersion, String interfaceName, String secretId, String dataExchangeId, String signature, String encryptCode, String zipCode, String content) {

        log.info("{},数据校验,请求的interfaceVersion:{},interfaceName:{},dataExchangeId:{},secretId:{},signature:{},encryptCode:{},zipCode:{},content:{}", LOGGER_MSG, interfaceVersion, interfaceName, dataExchangeId, secretId, signature, encryptCode, zipCode, content);
        CheckResult checkResult = new CheckResult(RespStatusEnum.SUCCESS);
        StringBuilder stringBuilder = new StringBuilder();
        if (StrUtil.isBlank(interfaceVersion)) {
            stringBuilder.append(RespStatusEnum.CHECK_INTERFACEVERSION_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(interfaceName)) {
            stringBuilder.append(RespStatusEnum.CHECK_INTERFACENAME_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(dataExchangeId)) {
            stringBuilder.append(RespStatusEnum.CHECK_CHANGEID_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(secretId)) {
            stringBuilder.append(RespStatusEnum.CHECK_SECRETID_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(signature)) {
            stringBuilder.append(RespStatusEnum.CHECK_SIGNATURE_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(encryptCode)) {
            stringBuilder.append(RespStatusEnum.CHECK_ENCRYPTCODE_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(zipCode)) {
            stringBuilder.append(RespStatusEnum.CHECK_ZIPCODE_NULL.getDescribe()).append("/r/n");
        } else if (StrUtil.isBlank(content)) {
            stringBuilder.append(RespStatusEnum.CHECK_CONTENT_NULL.getDescribe()).append("/r/n");
        }

        /**
         * 接口版本只支持v5
         * 接口名称暂时不作校验
         */
        if (!ConfigurerInfo.INTERFACE_VERSION_V5.equals(interfaceVersion)) {
            stringBuilder.append(RespStatusEnum.CHECK_INTERFACEVERSION_DATA_ERROR.getDescribe()).append("/r/n");
        } else if (!(ConfigureConstant.STRING_0.equals(encryptCode) || ConfigureConstant.STRING_1.equals(encryptCode))) {
            stringBuilder.append(RespStatusEnum.CHECK_ENCRYPTCODE_DATA_ERROR.getDescribe()).append("/r/n");
        } else if (!(ConfigureConstant.STRING_0.equals(zipCode) || ConfigureConstant.STRING_1.equals(zipCode))) {
            stringBuilder.append(RespStatusEnum.CHECK_ZIPCODE_NULL_DATA_ERROR.getDescribe()).append("/r/n");
        }

        if (StrUtil.isNotBlank(stringBuilder.toString())) {
            log.error("{}数据校验失败,错误信息为:{}", LOGGER_MSG, stringBuilder.toString());
            return CheckResult.error(RespStatusEnum.CHECK_INTERFACEVERSION_NULL.getCode(), stringBuilder.toString());
        }
        return checkResult;
    }
    
    /**
     * 
     * @description 老版接口保留
     * @author Allen 
     * @updateTime 2021/12/20 17:28 
     * @param
     */
    @PostMapping("/dii")
    public String invoice(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        GlobalInfo globalInfo;
        String returnResult;
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            log.info("================" + globalInfo.getDataExchangeId() + "========解析头部信息完成");
            if (validParams == 1) {
                returnResult = authStatusService.getSignFailure(globalInfo);
                log.info("================返回报文：" + returnResult);
                return returnResult;
            }
            Authorize authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 校验IP
            if (checkIp) {
                int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
                if (blocOne == 0) {
                    returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                    log.info("================返回报文：" + returnResult);
                    return returnResult;
                }
            }
            returnResult = routeRequet(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            returnResult = authStatusService.getDealWithFailure(null);
            log.error("========调用接口错误==========", e);
        }
        return returnResult;
    }


    private String routeRequet(GlobalInfo globalInfo
            ,Map<String, String> requestParam
            ,HttpServletRequest request
            , HttpServletResponse response
            ,Authorize authorize) throws Exception {
        log.info("========接口调用开始=======" + globalInfo.getDataExchangeId());
        String returnResult = null;
        switch (globalInfo.getInterfaceCode()) {
            // 发票采集
            case "INVOICE.GET":
                returnResult = gatherService.get(globalInfo, requestParam, request, response, authorize);
                break;
            // 发票状态获取
            case "INVOICE.STATE":
                returnResult = gatherService.getState(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取单张发票
            case "INVOICE.GETSINGLE":
                returnResult = gatherService.getSingle(globalInfo, requestParam, request, response, authorize);
                break;
            // 申请认证
            case "INVOICE.LEGALIZE":
                returnResult =
                        invoiceAuthService.applyInvoiceAuth(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取认证结果
            case "INVOICE.LEGALIZE_STATUS":
                returnResult =
                        invoiceAuthService.getAuthResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取平台认证结果
            case "INVOICE.AUTH_RESULT":
                returnResult = gatherService.getAuthResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 申请统计（撤销）
            case "INVOICE.APPLYSTAT":
                returnResult = applyStatService.applyStat(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取统计结果
            case "INVOICE.STATRESULT":
                returnResult = applyStatService.statResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 申请确认（撤销）
            case "INVOICE.APPLYCONFIRM":
                returnResult =
                        applyStatService.applyConfirm(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取确认结果
            case "INVOICE.CONFIRMRESULT":
                returnResult =
                        applyStatService.confirmResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取平台签收发票
            case "INVOICE.SIGNGET":
                returnResult = signDataService.getInvoice(globalInfo, requestParam, request, response, authorize);
                break;
            // 签收发票
            case "INVOICE.SIGNINVOICE":
                returnResult = signDataService.signInvoice(globalInfo, requestParam, request, response, authorize);
                break;
            // 根据批次号获取签收发票
            case "INVOICE.GETINVOICEBYBATCHNO":
                returnResult =
                        signDataService.getInvoiceByBatchNo(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取发票图片
            case "INVOICE.GETIMG":
                returnResult = signDataService.getImg(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取查验发票信息
            case "INVOICE.GETCHECKINVOICE":
                returnResult = checkDataService.get(globalInfo, requestParam, request, response, authorize);
                break;
            // 永刚进项发票认证状态变更推送接口
            case "INVOICE.APPLY":
                returnResult = orderService.saveOrder(globalInfo, requestParam, request, response, authorize);
                break;
            // 永刚进项认证状态查询获取接口
            case "INVOICE.GETONE":
                returnResult = orderService.countRzhInfo(globalInfo, requestParam, request, response, authorize);
                break;
            // 永刚进项发票认证状态获取接口
            case "INVOICE.LEGALIZESTATUS":
                returnResult = orderService.getRzhStatus(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取企业档案信息
            case "INVOICE.TAXPERIOD":
                returnResult =
                        taxCurrentService.getTaxCurrent(globalInfo, requestParam, request, response, authorize);
                break;
            // 票池入账业务
            case "INVOICE.INACCOUNT":
                returnResult = invoicePoolService.inAccount(globalInfo, requestParam, request, response, authorize);
                break;
            // 票池摊销业务
            case "INVOICE.AMORTIZE":
                returnResult = invoicePoolService.amortize(globalInfo, requestParam, request, response, authorize);
                break;
            // 票池采集业务
            case "INVOICE.LISTINVOICE":
                returnResult =
                        invoicePoolService.listInvoice(globalInfo, requestParam, request, response, authorize);
                break;
            // 票池状态采集业务
            case "INVOICE.LISTSTATE":
                returnResult = invoicePoolService.listState(globalInfo, requestParam, request, response, authorize);
                break;
            // 每日优鲜全票面信息获取接口
            case "MRYX.GETINVOICE":
                returnResult =
                        mryxInterfaceService.getAllInfo(globalInfo, requestParam, request, response, authorize);
                break;
            // 每日优鲜签收状态获取接口
            case "MRYX.GETSTATUS":
                returnResult =
                        mryxInterfaceService.getSignState(globalInfo, requestParam, request, response, authorize);
                break;
            // 每日优鲜付款信息同步接口
            case "MRYX.SYNINFO":
                returnResult =
                        mryxInterfaceService.synPayInfo(globalInfo, requestParam, request, response, authorize);
                break;
            // 每日优鲜取消签收
            case "INVOICE.REVOKESIGN":
                returnResult = signDataService.revokeSign(globalInfo, requestParam, request, response, authorize);

                break;
            // 海关缴款书采集
            case "CUSTOMSPC.GET":
                returnResult = customspcService.getCustoms(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书状态采集
            case "CUSTOMSPC.STATE":
                returnResult =
                        customspcService.getCustomsState(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书认证请求
            case "CUSTOMSPC.LEGALIZE":
                returnResult =
                        customspcService.applyCustomsAuth(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书认证结果获取
            case "CUSTOMSPC.LEGALIZE_STATUS":
                returnResult =
                        customspcService.getCustomsAuthResult(globalInfo, requestParam, request, response, authorize);

                break;
            // 海关缴款书申请录入
            case "CUSTOMSPC.ENTRY":
                returnResult =
                        customspcService.applyCustomsUpload(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书录入结果获取
            case "CUSTOMSPC.ENTRY_RESULT":
                returnResult =
                        customspcService.getCustomsUploadResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 58 --获取签收结果信息
            case "GET.SIGNRESULT":
                returnResult =
                        feService.getSignResult(globalInfo, requestParam, request, response, authorize);
                break;
            // 亚宝获取报销信息
            case "GET.INVOICE":
                returnResult = yaBaoService.getBx(globalInfo, requestParam, request, response, authorize);
                break;
            // 亚宝用户注册接口
            case "USER.ADD":
                returnResult =
                        yaBaoService.yaBaoUserAdd(globalInfo, requestParam, request, response, authorize);
                break;
            // 进项税转出
            case "INVOICE.GETINVOICEOUT":
                returnResult = tDxRecordInvoiceOutService.getOutInvoice(globalInfo, requestParam, request, response,
                        authorize);
                break;
            case "INVOICE.REIMBURSEMENT":
                log.info("接收票据:{}", requestParam.get("data"));
                ReimburseReq reimburseReq = JSONObject.parseObject(requestParam.get("data"), ReimburseReq.class);
                ReturnStateInfo run = new ReturnStateInfo();
                InterfaceCode interfaceCode = new InterfaceCode();
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                SysDeptEntity deptEntity = sysDeptDao.getOrgType(reimburseReq.getGfTaxNo());
                if (deptEntity == null) {
                    run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(run);
                    return JSON.toJSONString(interfaceCode);
                }
                TDxInvoiceReimburse reimburse = tDxInvoiceReimburseService.invoiceHandle(reimburseReq, deptEntity);
                if ("1".equals(reimburse.getQsStatus())) {
                    run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(run);
                    returnResult = JSON.toJSONString(interfaceCode);
                } else {
                    run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
                    run.setReturnMessage(reimburse.getNotes());
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(run);
                    returnResult = JSON.toJSONString(interfaceCode);
                }

                break;
            case "INVOICE.RISKSTATISTICS":
                returnResult =
                        riskStatisticsService.getRiskStatistics(globalInfo, requestParam, request, response, authorize);
                break;
            case "INVOICE.SIGNCANCELED":
                returnResult =
                        tDxInvoiceReimburseService.signCanceled(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书入账业务
            case "CUSTOMSPC.INACCOUNT":
                returnResult = customspcService.customspcInAccount(globalInfo, requestParam, request, response, authorize);
                break;
            // 海关缴款书查询
            case "CUSTOMSPC.GETSINGLE":
                returnResult = customspcService.getSingle(globalInfo, requestParam, request, response, authorize);
                break;
            //申报进项转出统计
            case "INVOICE.TRANSFER":
                returnResult =
                        declareService.getTransferStatistics(globalInfo, requestParam, request, response, authorize);
                break;
            //申报统计接口
            case "INVOICE.REPORTSTATISTICS":
                returnResult =
                        declareService.getReportStatistics(globalInfo, requestParam, request, response, authorize);
                break;
            //销项数据推送
            case "INVOICE.SALSESPUSH":
                returnResult = invoicePoolService.salsePush(globalInfo, requestParam, request, response, authorize);
                break;

            // 获取单张发票
            case "INVOICE.SINGLEINVOICECHECK":
                returnResult = gatherService.singleInvoiceChenck(globalInfo, requestParam, request, response, authorize);
                break;
            // 获取单张发票
            case "INVOICE.SYNCINVOICEINFO":
                returnResult = gatherService.syncInvoiceInfo(globalInfo, requestParam, request, response, authorize);
                break;

            // 接口编码不存在
            default:
                returnResult = authStatusService.getInterfaceCodeError(globalInfo);
                break;
        }
        log.info("========调用接口结束========" + globalInfo.getDataExchangeId());
        log.info("========调用返回========" + returnResult);
        return returnResult;
    }


    /**t
     * 入账业务接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/inAccount")
    public String inAccount(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = invoicePoolService.inAccount(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
      * 海关缴款书入账业务接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/customsInAccount")
    public String customsInAccount(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = customspcService.customspcInAccount(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
     * 海关缴款书查询
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/getSingle")
    public String getSingle(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = customspcService.getSingle(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
     * 摊销业务接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/amortize")
    public String amortize(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = invoicePoolService.amortize(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
     * 票池采集业务接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/listInvoice")
    public String listInvoice(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = invoicePoolService.listInvoice(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
     * 票池采集业务接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/listState")
    public String listState(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult = invoicePoolService.listState(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    @PostMapping("/salsePush")
    public String salsePush(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);

            log.info("接收的push参数globalInfo={}",globalInfo);

            // 校验IP
//            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
//            if (blocOne == 0) {
//                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
//                return returnResult;
//            }
            returnResult = invoicePoolService.salsePush(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    @PostMapping("/reimbursementSync")
    public String reimbursementSync(HttpServletRequest request, HttpServletResponse response) {
        String authorize1 = request.getParameter("authorize");
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            if (checkIp) {
                int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
                if (blocOne == 0) {
                    returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                    return returnResult;
                }
            }
            log.info("接收票据:{}", requestParam.get("data"));
            ReimburseReq reimburseReq = JSONObject.parseObject(requestParam.get("data"), ReimburseReq.class);
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrgType(reimburseReq.getGfTaxNo());
            if (deptEntity == null) {
                run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            TDxInvoiceReimburse reimburse = tDxInvoiceReimburseService.invoiceHandle(reimburseReq, deptEntity);
            if ("1".equals(reimburse.getQsStatus())) {
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                returnResult = JSON.toJSONString(interfaceCode);
            } else {
                run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
                run.setReturnMessage(reimburse.getNotes());
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                returnResult = JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }
        return returnResult;
    }

    /**
     * 风控统计接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/riskStatistics")
    public String riskStatistics(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
            if (blocOne == 0) {
                returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                return returnResult;
            }
            returnResult =
                riskStatisticsService.getRiskStatistics(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }

        return returnResult;
    }

    /**
     * 进项转出统计
     */
    @PostMapping("/transfer")
    public String transfer(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            if (checkIp) {
                int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
                if (blocOne == 0) {
                    returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                    log.info("================返回报文：" + returnResult);
                    return returnResult;
                }
            }
            returnResult =
                    declareService.getTransferStatistics(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }
        return returnResult;
    }

    /**
     * 申报统计接口
     */
    @PostMapping("/reportStatistics")
    public String reportStatistics(HttpServletRequest request, HttpServletResponse response) {
        String returnResult = null;
        ObjectMapper mapper = new ObjectMapper();
        GlobalInfo globalInfo = null;
        Authorize authorize = null;
        try {
            // 获取json
            Map<String, String> requestParam = OpenApiUtils.getRequestParam(request, mapper);
            authorize = JSON.parseObject(requestParam.get("authorize"), Authorize.class);
            // 鉴权校验接口安全
            int validParams = authStatusService.validParams(request, requestParam);
            globalInfo = authStatusService.getGlobalInfo(requestParam);
            // 校验IP
            if (checkIp) {
                int blocOne = checkIpBlocAppidService.checkBlocOne(authorize.getAppSecId(), request);
                if (blocOne == 0) {
                    returnResult = checkIpBlocAppidService.getCheckFailure(globalInfo);
                    log.info("================返回报文：" + returnResult);
                    return returnResult;
                }
            }
            returnResult =
                    declareService.getReportStatistics(globalInfo, requestParam, request, response, authorize);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("线程{},接口调用错误{}", Thread.currentThread().getId(), authorize.getAppSec());
            returnResult = authStatusService.getDealWithFailure(globalInfo);
        }
        return returnResult;
    }
    @RequestMapping(path = "/po",method={RequestMethod.POST,RequestMethod.GET})
    public String po(@RequestBody String param,HttpServletRequest request){
        log.info("po接口调用开始,传参{}",param);
        String token = request.getHeader("token");
        if(org.apache.commons.lang3.StringUtils.isBlank(token) && !ConfigureConstant.POTOKEN.equals(token)){
            return "非法请求,请停止访问!";
        }
        String resultString = "";
        ErpInvoiceData requestParam = JsonUtils.getInstance().parseObject(param, ErpInvoiceData.class);
        //同步 凭证号 判断自动认证接口开发
        if("FI847".equals(requestParam.getIS_INPUT().getIFYWID())){
            resultString = receiveErpInvoiceMessage(requestParam);
            //进项税转出
        }else if("FI849".equals(requestParam.getIS_INPUT().getIFYWID())){
            resultString = transferOut(requestParam);
            //票账比对数据推送
        }else if("FI848".equals(requestParam.getIS_INPUT().getIFYWID())){
            resultString = insertVouncherRecord(requestParam);
        }
        return resultString;
    }

    private String insertVouncherRecord(ErpInvoiceData requestParam) {

        OutPut outPut = new OutPut();
        String zdata = requestParam.getIS_INPUT().getZDATA();
        List<VoucherRecord> voucherRecords = JSON.parseArray(zdata, VoucherRecord.class);
        DynamicContextHolder.push("business"+ DbConstant.BUSINESS_READ);
        try{
            boolean b = voucherRecordService.addVoucherRecords(voucherRecords);
            EsOutPutResp esOutPutResp = new EsOutPutResp();
            esOutPutResp.setBSKEY(requestParam.getIS_INPUT().getBSKEY());
            esOutPutResp.setSAPKEY(requestParam.getIS_INPUT().getSAPKEY());
            if(b){
                esOutPutResp.setZTYPE("S");
                esOutPutResp.setZMESSAGE("处理成功");
            }else {
                esOutPutResp.setZTYPE("E");
                esOutPutResp.setZMESSAGE("处理失败");
            }
            outPut.setES_OUTPUT(esOutPutResp);
            return JsonUtils.getInstance().toJsonString(outPut);
        }catch (Exception e){
            e.printStackTrace();
            EsOutPutResp esOutPutResp = new EsOutPutResp();
            esOutPutResp.setBSKEY(requestParam.getIS_INPUT().getBSKEY());
            esOutPutResp.setSAPKEY(requestParam.getIS_INPUT().getSAPKEY());
            esOutPutResp.setZTYPE("E");
            esOutPutResp.setZMESSAGE("程序内部错误");
            outPut.setES_OUTPUT(esOutPutResp);
            return JsonUtils.getInstance().toJsonString(outPut);
        }

    }


    @PostMapping("receiveErpInvoiceMessage")
    public String receiveErpInvoiceMessage(@RequestBody ErpInvoiceData erpInvoiceData){
        OutPut outPut = new OutPut();

        List<ZDATA> zdata = JSON.parseArray(erpInvoiceData.getIS_INPUT().getZDATA(), ZDATA.class);
        List<String> fpdms = new ArrayList<>();
        List<String> fphms = new ArrayList<>();
        List<String> bzdhs = new ArrayList<>();
        zdata.stream().forEach(zdata1 -> {
            fpdms.add(zdata1.getZFPDM());
            fphms.add(zdata1.getZFPHM());
            bzdhs.add(zdata1.getZBZDH());
        });
        RequestRecord receiveErpInvoiceMessageRecord =requestRecordService.getBaseRequestRecord(JSONObject.toJSONString(erpInvoiceData),
                "/po", JSONObject.toJSONString(fpdms),JSONObject.toJSONString(fphms), "receiveErpInvoiceMessage");
        receiveErpInvoiceMessageRecord.setBzdh(JSONObject.toJSONString(bzdhs));

        try {
            EsOutPutResp esOutPutResp=invoiceAuthService.receiveErpInvoiceMessage(erpInvoiceData.getIS_INPUT());
            outPut.setES_OUTPUT(esOutPutResp);

            try {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                if (esOutPutResp.getZMESSAGE().contains("不存在")) {
                    requestRecordService.saveFailedRequestRecord(receiveErpInvoiceMessageRecord, 0, JsonUtils.getInstance().toJsonString(outPut),
                            esOutPutResp.getZMESSAGE());
                } else {
                    requestRecordService.saveSuccessfulRequestRecord(receiveErpInvoiceMessageRecord, JsonUtils.getInstance().toJsonString(outPut));
                }
            } catch (Exception e) {
                log.error("FI847接口记录保存失败，errormsg:{}",e);
            }

            return JsonUtils.getInstance().toJsonString(outPut);
        }catch (Exception e){
            log.info("{}接收erp发票数据出错,sapkey:{}",e,erpInvoiceData.getIS_INPUT().getSAPKEY());
            e.printStackTrace();
            EsOutPutResp esOutPutResp = new EsOutPutResp();
            esOutPutResp.setBSKEY(erpInvoiceData.getIS_INPUT().getBSKEY());
            esOutPutResp.setSAPKEY(erpInvoiceData.getIS_INPUT().getSAPKEY());
            esOutPutResp.setZTYPE("E");
            esOutPutResp.setZMESSAGE("程序内部错误");
            outPut.setES_OUTPUT(esOutPutResp);

            try {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                requestRecordService.saveFailedRequestRecord(receiveErpInvoiceMessageRecord, 1, JsonUtils.getInstance().toJsonString(outPut),
                        "FI847接口接收erp发票数据出错,异常信息："+"{"+JSONObject.toJSONString(e)+"}");
            } catch (Exception exception) {
                log.error("FI847接口记录保存失败，errormsg:{}",e);
            }

            return JsonUtils.getInstance().toJsonString(outPut);
        }
    }

    public String transferOut(ErpInvoiceData erpInvoiceData){

        String zdata = erpInvoiceData.getIS_INPUT().getZDATA();
        List<Map> list = JSON.parseArray(zdata, Map.class);

        List<String> fpdms = new ArrayList<>();
        List<String> fphms = new ArrayList<>();
        List<String> bzdhs = new ArrayList<>();
        for (Map<String ,Object> map:list) {
            String invoiceCode =(String) map.get("ZFPDM");
            String invoiceNo = (String)map.get("ZFPHM");
            String bzdh = map.get("ZBZDH")==null?"":map.get("ZBZDH").toString();
            fpdms.add(invoiceCode);
            fphms.add(invoiceNo);
            bzdhs.add(bzdh);
        }
        log.info("进项税转出（FI849）接收到的发票号码为:{}\n进项税转出（FI849）接收到的发票代码为:{}\n进项税转出（FI849）接收到的报账单号为:{}\n",
                JSONObject.toJSONString(fphms),JSONObject.toJSONString(fpdms),JSONObject.toJSONString(bzdhs));
        RequestRecord transferOutRecord =requestRecordService.getBaseRequestRecord(JSONObject.toJSONString(erpInvoiceData),
                "/po", JSONObject.toJSONString(fpdms),JSONObject.toJSONString(fphms), "transferOut");
        transferOutRecord.setBzdh(JSONObject.toJSONString(bzdhs));

        for(Map<String ,Object> map:list){
            String invoiceCode =(String) map.get("ZFPDM");
            String invoiceNo = (String)map.get("ZFPHM");
            String uuid = invoiceCode+invoiceNo;
            String[] ids = uuid.split(",");
            DynamicContextHolder.push("business"+DbConstant.BUSINESS_READ);
            List<BaseTDxRecordInvoice> invoices = baseIReceiptInvoiceService.selectByUuids(ids);
            OutPut outPut = new OutPut();
            EsOutPutResp es = new EsOutPutResp();
            es.setSAPKEY(erpInvoiceData.getIS_INPUT().getSAPKEY());
            es.setBSKEY(erpInvoiceData.getIS_INPUT().getBSKEY());
            es.setZTYPE("S");
            es.setZMESSAGE("处理成功");
            if(CollectionUtils.isEmpty(invoices)){
                es.setZTYPE("E");
                es.setZMESSAGE("底账数据不存在");
                outPut.setES_OUTPUT(es);

                try {
                    DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                    requestRecordService.saveFailedRequestRecord(transferOutRecord, 0, JsonUtils.getInstance().toJsonString(outPut),
                            es.getZMESSAGE());
                } catch (Exception e) {
                    log.error("FI849接口记录保存失败，errormsg:{}",e);
                }

                return JsonUtils.getInstance().toJsonString(outPut);
            }
        }


        try{
            /**
             * 根据金额判断是转入还是转出
             *
             *
             */
            String transfer ="";
            for(Map<String,Object> map:list) {
                String invoiceCode =(String) map.get("ZFPDM");
                String invoiceNo = (String)map.get("ZFPHM");
                BigDecimal bigDecimal = (BigDecimal) map.get("JXSZC");
                String outReason = (String)map.get("ZZCYY");
                String outTaxPeriod = (String)map.get("BUDAT");
                String uuid = invoiceCode+invoiceNo;
                BaseInvoiceEditVO baseInvoiceEditVO = new BaseInvoiceEditVO();
                baseInvoiceEditVO.setPrimaryKey(uuid);
                baseInvoiceEditVO.setOutReason(outReason);
                baseInvoiceEditVO.setOutTax(bigDecimal.toString());
                baseInvoiceEditVO.setOutStatus("1");
                baseInvoiceEditVO.setOutTaxPeriod(outTaxPeriod);
                UserInfo userInfo = new UserInfo();
                if(bigDecimal.compareTo(BigDecimal.ZERO)==1){
                    transfer = iReceiptOutService.transfer(erpInvoiceData,baseInvoiceEditVO, userInfo);
                }else {
                    BaseReceiptOutCancelEditReqVO baseReceiptOutCancelEditReqVO = new BaseReceiptOutCancelEditReqVO();
                    baseReceiptOutCancelEditReqVO.setPrimaryKey(uuid);
                    String s = baseIReceiptInvoiceService.cancelOut(baseReceiptOutCancelEditReqVO);
                    if(s.equals("取消转出成功")){
                        OutPut outPut = new OutPut();
                        EsOutPutResp es = new EsOutPutResp();
                        es.setSAPKEY(erpInvoiceData.getIS_INPUT().getSAPKEY());
                        es.setBSKEY(erpInvoiceData.getIS_INPUT().getBSKEY());
                        es.setZTYPE("S");
                        es.setZMESSAGE("处理成功");
                        outPut.setES_OUTPUT(es);
                        transfer = JsonUtils.getInstance().toJsonString(outPut);
                    }
                }
            }

            try {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                requestRecordService.saveSuccessfulRequestRecord(transferOutRecord, transfer);
            } catch (Exception e) {
                log.error("FI849接口记录保存失败，errormsg:{}",e);
            }

            return transfer;
        }catch (Exception e){
            log.error("error", e);
            OutPut outPut = new OutPut();
            EsOutPutResp es = new EsOutPutResp();
            es.setSAPKEY(erpInvoiceData.getIS_INPUT().getSAPKEY());
            es.setBSKEY(erpInvoiceData.getIS_INPUT().getBSKEY());
            es.setZTYPE("E");
            es.setZMESSAGE("系统内部错误");
            outPut.setES_OUTPUT(es);

            try {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                requestRecordService.saveFailedRequestRecord(transferOutRecord,1, JsonUtils.getInstance().toJsonString(outPut),
                        "进项税转出（FI849）处理出现异常，异常信息："+"{"+JSONObject.toJSONString(e)+"}");
            } catch (Exception exception) {
                log.error("FI849接口记录保存失败，errormsg:{}",e);
            }

            return JsonUtils.getInstance().toJsonString(outPut);
        }

    }


}
