package com.jianshui.invoice.service.impl.api;
import java.util.Date;

import cn.hutool.core.bean.copier.CopyOptions;
import com.jianshui.invoice.domain.dto.api.*;
import com.jianshui.invoice.domain.dto.api.jcsk.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jianshui.common.constant.WebServiceConstant;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.enums.ErrorCode;
import com.jianshui.common.exception.jianshui.JianshuiParamErrorException;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.TimeUtil;
import com.jianshui.common.utils.ValidateUtils;
import com.jianshui.common.utils.jcsk.ApiHttp;
import com.jianshui.common.utils.uuid.IdUtils;
import com.jianshui.framework.manager.AsyncManager;
import com.jianshui.invoice.constant.aisino.console.AisinoConsoleConstants;
import com.jianshui.invoice.domain.*;
import com.jianshui.invoice.domain.dto.*;
import com.jianshui.invoice.domain.dto.api.aisino.console.*;
import com.jianshui.invoice.domain.dto.api.jcsk.add.InvoiceAllAddInfoTwoDTO;
import com.jianshui.invoice.domain.dto.api.jcsk.add.InvoiceAllAddTwoDTO;
import com.jianshui.invoice.domain.dto.api.jcsk.add.InvoiceAllAddmxListTwoDTO;
import com.jianshui.invoice.domain.dto.api.jcsk.red.AddRedInvoiceTwoDTO;
import com.jianshui.invoice.domain.vo.jcsk.*;
import com.jianshui.invoice.mapper.*;
import com.jianshui.invoice.service.IInvoiceApiService;
import com.jianshui.invoice.utils.aisino.console.AisinoConsoleUtil;
import com.jianshui.system.domain.InvoiceAllApiLog;
import com.jianshui.system.domain.InvoiceAllYhdj;
import com.jianshui.system.mapper.InvoiceAllApiLogMapper;
import com.jianshui.system.mapper.InvoiceAllYhdjMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 金财数科
 */
@Component("jcsk_invoice")
@Slf4j
public class JcskInvoiceApiServiceImpl implements IInvoiceApiService {

    @Autowired
    private BillInfoMapper billInfoMapper;
    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private SkDyjMapper skDyjMapper;

    @Autowired
    private RedinfoMapper redinfoMapper;

    @Autowired
    private InvoiceAllApiLogMapper allApiLogMapper;

    @Autowired
    private InvoiceAllYhdjMapper yhdjMapper;


    /**
     * 发票开具
     *
     * @param billInfo
     * @param companyservice
     * @return com.jianshui.invoice.domain.dto.HXResponse
     * @author dxk
     * @date 2022/6/27 16:50
     */
    @Override
    public HXResponse addInvoice(BillInfo billInfo, Companyservice companyservice) throws IllegalAccessException, InstantiationException {

        // 请求billInfo
        Long billInfoID = 0L;

        // kptype 1蓝票 2红票
        String kpType = billInfo.getKptype();

        if ("1".equals(kpType)) {

            // 查询用户登记参数
            QueryWrapper<InvoiceAllYhdj> yhdjQueryWrapper = new QueryWrapper<>();
            yhdjQueryWrapper.eq("nsrsbh", companyservice.getSellertax());
            yhdjQueryWrapper.eq("identity", companyservice.getIdentity());
            InvoiceAllYhdj invoiceAllYhdj = yhdjMapper.selectOne(yhdjQueryWrapper);

            if (BeanUtil.isEmpty(invoiceAllYhdj)) {
                return new HXResponse("用户未登记！");
            }

            QueryTwoDTO queryDTO = new QueryTwoDTO();
            queryDTO.setDqbm(invoiceAllYhdj.getDqbm());
            queryDTO.setAsync("false");
            queryDTO.setBsrysfzjhm(invoiceAllYhdj.getBsrysfzjhm());
            queryDTO.setNsrsbh(invoiceAllYhdj.getNsrsbh());
            queryDTO.setRequestId("tycxjk");

            // 开票实体转换,校验
            InvoiceAllAddTwoDTO invoiceAllAddTwoDTO = BeanUtil.copyProperties(billInfo, InvoiceAllAddTwoDTO.class);
            invoiceAllAddTwoDTO.setDqbm(queryDTO.getDqbm());
            invoiceAllAddTwoDTO.setBsrysfzjhm(queryDTO.getBsrysfzjhm());
            invoiceAllAddTwoDTO.setNsrsbh(queryDTO.getNsrsbh());
            invoiceAllAddTwoDTO.setAsync("true");
            ValidateUtils.validate(invoiceAllAddTwoDTO);

            // 忽略明细属性
            InvoiceAllAddInfoTwoDTO invoiceAllAddInfoTwoDTO = BeanUtil.copyProperties(billInfo, InvoiceAllAddInfoTwoDTO.class
                    ,"fjxxList","mxList","tdywxx","ext");
            // TODO: 2023/4/24 明细处理 必填非必填对应

            ValidateUtils.validate(invoiceAllAddInfoTwoDTO);

            // 明细集合
            List<InvoiceAllAddmxListTwoDTO> mxList = BeanUtil.copyToList(billInfo.getBillDetailList(), InvoiceAllAddmxListTwoDTO.class);
            if (CollectionUtils.isEmpty(mxList)) {
                return new HXResponse("mxList明细集合不存在！");
            }
            for (InvoiceAllAddmxListTwoDTO addmxListDTO : mxList) {
                ValidateUtils.validate(addmxListDTO);
            }

            invoiceAllAddInfoTwoDTO.setMxList(mxList);
            invoiceAllAddTwoDTO.setJsonData(invoiceAllAddInfoTwoDTO);


            // 报文转换存储
            billInfo.setCompanyId(companyservice.getCompanyid());
            billInfo.setServiceSupplierKey("JCSK");
            try {
                int resBillInfo = billInfoMapper.insertBillInfo(billInfo);
                if (resBillInfo > 0) {
                    billInfoID = billInfo.getId();
                    if (BeanUtil.isEmpty(billInfo.getId())) {
                        log.error("【金四服务类】【金财数科】【蓝字发票开具】API请求异常，billInfoId返回存储错误。");
                        return new HXResponse("蓝字发票开具内部错误！");
                    }
                    //数据库存储
                    List<BillDetail> billDetailList = billInfo.getBillDetailList();
                    int billDetailResult = billInfoMapper.batchBillDetail(billDetailList);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【金四服务类】【金财数科】【蓝字发票开具】API请求异常，billInfo存储错误。错误信息:{}", e.getMessage());
                return new HXResponse("蓝字发票开具内部错误！");
            }

            cn.hutool.json.JSONObject result = null;

            // TODO: 2023/4/23 调试
            log.info("金财数科蓝字请求报文打印=",JSONUtil.parse(invoiceAllAddTwoDTO));
            return null;
            
            /*try {
                result = ApiHttp.request(WebServiceConstant.LZFPKJ, WebServiceConstant.URL, invoiceAllAddTwoDTO, companyservice);

                String code = result.get("code") != null ? result.get("code").toString() : "";
                String msg = result.get("msg") != null ? result.get("msg").toString() : "";
                String data = result.get("data") != null ? result.get("data").toString() : "";

                if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                    cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                    String requestId = json.getOrDefault("requestId", "").toString();
                    if (StrUtil.isEmpty(requestId)) {
                        return new HXResponse(msg);
                    }
                    BillInfo billInfoRes = billInfoMapper.selectBillInfoById(billInfoID);
                    billInfoRes.setOutTradeOrderno(requestId);
                    billInfoMapper.updateBillInfo(billInfoRes);

                    // 保存日志
                    InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                    allApiLog.setUrl(WebServiceConstant.LZFPKJ);
                    allApiLog.setSendMsg("");
                    allApiLog.setResultMsg("");
                    allApiLog.setCompany(companyservice.getSellertax());
                    allApiLog.setIdentityId(companyservice.getIdentity());
                    allApiLog.setRequestId(requestId);
                    allApiLog.setCreateTime(new Date());
                    AsyncManager.me().execute(
                            new TimerTask() {
                                @Override
                                public void run() {
                                    allApiLogMapper.insertInvoiceAllApiLog(allApiLog);
                                }
                            }
                    );

                    HXResponse response = new HXResponse("0000", "同步成功");
                    response.put("fpqqlsh", billInfo.getSystemOrderno());
                    return response;
                } else {
                    return new HXResponse(msg);
                }
            } catch (Exception e) {
                log.error("【金四服务类】【金财数科】【蓝字发票开具】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
                return new HXResponse("蓝字发票开具异常");
            }*/

        } else if ("2".equals(kpType)) {

            //billinfo => 红字报文

            AddRedInvoiceTwoDTO addRedInvoiceDTO = BeanUtil.copyProperties(billInfo, AddRedInvoiceTwoDTO.class);
            ValidateUtils.validate(addRedInvoiceDTO);

            // 查找原Invoice
            QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
            invoiceQueryWrapper.eq("fphm", addRedInvoiceDTO.getYfphm());
            invoiceQueryWrapper.eq("invoice_type", getInvoiceType(addRedInvoiceDTO.getYfplxdm(), false));
            Invoice originInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
            if (originInvoice == null) {
                return new HXResponse(ErrorCode.INVOICE_NOT_EXISTS.toString());
            }

            BillInfo redBillInfo = billInfoMapper.selectById(originInvoice.getBillInfoId());
            if (billInfo == null) {
                return new HXResponse(ErrorCode.INVOICE_NOT_EXISTS.toString());
            }
            redBillInfo.setId(null);
            redBillInfo.setOriginFphm(addRedInvoiceDTO.getYfphm());
            redBillInfo.setOutTradeOrderno(addRedInvoiceDTO.getFpqqlsh());
            redBillInfo.setFpqqlsh("");
            String systemOrderno = IdUtils.randomSystemOrderno();
            redBillInfo.setSystemOrderno(systemOrderno);
            redBillInfo.setKptype("2");
            if (billInfoMapper.insert(redBillInfo) == 0) {
                return new HXResponse(ErrorCode.INVOICE_NOT_EXISTS.toString());
            }

            cn.hutool.json.JSONObject result = null;
            try {
                result = ApiHttp.request(WebServiceConstant.ADD_RED_INVOICE, WebServiceConstant.URL, addRedInvoiceDTO, companyservice);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
                return new HXResponse(ErrorCode.INCOME_ERROR.toString());
            }

            // 处理请求
            if (!StringUtils.equals("0000", result.getStr("code"))) {
                log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。返回信息:{}", result);
                return new HXResponse(result.getStr("message"));
            }

            cn.hutool.json.JSONObject data = result.getJSONObject("data");
            if (data == null) {
                return new HXResponse(ErrorCode.INCOME_ERROR.toString());
            }

            String requestId = data.getStr("requestId");
            redBillInfo.setFpqqlsh(requestId);
            redBillInfo.setOutTradeOrderno(requestId);
            billInfoMapper.updateById(redBillInfo);

            HXResponse response = new HXResponse("0000", "同步成功");
            response.put("fpqqlsh", billInfo.getSystemOrderno());
            return response;
        } else {
            return new HXResponse(ErrorCode.INCOME_ERROR + "未获取到开票类型！".toString());
        }

    }


    /**
     * 发票打印
     *
     * @param invoice
     * @param companyservice
     * @return com.jianshui.common.core.domain.AjaxResult
     * @author dxk
     * @date 2022/6/29 13:48
     */
    @Override
    public AjaxResult printInvoice(Invoice invoice, Companyservice companyservice) {
        return null;
    }


    /**
     * 发票作废
     *
     * @param invoice
     * @param companyservice
     * @return com.jianshui.invoice.domain.dto.HXResponse
     * @author dxk
     * @date 2022/6/30 9:43
     */
    @Override
    public HXResponse deprecateInvoice(JSONObject invoice, Companyservice companyservice) {
        return null;
    }


    @Override
    public AjaxResult reInvoice(BillInfo billInfo, Companyservice companyservice) {
        return null;
    }

    /**
     * 单个发票查询
     *
     * @param billInfo
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse queryInvoice(QueryBillInfoDTO billInfo, Companyservice companyservice) {

        String systemOrderNo = billInfo.getSystemOrderno();
        BillInfo billInfoResult = billInfoMapper.selectBySystemOrderNo(companyservice.getCompanyid(), systemOrderNo);

        // requestId=OutTradeOrderno
        if (StrUtil.isEmpty(billInfoResult.getOutTradeOrderno())) {
            return new HXResponse("未获取到开票记录！");
        }

        // 查询用户登记参数
        QueryWrapper<InvoiceAllYhdj> yhdjQueryWrapper = new QueryWrapper<>();
        yhdjQueryWrapper.eq("nsrsbh", companyservice.getSellertax());
        yhdjQueryWrapper.eq("identity", companyservice.getIdentity());
        InvoiceAllYhdj invoiceAllYhdj = yhdjMapper.selectOne(yhdjQueryWrapper);

        if (BeanUtil.isEmpty(invoiceAllYhdj)) {
            return new HXResponse("用户未登记！");
        }

        QueryTwoDTO queryDTO = new QueryTwoDTO();
        queryDTO.setDqbm(invoiceAllYhdj.getDqbm());
        queryDTO.setAsync("false");
        queryDTO.setBsrysfzjhm(invoiceAllYhdj.getBsrysfzjhm());
        queryDTO.setNsrsbh(invoiceAllYhdj.getNsrsbh());
        queryDTO.setRequestId("tycxjk");

        ValidateUtils.validate(queryDTO);

        String requestId = queryDTO.getRequestId();
        String serviceId = "";

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.TYCXJK, WebServiceConstant.URL, queryDTO, companyservice);


            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {

                QueryWrapper<InvoiceAllApiLog> apiLogQueryWrapper = new QueryWrapper<>();
                apiLogQueryWrapper.eq("request_id", requestId);
                InvoiceAllApiLog allApiLog = allApiLogMapper.selectOne(apiLogQueryWrapper);
                if (BeanUtil.isNotEmpty(allApiLog) && StrUtil.isNotEmpty(allApiLog.getRequestId())) {
                    serviceId = allApiLog.getRequestId();
                }

                HXResponse response = new HXResponse("0000", "查询成功");

                String finalServiceId = serviceId;

                if (WebServiceConstant.LZFPKJ.equals(finalServiceId)) {
                    // 蓝字发票开具
                    AddInvoiceTWOVO addInvoiceVO = BeanUtil.copyProperties(data, AddInvoiceTWOVO.class);

                    if (BeanUtil.isNotEmpty(addInvoiceVO)) {
                        QueryWrapper<BillInfo> billInfoQueryWrapper = new QueryWrapper<>();
                        billInfoQueryWrapper.eq("out_trade_orderno", requestId);
                        BillInfo billInfoR = billInfoMapper.selectOne(billInfoQueryWrapper);
                        if (BeanUtil.isNotEmpty(billInfoR)) {
                            QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
                            invoiceQueryWrapper.eq("out_trade_orderno", requestId);
                            Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                            if (BeanUtil.isNotEmpty(invoice)) {
                                invoice = BeanUtil.copyProperties(billInfo, Invoice.class);
                                invoice.setFphm(addInvoiceVO.getFphm());
                                invoice.setKprq(DateUtil.parse(addInvoiceVO.getKprq()));
                                invoice.setZzfpdm(addInvoiceVO.getZzfpdm());
                                invoice.setZzfphm(addInvoiceVO.getZzfphm());
                                //二维码=二维码下载地址
                                invoice.setQrCode(addInvoiceVO.getEwmUrl());
                                //发票 pdf 地址=PDF格式下载地址
                                invoice.setInvoicePdfUrl(addInvoiceVO.getPdfUrl());
                                //发票详情地址=OFD格式下载地址
                                invoice.setInvoiceJpgUrl(addInvoiceVO.getOfdUrl());
                                //ofdUrl=XML格式下载地址
                                invoice.setcOfdUrl(addInvoiceVO.getXmlUrl());
                                invoice.setState(2);
                                invoiceMapper.updateInvoice(invoice);
                                billInfoR.setState(2);
                                billInfoMapper.updateById(billInfoR);
                            } else {
                                invoice = BeanUtil.copyProperties(billInfo, Invoice.class);
                                invoice.setFphm(addInvoiceVO.getFphm());
                                invoice.setKprq(DateUtil.parse(addInvoiceVO.getKprq()));
                                invoice.setZzfpdm(addInvoiceVO.getZzfpdm());
                                invoice.setZzfphm(addInvoiceVO.getZzfphm());
                                //二维码=二维码下载地址
                                invoice.setQrCode(addInvoiceVO.getEwmUrl());
                                //发票 pdf 地址=PDF格式下载地址
                                invoice.setInvoicePdfUrl(addInvoiceVO.getPdfUrl());
                                //发票详情地址=OFD格式下载地址
                                invoice.setInvoiceJpgUrl(addInvoiceVO.getOfdUrl());
                                //ofdUrl=XML格式下载地址
                                invoice.setcOfdUrl(addInvoiceVO.getXmlUrl());
                                invoice.setState(2);
                                invoiceMapper.insertInvoice(invoice);
                                billInfoR.setState(2);
                                billInfoMapper.updateById(billInfoR);
                            }
                            // 返回数据
                            response.put("data", invoice);
                        } else {
                            log.error("【金四服务类】【金财数科】【通用查询接口】API请求异常，billInfo未查询到，requestId={}。", requestId);
                            return new HXResponse("查询错误！");
                        }
                    }
                } else if (WebServiceConstant.FPEWMXZ.equals(finalServiceId)) {
                    // 获取发票下载地址
                    cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                    String ewmUrl = json.getOrDefault("ewmUrl", "").toString();
                    String pdfUrl = json.getOrDefault("pdfUrl", "").toString();
                    String ofdUrl = json.getOrDefault("ofdUrl", "").toString();
                    String xmlUrl = json.getOrDefault("xmlUrl", "").toString();
                    if (StrUtil.isNotEmpty(requestId)) {
                        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
                        invoiceQueryWrapper.eq("out_trade_orderno", requestId);
                        Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                        if (BeanUtil.isNotEmpty(invoice)) {
                            invoice.setInvoicePdfUrl(pdfUrl);
                            invoice.setcOfdUrl(ofdUrl);
                            invoiceMapper.updateInvoice(invoice);
                        }
                    }
                    // TODO: 2023/3/29 返回数据处理
                } else if (WebServiceConstant.ADD_RED_INVOICE.equals(finalServiceId)) {
                    // 查找原发票信息
                    AddRedInvoiceTWOVO addRedInvoiceVO = BeanUtil.copyProperties(data, AddRedInvoiceTWOVO.class);
                    QueryWrapper<BillInfo> billInfoQueryWrapper = new QueryWrapper<>();
                    billInfoQueryWrapper.eq("fpqqlsh", requestId);
                    BillInfo billInfoR = billInfoMapper.selectOne(billInfoQueryWrapper);
                    if (billInfoR != null) {
//                        return AjaxResult.error("未查询到原发票信息");
                        // 根据billInfo获得原发票号码
                        QueryWrapper<BillInfo> originBillInfoWrapper = new QueryWrapper<>();
                        originBillInfoWrapper.eq("origin_fphm", billInfoR.getOriginFphm());
                        BillInfo originBillInfo = billInfoMapper.selectOne(originBillInfoWrapper);
                        if (originBillInfo != null) {
//                        return AjaxResult.error("未查询到原发票信息");
                            // 查找原发票信息
                            Invoice originInvoice = invoiceMapper.selectInvoiceByBillInfoId(originBillInfo.getId());
                            Invoice invoice = BeanUtil.copyProperties(originInvoice, Invoice.class);
                            invoice.setFphm(addRedInvoiceVO.getFphm());
                            invoice.setBillInfoId(billInfo.getId());
                            invoice.setSystemOrderno(billInfo.getSystemOrderno());
                            invoice.setOutTradeOrderno(billInfo.getOutTradeOrderno());
                            invoice.setFpqqlsh(billInfo.getFpqqlsh());
                            invoice.setKprq(DateUtil.parse(addRedInvoiceVO.getKprq()));
                            invoice.setZzfpdm(addRedInvoiceVO.getZzfpdm());
                            invoice.setZzfphm(addRedInvoiceVO.getZzfphm());
                            //二维码=二维码下载地址
                            invoice.setQrCode(addRedInvoiceVO.getEwmUrl());
                            //发票 pdf 地址=PDF格式下载地址
                            invoice.setInvoicePdfUrl(addRedInvoiceVO.getPdfUrl());
                            //发票详情地址=OFD格式下载地址
                            invoice.setInvoiceJpgUrl(addRedInvoiceVO.getOfdUrl());
                            //ofdUrl=XML格式下载地址
                            invoice.setcOfdUrl(addRedInvoiceVO.getXmlUrl());
                            invoice.setState(2);
                            invoiceMapper.insertInvoice(invoice);
                            billInfoR.setState(2);
                            billInfoMapper.updateById(billInfoR);

                            response.put("data", invoice);
                        }
                    }
                }

                else if (WebServiceConstant.KSHC.equals(finalServiceId)) {
                    // 快速冲红
                    // TODO: 后期存库
//                    KschVO kschVO = BeanUtil.copyProperties(data,KschVO.class);
//                    InvoiceAllKschVO invoiceAllKschVO = BeanUtil.copyProperties(kschVO,InvoiceAllKschVO.class);

                }else if (WebServiceConstant.SQHZFPXXQRD.equals(finalServiceId)) {
                    // 申请红字信息表
                    // TODO: 后期存库
                }else if (WebServiceConstant.CXHZFPXXQRD.equals(finalServiceId)) {
                    // 查询红字信息表

                    RedInvoiceQueryAllTWOVO redInvoiceQueryAllTWOVO = BeanUtil.copyProperties(data, RedInvoiceQueryAllTWOVO.class);
                    // 返回报文转换
                    List<Redinfo> resultDownload = parseRedINFO(redInvoiceQueryAllTWOVO);
                    // TODO: 2023/4/6 数据存储
                    response.put("data", resultDownload);
                }else if (WebServiceConstant.SHHZFPXXQRD.equals(finalServiceId)) {
                    // 审核红字信息表
                    // TODO: 后期存库
                }else if (WebServiceConstant.QDFPWJHQ.equals(finalServiceId)) {
                    // 审核红字信息表
                    // TODO: 全电发票文件获取
                }
                return response;
            } else {

                return new HXResponse(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【通用查询接口】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("通用查询接口异常");
        }

    }

    /**
     * 数科报文=》简税报文转换
     * @param redInvoiceQueryAllTWOVO
     * @return
     */
    private List<Redinfo> parseRedINFO(RedInvoiceQueryAllTWOVO redInvoiceQueryAllTWOVO) {
        List<Redinfo> redinfos = new ArrayList<>();

        // 页数
        int pageNumber = redInvoiceQueryAllTWOVO.getPageNumber();
        // 每页条数
        int pageSize = redInvoiceQueryAllTWOVO.getPageSize();
        // 总条数
        int total = redInvoiceQueryAllTWOVO.getTotal();;
        //发票集合
        List<RedInvoiceQueryTWOVO> redInvoiceQueryTWOVOS = redInvoiceQueryAllTWOVO.getFpList();

        for (RedInvoiceQueryTWOVO redInvoiceQueryTWOVO : redInvoiceQueryTWOVOS) {

            RedinfoCopyVO redinfoVO = BeanUtil.copyProperties(redInvoiceQueryTWOVO,RedinfoCopyVO.class);

            Redinfo redinfo = BeanUtil.copyProperties(JSONUtil.parseObj(redinfoVO),Redinfo.class);

            // TODO: 2023/4/6 明细接口数科还没对
            // redinfo.setRedinfodetailList(null);

            redinfos.add(redinfo);
        }

        return redinfos;
    }


    /**
     * 发票批量查询
     *
     * @param billInfo
     * @param byWhat
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse batchQueryInvoices(BillInfo billInfo, String byWhat, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse scopeQueryInvoices(JSONObject queryJson, Companyservice companyservice) {
        return null;
    }

    /**
     * 红字信息表上传
     */
    @Override
    public HXResponse uploadRedInfo(Redinfo redinfo, Companyservice companyservice) {

        // 前置处理    redinfo.setCompanyId(companyservice.getCompanyid());
        redinfo.setSystemOrderno(IdUtils.randomSystemOrderno());
        if (StringUtils.isEmpty(redinfo.getOutTradeOrderno())) {
            // 把 outTradeOrderno作为用户的申请单号
            throw new JianshuiParamErrorException(ErrorCode.EMPTY_REDINFO_NO, companyservice, "invoice");
        }
        redinfo.setOutTradeOrderno(redinfo.getOutTradeOrderno());
        redinfo.setFpqqlsh(redinfo.getSystemOrderno());
        redinfo.setRedInfoStatus("0");
        redinfo.setSellerName(companyservice.getSellername());
        redinfo.setSellerTaxnum(companyservice.getSellertax());
        redinfo.setBillInputTime(TimeUtil.dateFormat(new Date(), "yyyyMMddHHmmss"));
        List<Redinfodetail> redinfodetailList = redinfo.getRedinfodetailList();
        BigDecimal taxfreeamt = new BigDecimal(0); // 不含税金额
        BigDecimal tax = new BigDecimal(0); // 税额
        for (Redinfodetail detail : redinfodetailList) {
            taxfreeamt = taxfreeamt.add(detail.getTaxfreeamt());
            tax = tax.add(detail.getTax());
        }
        redinfo.setTax(tax);
        redinfo.setTaxfreeamt(taxfreeamt);
        redinfo.setTaxamt(tax.add(taxfreeamt));
        redinfoMapper.insertRedinfo(redinfo);
        int index = 0;

        String spbm = "";
        for (Redinfodetail detail : redinfodetailList) {
            detail.setBillno(redinfo.getRedInfoNo());
            detail.setRedinfoId(redinfo.getId());
            detail.setIndex(++index);
            detail.setBillno(redinfo.getRedInfoNo());
            taxfreeamt = taxfreeamt.add(detail.getTaxfreeamt());
            tax = tax.add(detail.getTax());

            // 商品编码
            spbm = detail.getSpbm();
        }

        redinfoMapper.batchRedinfodetail(redinfodetailList);


        // 金财数科数据处理 start
        // 查询用户登记参数
        QueryWrapper<InvoiceAllYhdj> yhdjQueryWrapper = new QueryWrapper<>();
        yhdjQueryWrapper.eq("nsrsbh", companyservice.getSellertax());
        yhdjQueryWrapper.eq("identity", companyservice.getIdentity());
        InvoiceAllYhdj invoiceAllYhdj = yhdjMapper.selectOne(yhdjQueryWrapper);

        if (BeanUtil.isEmpty(invoiceAllYhdj)) {
            return new HXResponse("用户未登记！");
        }

        SqhzTwoDTO sqhzDTO = BeanUtil.copyProperties(redinfo,SqhzTwoDTO.class);
        sqhzDTO.setAsync("true");
        sqhzDTO.setBsrysfzjhm(invoiceAllYhdj.getBsrysfzjhm());
        sqhzDTO.setDqbm(invoiceAllYhdj.getDqbm());
        sqhzDTO.setNsrsbh(invoiceAllYhdj.getNsrsbh());
        ValidateUtils.validate(sqhzDTO);

        SqhzJsonDataTwoDTO sqhzJsonDataTwoDTO = BeanUtil.copyProperties(redinfo,SqhzJsonDataTwoDTO.class);
        ValidateUtils.validate(sqhzJsonDataTwoDTO);

        List<SqhzJsonDataDetailTwoDTO> sqhzJsonDataDetailTwoDTOS = BeanUtil.copyToList(redinfo.getRedinfodetailList(),SqhzJsonDataDetailTwoDTO.class);
        for (SqhzJsonDataDetailTwoDTO sqhzJsonDataDetailTwoDTO : sqhzJsonDataDetailTwoDTOS) {
            ValidateUtils.validate(sqhzJsonDataDetailTwoDTO);
        }
        sqhzJsonDataTwoDTO.setHzqrxxmxlist(sqhzJsonDataDetailTwoDTOS);
        sqhzDTO.setJsonData(sqhzJsonDataTwoDTO);

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.SQHZFPXXQRD, WebServiceConstant.URL, sqhzDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.SQHZFPXXQRD);
                allApiLog.setSendMsg(sqhzDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);


                HXResponse response = new HXResponse("0000", "申请成功");
                response.put("queryid",requestId);
                return response;

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【申请红字信息表】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("通用查询接口异常");

        }

        /*if (!StringUtils.equals("0000", retcode)) {
            redinfo.setRedInfoStatus("2");
            redinfo.setRedInfoMessage(retmsg);
            redinfoMapper.updateRedinfo(redinfo);
            return new HXResponse(retmsg);
        }

        redinfo.setRedInfoStatus("1");
        redinfo.setRedInfoMessage(retmsg);
        redinfoMapper.updateRedinfo(redinfo);
        return new HXResponse(retmsg);*/
    }

    @Override
    public AjaxResult queryRedInfo(Redinfo redinfo, Companyservice companyservice) {
        return null;
    }

    /**
     * 红字信息表下载
     */
    @Override
    public HXResponse downloadRedInfo(DownloadRedInfoDTO downloadRedInfoDTO, Companyservice companyservice) {

        // 查找之前的红票
        Redinfo redinfo = new Redinfo();
        redinfo.setRedInfoNo(downloadRedInfoDTO.getBillInfoNo());
        redinfo.setCompanyId(companyservice.getCompanyid());
        QueryWrapper<Redinfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getInvoiceLine())) {
            queryWrapper.eq("invoice_type", downloadRedInfoDTO.getInvoiceLine());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getBuyerTaxNo())) {
            queryWrapper.eq("buyer_taxnum", downloadRedInfoDTO.getBuyerTaxNo());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getExtensionNumber())) {
            queryWrapper.eq("fjh", downloadRedInfoDTO.getExtensionNumber());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getTerminalNumber())) {
            queryWrapper.eq("terminal_number", downloadRedInfoDTO.getTerminalNumber());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getBillTimeBegin())) {
            queryWrapper.ge("bill_input_time", downloadRedInfoDTO.getBillTimeBegin());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getBillTimeEnd())) {
            queryWrapper.le("bill_input_time", downloadRedInfoDTO.getBillTimeEnd());
        }
        if (StringUtils.isNotEmpty(downloadRedInfoDTO.getBillNo())) {
            queryWrapper.le("out_trade_orderno", downloadRedInfoDTO.getBillNo());
        }
        queryWrapper.orderByDesc("id");
        queryWrapper.last(" limit 1 ");
        Redinfo redInfoResult = redinfoMapper.selectOne(queryWrapper);
        if (redInfoResult == null) {
            HXResponse response = new HXResponse("9999", "未查到指定红字信息");
            return response;
        }

        // TODO: 组装进数科需要的报文。 待处理。

        // 查询用户登记参数
        QueryWrapper<InvoiceAllYhdj> yhdjQueryWrapper = new QueryWrapper<>();
        yhdjQueryWrapper.eq("nsrsbh", companyservice.getSellertax());
        yhdjQueryWrapper.eq("identity", companyservice.getIdentity());
        InvoiceAllYhdj invoiceAllYhdj = yhdjMapper.selectOne(yhdjQueryWrapper);

        if (BeanUtil.isEmpty(invoiceAllYhdj)) {
            return new HXResponse("用户未登记！");
        }

        // 这里直接用传入的报文进行转换
        CxhzTwoDTO cxhzDTO = BeanUtil.copyProperties(downloadRedInfoDTO,CxhzTwoDTO.class);
        cxhzDTO.setAsync("true");
        cxhzDTO.setNsrsbh(invoiceAllYhdj.getNsrsbh());
        cxhzDTO.setDqbm(invoiceAllYhdj.getDqbm());

        CxhzJsonDataTwoDTO cxhzJsonDataDTO = BeanUtil.copyProperties(downloadRedInfoDTO,CxhzJsonDataTwoDTO.class);

        ValidateUtils.validate(cxhzDTO);
        ValidateUtils.validate(cxhzJsonDataDTO);

        cxhzDTO.setJsonData(cxhzJsonDataDTO);


        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.CXHZFPXXQRD, WebServiceConstant.URL, cxhzDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }

                // TODO: 2023/4/3 数据库存储：根据业务调整


                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.CXHZFPXXQRD);
                allApiLog.setSendMsg(cxhzDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

                HXResponse response = new HXResponse("0000", "申请成功");
                response.put("queryid",requestId);
                return response;

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【查询红字信息表】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("查询红字信息表接口异常");

        }


    }


    @Override
    public HXResponse deprecateQueryInvoice(DeprecateQueryInvoiceDTO invoice, Companyservice companyservice) {
        return null;
    }


    /**
     * 打印机查询
     *
     * @param queryPrinterDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse queryPrinter(QueryPrinterDTO queryPrinterDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse pushData(BillInfo billInfo, Companyservice companyservice) {
        return null;
    }

    /**
     * 发票打印
     *
     * @param printDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse batchPrint(PrintDTO printDTO, Companyservice companyservice) {

        return null;

    }

    @Override
    public AjaxResult syncStockInfo(Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse signInvoice(SignESealDTO signESealDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse createESeal(CreateESealDTO createESealDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse registerESeal(RegisterESealDTO createESealDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public AjaxResult SummaryReport(SummaryReportQueryDTO summaryReportQueryDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public Object callback(HttpServletRequest request) {
        return null;
    }


    /**
     * 简税转换总部控制台发票类型
     *
     * @param invoiceType
     * @return java.lang.Integer
     * @author dxk
     * @date 2022/6/28 20:17
     */
    public static Integer CovertInvoiceType(String invoiceType) {

        /**
         * 发票种类 invoice_type（ p电子增值税普通发票 c增值税普通发票 s 增值税专用发票 e 收购发票 f 收购发票 r增值税普通发票）
         */
        if (StrUtil.isEmpty(invoiceType)) {
            return -1;
        }
        if ("p".equals(invoiceType) || "c".equals(invoiceType) || "e".equals(invoiceType) || "f".equals(invoiceType) || "r".equals(invoiceType)) {
            return 2;
        } else if ("s".equals(invoiceType)) {
            return 0;
        }

        return -1;
    }

    /**
     * 总部控制台转简税发票类型
     *
     * @param invoiceType
     * @return java.lang.String
     * @author dxk
     * @date 2022/6/29 17:12
     */
    public static String CovertInvoiceTypeReverse(String invoiceType) {

        if (invoiceType.equals("2")) {
            return "p";
        } else if (invoiceType.equals("0")) {
            return "s";
        }
        return "";
    }




    /** 金财数科新增接口 **/

    @Override
    public Object addCallback(HttpServletRequest request) {
        return null;
    }

    @Override
    public Object decryptCallback(HttpServletRequest request) {
        return null;
    }




    @Override
    public HXResponse getFileUrl(InvoiceAllFileAcquisitionTWODTO invoiceAllFileAcquisitionTWODTO, Companyservice companyservice) {

        FileAcquisitionTwoDTO fileAcquisitionDTO = BeanUtil.copyProperties(invoiceAllFileAcquisitionTWODTO, FileAcquisitionTwoDTO.class);
        ValidateUtils.validate(fileAcquisitionDTO);

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.FPEWMXZ, WebServiceConstant.URL, fileAcquisitionDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.FPEWMXZ);
                allApiLog.setSendMsg(fileAcquisitionDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【获取发票下载地址】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("获取发票下载地址错误！");

        }

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    @Override
    public HXResponse getFileAcquisitionOn(InvoiceAllFileAcquisitionOnTWODTO invoiceAllFileAcquisitionOnTWODTO, Companyservice companyservice) {
        FileAcquisitionOnTwoDTO fileAcquisitionOnDTO = BeanUtil.copyProperties(invoiceAllFileAcquisitionOnTWODTO, FileAcquisitionOnTwoDTO.class);
        FileAcquisitionOnDetailTwoDTO fileAcquisitionOnDetailDTO = BeanUtil.copyProperties(invoiceAllFileAcquisitionOnTWODTO.getJsonData(),FileAcquisitionOnDetailTwoDTO.class);
        fileAcquisitionOnDTO.setJsonData(fileAcquisitionOnDetailDTO);
        ValidateUtils.validate(fileAcquisitionOnDTO);
        ValidateUtils.validate(fileAcquisitionOnDetailDTO);

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.QDFPWJHQ, WebServiceConstant.URL, fileAcquisitionOnDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.QDFPWJHQ);
                allApiLog.setSendMsg(fileAcquisitionOnDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【全电安排文件获取】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("全电发票文件获取错误！");

        }

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    @Override
    public HXResponse qrcode(JSONObject decryptResult, Companyservice companyservice) {
       cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.QRCODE, WebServiceConstant.URL, decryptResult, companyservice);
            // TODO: 2022/12/11 返回处理 VO整理，数据存储。

            String code   = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            // TODO-kk: 2023/1/16 数据存储再整下
            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }

                HXResponse response = new HXResponse("0000", "同步成功",json);
                return response;
            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("获取二维码错误！");

        }

        // TODO 处理日志
//        log.info("【金四服务类】【金财数科】【获取二维码】API请求成功，外部报文返回code。返回信息:{}", result);

//        return AjaxResult.success(result);
    }

    @Override
    public HXResponse query(JSONObject decryptResult, Companyservice companyservice) {
       cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.QUERY, WebServiceConstant.URL, decryptResult, companyservice);
            // TODO: 2022/12/11 返回处理 VO整理，数据存储。
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("发票查询错误");

        }

        // TODO 处理日志

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    @Override
    public HXResponse getPrintXML(JSONObject decryptResult, Companyservice companyservice) {
        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.GET_PRINT_XML, WebServiceConstant.URL, decryptResult, companyservice);
            // TODO: 2022/12/11 返回处理 VO整理，数据存储。
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("获取二维码错误！");

        }

        // TODO 处理日志

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    @Override
    public HXResponse issueFastRedInvoice(InvoiceAllKshcTWODTO invoiceAllKshcDTO, Companyservice companyservice) {
        KshcTwoDTO kshcDTO = BeanUtil.copyProperties(invoiceAllKshcDTO, KshcTwoDTO.class);
        ValidateUtils.validate(kshcDTO);
        ValidateUtils.validate(kshcDTO.getJsonData());

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.KSHC, WebServiceConstant.URL, kshcDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.KSHC);
                allApiLog.setSendMsg(kshcDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【快速红冲】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("快速红冲错误！");

        }

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    @Override
    public HXResponse invoiceStatic(JSONObject decryptResult, Companyservice companyservice) {
        // com.alibaba.fastjson.JSONObject jsonObj = requestBody.getJSONObject("jsonData");
        // if (jsonObj == null) {
        //     return AjaxResult.error(ErrorCode.INVOICE_NOT_EXISTS);
        // }

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.INVOICE_STATIC, WebServiceConstant.URL, decryptResult, companyservice);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("发票统计错误！");
        }

        // 处理请求
        if (!StringUtils.equals("0000", result.getStr("code"))) {
            log.error("【金四服务类】【金财数科】【获取二维码】API请求异常，外部报文返回code非0000。返回信息:{}", result);
            return new HXResponse(result.getStr("message"));
        }

        cn.hutool.json.JSONObject data = result.getJSONObject("data");
        if (data == null) {
            return new HXResponse("发票统计错误！");
        }

        log.info("【金四服务类】【金财数科】【蓝字统计】API请求成功，返回信息:{}", result);

        // String requestId = data.getStr("requestId");

        HXResponse response = new HXResponse("0000", "同步成功",data);
        return response;
    }

    @Override
    public HXResponse auditRedInfo(InvoiceAllShhzTWODTO invoiceAllShhzTWODTO, Companyservice companyservice) {
        // TODO: 2023/3/16 外部报文转数科校验

        ShhzTwoDTO shhzDTO = BeanUtil.copyProperties(invoiceAllShhzTWODTO,ShhzTwoDTO.class);
        ValidateUtils.validate(shhzDTO);

        ShhzJsonDataTwoDTO shhzJsonDataDTO = BeanUtil.copyProperties(shhzDTO.getJsonData(),ShhzJsonDataTwoDTO.class);
        ValidateUtils.validate(shhzJsonDataDTO);

        shhzDTO.setJsonData(shhzJsonDataDTO);


        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.SHHZFPXXQRD, WebServiceConstant.URL, shhzDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.SHHZFPXXQRD);
                allApiLog.setSendMsg(shhzDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【审核红字信息表】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("审核红字信息表错误！");

        }

        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }

    /**
     * 查询红字信息表明细
     * @param invoiceAllRedInvoiceDetailDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse queryRedInfoDetail(InvoiceAllRedInvoiceDetailTWODTO invoiceAllRedInvoiceDetailDTO, Companyservice companyservice) {

        RedInvoiceDetailTWODTO redInvoiceDetailDTO = BeanUtil.copyProperties(invoiceAllRedInvoiceDetailDTO, RedInvoiceDetailTWODTO.class);
        InvoiceAllRedInvoiceDetailJsonDataTWODTO redInvoiceDetailJsonDataDTO = BeanUtil.copyProperties(invoiceAllRedInvoiceDetailDTO.getJsonData(),InvoiceAllRedInvoiceDetailJsonDataTWODTO.class);
        redInvoiceDetailDTO.setJsonData(redInvoiceDetailJsonDataDTO);
        ValidateUtils.validate(redInvoiceDetailDTO);
        ValidateUtils.validate(redInvoiceDetailJsonDataDTO);

        cn.hutool.json.JSONObject result = null;
        try {
            result = ApiHttp.request(WebServiceConstant.CXHZFPXXQRDMX, WebServiceConstant.URL, redInvoiceDetailDTO, companyservice);

            String code = result.get("code") != null ? result.get("code").toString() : "";
            String msg = result.get("msg") != null ? result.get("msg").toString() : "";
            String data = result.get("data") != null ? result.get("data").toString() : "";

            if ("0000".equals(code) && StrUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                String requestId = json.getOrDefault("requestId", "").toString();
                if (StrUtil.isEmpty(requestId)) {
                    return new HXResponse(msg);
                }
                InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
                allApiLog.setUrl(WebServiceConstant.QDFPWJHQ);
                allApiLog.setSendMsg(redInvoiceDetailDTO.toString());
                allApiLog.setResultMsg(JSONUtil.toJsonStr(result));
                allApiLog.setCompany(companyservice.getSellertax());
                allApiLog.setIdentityId(companyservice.getIdentity());
                allApiLog.setRequestId(requestId);
                allApiLog.setCreateTime(new Date());
                allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            } else {
                return new HXResponse(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【金四服务类】【金财数科】【查询红字申请表明细】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
            return new HXResponse("查询红字申请表明细错误！");

        }
        HXResponse response = new HXResponse("0000", "同步成功",result);
        return response;
    }


    /**
     * 简税和金财数科 发票类型互换
     *
     * @param invoiceType 发票种类
     * @param jcsk2js     是否通过金财数科转换为简税
     * @return
     */
    private static String getInvoiceType(String invoiceType, boolean jcsk2js) {
        Map<String, String> map = new HashMap<>();
        map.put("10", "p"); //电子增值税普通发票 10
        map.put("04", "c"); //增值税普通发票 04
        map.put("01", "s"); //增值税专用发票 01
        map.put("08", "b"); //增值税电子专用发票 08
        map.put("87", "j"); //机动车发票 87
        map.put("88", "u"); //二手车发票 88
        map.put("82", "q"); //全电普票
        map.put("81", "q"); //全电专票
        if (jcsk2js) {
            String resp = map.get(invoiceType);
            return StringUtils.isNotEmpty(resp) ? resp : invoiceType;
        }

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue().equals(invoiceType)) {
                return entry.getKey();
            }
        }

        return invoiceType;
    }


}
