package com.jianshui.invoice.service.impl.api;

import ch.qos.logback.core.joran.spi.ElementPath;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.dxhy.order.protocol.invoke.DxhyInterfaceResponse;
import com.google.gson.Gson;
import com.jianshui.common.constant.Constants;
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.enums.InvoiceType;
import com.jianshui.common.exception.jianshui.JianshiSystemErrorException;
import com.jianshui.common.exception.jianshui.JianshuiParamErrorException;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.common.utils.*;
import com.jianshui.common.utils.http.HttpHelper;
import com.jianshui.common.utils.spring.SpringUtils;
import com.jianshui.common.utils.uuid.IdUtils;
import com.jianshui.framework.manager.AsyncManager;
import com.jianshui.invoice.constant.elephant.ElephantConstants;
import com.jianshui.invoice.constant.elephant.ElephantConstantsV6;
import com.jianshui.invoice.domain.*;
import com.jianshui.invoice.domain.dto.*;
import com.jianshui.invoice.domain.dto.api.*;
import com.jianshui.invoice.domain.dto.api.elephant.*;
import com.jianshui.invoice.domain.dto.api.elephant.sd.GetRpaAuthStatusDTO;
import com.jianshui.invoice.domain.dto.api.elephant.sd.HZQRDMXLIST;
import com.jianshui.invoice.domain.dto.api.elephant.sd.RedDownload;
import com.jianshui.invoice.domain.dto.api.elephant.sd.RedUpload;
import com.jianshui.invoice.domain.dto.api.jcsk.CxhzJsonDataTwoDTO;
import com.jianshui.invoice.domain.dto.api.jcsk.CxhzTwoDTO;
import com.jianshui.invoice.domain.ele.*;
import com.jianshui.invoice.domain.vo.InvoiceAllQycodeResultElEVO;
import com.jianshui.invoice.domain.vo.jcsk.*;
import com.jianshui.invoice.mapper.BillInfoMapper;
import com.jianshui.invoice.mapper.InvoiceFileMapper;
import com.jianshui.invoice.mapper.InvoiceMapper;
import com.jianshui.invoice.mapper.RedinfoMapper;
import com.jianshui.invoice.service.IBillInfoService;
import com.jianshui.invoice.service.IInvoiceApiService;
import com.jianshui.invoice.task.QueryInvoiceTask;
import com.jianshui.invoice.utils.BillInfoUtils;
import com.jianshui.invoice.utils.JsonCaseUtils;
import com.jianshui.invoice.utils.elephant.ElephantUtils;
import com.jianshui.queue.utils.RedisQueueUtil;
import com.jianshui.storage.domain.StorageUrlDTO;
import com.jianshui.storage.factory.StorageFactory;
import com.jianshui.storage.service.IStorageService;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.domain.InvoiceAllApiLog;
import com.jianshui.system.mapper.CompanyserviceMapper;
import com.jianshui.system.mapper.CompanyservicePropMapper;
import com.jianshui.system.mapper.InvoiceAllApiLogMapper;
import com.jianshui.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Lang;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销项实现
 * 字典配置：销项-服务公司-大象V6
 **/
@Component("elephantV6_invoice")
@Slf4j
public class ElephantInvoiceApiV6ServiceImpl implements IInvoiceApiService {

    @Autowired
    private BillInfoMapper billInfoMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Autowired
    private RedinfoMapper redinfoMapper;

    @Autowired
    private CompanyserviceMapper companyserviceMapper;

    @Autowired
    private CompanyservicePropMapper companyservicePropMapper;

    @Autowired
    private StorageFactory storageFactory;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IBillInfoService billInfoService;

    @Autowired
    private InvoiceAllApiLogMapper allApiLogMapper;

    @Autowired
    private InvoiceFileMapper invoiceFileMapper;

    private static String ELE_File_URL;

    static {
        Environment environment = SpringUtils.getBean(Environment.class);
        ELE_File_URL = environment.getProperty("elephant_invoice_file");
    }

    /**
     * 发票开具
     * v6
     * @param billInfo
     * @return
     */
    @Override
    public HXResponse addInvoice(BillInfo billInfo, Companyservice companyservice) throws IllegalAccessException, InstantiationException {


        // 预处理
        try {
            billInfo = BillInfoUtils.processBillInfo(billInfo, companyservice);
        } catch (JianshuiParamErrorException e) {
            return new HXResponse(e.getMessage());
        } catch (Exception e) {
            log.error("【销项】【大象发票】开票接口校验异常", e);
            return new HXResponse("格式校验失败，请检查报文");
        }
        log.info("billInfo信息：{}",JSONObject.toJSONString(billInfo));

        // 订单头信息
        DDTXX ddtxx = new DDTXX(billInfo);

        CompanyserviceProp companyserviceProp = companyservicePropMapper.selectPropByKey(companyservice.getCompanyid(), "account_show");

        if (companyserviceProp != null && "1".equals(companyserviceProp.getValue())){
            StringBuilder bz = new StringBuilder();
            if (StringUtils.isNotBlank(ddtxx.getBZ())){
                bz.append(ddtxx.getBZ()).append("\n");
            }
            String buyerBank = billInfo.getBuyerBank();
            String buyerAccount = billInfo.getBuyerAccount();
            String sellerAccount = billInfo.getSellerAccount();
            String sellerBank = billInfo.getSellerBank();


            bz.append("购方开户银行账号：");

            if (StringUtils.isNotBlank(buyerBank)) {
                bz.append("\t").append(buyerBank);
            }
            if (StringUtils.isNotBlank(buyerAccount)) {
                bz.append("\t").append(buyerAccount);
            }

            bz.append("\n");

            bz.append("销方开户银行账号：");

            if (StringUtils.isNotBlank(sellerBank)) {
                bz.append("\t").append(sellerBank);
            }
            if (StringUtils.isNotBlank(sellerAccount)) {
                bz.append("\t").append(sellerAccount);
            }

            log.info("备注信息：\n{}",bz.toString());
            ddtxx.setBZ(bz.toString());
        }




        // 订单票面信息
        DDPCXX ddpcxx = new DDPCXX();
        // ddpcxx.setKPFS("1"); // 设置开票方式为手动开票
        ddpcxx.setDDQQPCH(billInfo.getSystemOrderno());
        ddpcxx.setNSRSBH(billInfo.getSellerTaxnum());
        ddpcxx.setKPZD(billInfo.getTerminalNumber());
        String invioceType = billInfo.getInvoiceType();
        String fplxdm = ElephantUtils.transElephantType(invioceType, 1);
        ddpcxx.setFPLXDM(fplxdm);

        //kk 2023/9/15 V6数电新增
        // 标准开具
        Qdtxx qdtxx = BeanUtil.copyProperties(billInfo, Qdtxx.class);

        // 2023/9/22 特定要素类型代码处理
        qdtxx.setTdys(billInfo.getTdys());

        qdtxx.setQydm(billInfo.getDqbm());
        qdtxx.setFJYSLIST(billInfo.getFjyslist());// 附加要素列表
        qdtxx.setHWYSLIST(billInfo.getHwysList()); // 货物运输
        qdtxx.setBDCXSXX(billInfo.getBdcxsxxListt());// 不动产销售信息
        if(billInfo.getJzfwList() != null && billInfo.getJzfwList().size() > 0 ){
            qdtxx.setJZFWXX(billInfo.getJzfwList().get(0));// 建筑服务信息
        }
        if(billInfo.getBdczlxxList() != null && billInfo.getBdczlxxList().size() > 0 ){
            qdtxx.setBDCZLXX(billInfo.getBdczlxxList().get(0));// 不动产租赁信息
        }
//        qdtxx.setBDCZLXX(billInfo.getBdczlxxList()); //不动产租赁信息

        // 特殊票种地请求接口名转换
        String url = ElephantConstantsV6.ADD_INVOICE_LOCALHOST;
        if (CollectionUtils.isNotEmpty(qdtxx.getHWYSLIST())) {
            //GenerateQdHwysInvoice 货物运输
            url = ElephantConstantsV6.GENERATE_QD_HWYS_INVOICE;
        } else if (CollectionUtils.isNotEmpty(qdtxx.getBDCXSXX())) {
            // GenerateQdBdcxsInvoice 不动产销售信息
            url = ElephantConstantsV6.GENERATE_QD_BDCXS_INVOICE;
        } else if (BeanUtil.isNotEmpty(qdtxx.getJZFWXX())) {
            // GenerateQdJzfwInvoice 建筑服务信息
            url = ElephantConstantsV6.GENERATE_QD_JZFW_INVOICE;
        } else if (BeanUtil.isNotEmpty(qdtxx.getBDCZLXX())) {
            // GenerateQdBdczlInvoice 不动产租赁信息
            url = ElephantConstantsV6.GENERATE_QD_BDXZL_INVOICE;
        }

        // 开始处理详情
        List<BillDetail> details = billInfo.getBillDetailList();
        List<DDMXXX> ddmxxxList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            BillDetail detail = details.get(i);
            DDMXXX ddmxxx = new DDMXXX(billInfo, detail);
            ddmxxxList.add(ddmxxx);
        }

        // 开始封装请求报文
        ElephantInvoiceAddDTO elephantInvoiceAddDTO = new ElephantInvoiceAddDTO();
        elephantInvoiceAddDTO.setDDPCXX(ddpcxx);
        DDZXX ddzxx = new DDZXX();
        ddzxx.setDDTXX(ddtxx);
        ddzxx.setDDMXXX(ddmxxxList);
        // 全电头信息
        ddzxx.setQDTXX(qdtxx);
        List<DDZXX> ddzxxes = new ArrayList<>();
        ddzxxes.add(ddzxx);
        elephantInvoiceAddDTO.setDDZXX(ddzxxes);


        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(url, "", JSONUtil.parse(elephantInvoiceAddDTO), companyservice);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("【销项发票】【大象接口】【发票开具】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(elephantInvoiceAddDTO).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】发票开具请求结果{}", queryResult.toString());

        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        JSONObject result = queryResult.getJsonData();
        JSONObject contentJson = result;

        // 如果content不为空，判断状态代码
        if (contentJson != null) {
            String ztdm = contentJson.getString("ZTDM");
            if (!StringUtils.equals("0000", ztdm) && !StringUtils.equals("010000", ztdm)) {
                return new HXResponse(contentJson.getString("ZTXX"));
            }
        }

        billInfo.setState(20);
        billInfoMapper.updateBillInfo(billInfo);

        // 还需要单独调用下发票结果获取接口，获取订单结果
        JSONObject queryBody = new JSONObject();
        queryBody.put("NSRSBH", companyservice.getSellertax());
//        queryBody.put("DDQQPCH", billInfo.getSystemOrderno());
//        queryBody.put("FPLXDM", fplxdm);
//        queryBody.put("SFFHSBSJ", "0");

        // TODO: 2023/10/8 数电
        // 订单请求流水号
        queryBody.put("DDQQLSH", billInfo.getSystemOrderno());
        /*// 提取码
        queryBody.put("TQM", "0");
        // 订单号
        queryBody.put("DDH", "0");
        // 红字确认单编号
        queryBody.put("HZQRDBH", "0");
        // 版式文件(0:需要;1:不需要)
        queryBody.put("BSWJ", "0");
        // 订单日期起
        queryBody.put("DDRQQ", "0");
        // 订单日期止
        queryBody.put("DDRQZ", "0");*/
        // queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.ADD_INVOICE_RESULT, JSONUtil.parse(queryBody));
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(ElephantConstantsV6.ADD_INVOICE_RESULT_LOCALHOST, ElephantConstantsV6.ADD_INVOICE_RESULT_METHOD, JSONUtil.parse(queryBody), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【发票开具】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(elephantInvoiceAddDTO).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }

        log.info("【销项发票】【大象发票】发票开具请求拉取结果{}", queryResult.toString());
        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        // 如果content不为空，判断状态代码
        contentJson = queryResult.getJsonData();
        if (contentJson != null) {
            String ztdm = contentJson.getString("ZTDM");
//               021002    020111
            if (!StringUtils.equalsAny(ztdm, "020111", "020000", "010000","000000")) {
                // 开票失败
                if (StringUtils.equals("020002", ztdm)) {
                    billInfo.setState(22);
                    billInfoMapper.updateBillInfo(billInfo);
                }

                // kk: 2023/12/5 判断人脸识别的状态
                String DDFPZXX = contentJson.getString("DDFPZXX") != null ? contentJson.getString("DDFPZXX") : "";
                if(StrUtil.isNotEmpty(DDFPZXX)){
                    DDFPZXX ddfpzxx = BeanUtil.copyProperties(DDFPZXX,DDFPZXX.class);
                    if(ddfpzxx != null && ddfpzxx.getDDFPXX() != null && "03200".equals(ddfpzxx.getDDFPXX().getDDZT())){
                        return new HXResponse("E004",ddfpzxx.getDDFPXX().getDDZTXX() != null ? ddfpzxx.getDDFPXX().getDDZTXX():"发票开具失败，请确认是否人脸识别超期！");
                    }
                }

                return new HXResponse(contentJson.getString("ZTXX"));
            }

            // 如果全部开具成功
            if (StringUtils.equals("020000", ztdm)) {
                billInfo.setState(2);
                billInfoMapper.updateBillInfo(billInfo);
            }
        }

        // 定时拉取保存发票， TODO 处理开票中的问题
        AsyncManager.me().execute(new QueryInvoiceTask(billInfo, companyservice, this));

        // 数电的加入金财表
        InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
        allApiLog.setUrl(WebServiceConstant.LZFPKJ);
        allApiLog.setSendMsg("");
        allApiLog.setResultMsg("");
        allApiLog.setCompany(companyservice.getSellertax());
        allApiLog.setIdentityId(companyservice.getIdentity());
        allApiLog.setRequestId(billInfo.getSystemOrderno());
        allApiLog.setCreateTime(new Date());
        allApiLog.setCompanyName("大象V6");
        allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

        HXResponse response = new HXResponse("0000", "同步成功");
        response.put("fpqqlsh", billInfo.getSystemOrderno());
        return response;

    }


    /**
     * 发票失败重开接口
     *
     * @param
     */
    @Override
    public AjaxResult reInvoice(BillInfo billInfo, Companyservice companyservice) {
        return AjaxResult.error("系统维护中");
    }

    private static void debugLog(String msg, String uuid, Long timestamp) {
        Long now = System.currentTimeMillis();
        log.debug("【DebugLog:{}】耗时：{}，断点信息：{}", uuid, now - timestamp, msg);
    }

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

        // 获得当前时间戳
        Long timestamp = System.currentTimeMillis();
        String uuid = UUID.randomUUID().toString();
        debugLog("断点1", uuid, timestamp);
        QueryWrapper<BillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyservice.getCompanyid());
        if (StringUtils.isNotEmpty(billInfo.getFpqqlsh())) {
            queryWrapper.eq("fpqqlsh", billInfo.getFpqqlsh());
        } else if (StringUtils.isNotEmpty(billInfo.getOutTradeOrderno())) {
            queryWrapper.eq("out_trade_orderno", billInfo.getOutTradeOrderno());
        } else {
            HXResponse response = new HXResponse("9997", "订单号或流水号不能同时为空");
            return response;
        }

        queryWrapper.orderByDesc("id");
        queryWrapper.last(" limit 1");
        BillInfo originBillInfo = billInfoMapper.selectOne(queryWrapper);
        debugLog("断点2", uuid, timestamp);
        if (originBillInfo == null) {
            Invoice tempInvoice = new Invoice();
            tempInvoice.setInvoiceMsg("发票信息不存在");
            if (billInfo.getSystemOrderno() != null) {
                tempInvoice.setSystemOrderno(billInfo.getSystemOrderno());
            }
            if (billInfo.getOutTradeOrderno() != null) {
                tempInvoice.setOutTradeOrderno(billInfo.getOutTradeOrderno());
            }
            if (billInfo.getFpqqlsh() != null) {
                tempInvoice.setFpqqlsh(billInfo.getFpqqlsh());
            }
            HXResponse response = new HXResponse("9998", "发票信息不存在", tempInvoice);
            return response;
        }
        debugLog("断点3", uuid, timestamp);

        JSONObject queryBody = new JSONObject();
        queryBody.put("NSRSBH", companyservice.getSellertax());
        queryBody.put("DDQQLSH", originBillInfo.getSystemOrderno());
        queryBody.put("BSWJ", "0");
        debugLog("断点4", uuid, timestamp);

        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(ElephantConstantsV6.QUERY_INVOICE_LOCALHOST, ElephantConstantsV6.QUERY_INVOICE_METHOD, JSONUtil.parse(queryBody), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【发票开具】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(queryBody).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        debugLog("断点5", uuid, timestamp);

        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }
        debugLog("断点6", uuid, timestamp);

        // TODO 保存订单信息
        JSONObject contentJson = queryResult.getJsonData();
        debugLog("断点7", uuid, timestamp);

        ElephantInvoiceQueryResultDTO queryResultDTO = contentJson.toJavaObject(ElephantInvoiceQueryResultDTO.class);
        debugLog("断点8", uuid, timestamp);
        String ztdm = queryResultDTO.getZTDM();
        if (!StringUtils.equals("000000", ztdm) && !StringUtils.equals("002000", ztdm)) {
            Invoice tempInvoice = new Invoice();
            tempInvoice.setInvoiceMsg(queryResultDTO.getZTXX());
            if (billInfo.getSystemOrderno() != null) {
                tempInvoice.setSystemOrderno(billInfo.getSystemOrderno());
            }
            if (billInfo.getOutTradeOrderno() != null) {
                tempInvoice.setOutTradeOrderno(billInfo.getOutTradeOrderno());
            }
            if (billInfo.getFpqqlsh() != null) {
                tempInvoice.setFpqqlsh(billInfo.getFpqqlsh());
            }
            return new HXResponse(queryResultDTO.getZTXX(), tempInvoice);
        }
        debugLog("断点9", uuid, timestamp);
        List<DDFPZXX> ddfpzxxes = queryResultDTO.getDDFPZXX();
        if (ddfpzxxes.size() > 1) {
            HXResponse response = new HXResponse("9996", "一次只能查询一张发票");
            return response;
        }
        DDFPZXX ddfpzxx = ddfpzxxes.get(0);
        DDFPXX ddfpxx = ddfpzxx.getDDFPXX(); // 发票头信息
        // 查一下原来的发票
        debugLog("断点10", uuid, timestamp);
        Invoice invoice = invoiceMapper.selectBySystemOrderNo(companyservice.getCompanyid(), originBillInfo.getSystemOrderno());
        if (invoice == null) {
            invoice = new Invoice();
        }
        debugLog("断点11", uuid, timestamp);
        // invoice.setId(); // 主键ID */
        invoice.setBillInfoId(originBillInfo.getId()); //  bill_info表的bill_id */
        invoice.setCompanyId(companyservice.getCompanyid()); // "销方ID"
        invoice.setSystemOrderno(originBillInfo.getSystemOrderno()); // "系统订单号"
        invoice.setOutTradeOrderno(originBillInfo.getOutTradeOrderno()); // "客户订单号"
        invoice.setFpqqlsh(originBillInfo.getFpqqlsh()); // "流水号"
        invoice.setInvoiceType(originBillInfo.getInvoiceType()); // "发票种类"

        // 处理开票信息
        String ddzt = ddfpxx.getDDZT(); // 000000 成功，001000 订单处理成功 001999开票失败
        // 021002  020111

//        开票状态： 2 :开票完成（ 最终状态），其他状态分别为: 20:开票中; 21:开票成功签章中;22:开票失败;24: 开票成功签章失败;3: 发票已作废31

        if (StringUtils.equals(ddzt, "030000")) {
            invoice.setState(2); // "开票状态"
        } else if (StringUtils.equals(ddzt, "031999")) {
            invoice.setState(22); // "开票状态"
        } else if (StringUtils.equals(ddzt, "032000")) {
            invoice.setState(20); // "开票状态"


        } else if (StringUtils.equals(ddzt, "003000")) {
            invoice.setState(3); // "开票状态"
        } else if (StringUtils.equals(ddzt, "004000")) {
            invoice.setState(99); // "开票状态"
        } else if (StringUtils.equals(ddzt, "005000")) {
            invoice.setState(25); // "开票状态"
        } else if (StringUtils.equals(ddzt, "001999")) {
            invoice.setState(22); // "开票状态"
        } else {
            invoice.setState(20); // "开票状态"
        }

        // invoice.setState(); // "开票状态" TODO 处理开票状态
        invoice.setcInvoiceid("not used"); // 发票c_invoiceid */
        invoice.setFpdm(ddfpxx.getFPDM()); // "发票代码"
        invoice.setFphm(ddfpxx.getFPHM()); // "发票号码"
        try {
            String kprq = ddfpxx.getKPRQ();
            if (StringUtils.isNotEmpty(kprq)) {
                invoice.setKprq(DateUtils.parseDate(kprq, "yyyy-MM-dd HH:mm:ss")); // "开票日期", width = 30, dateFormat = "yyyy-MM-dd"
            }
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("【销项发票】【大象接口】【订单查询】 发票格式化日期错误。请求报文{}，大象返回报文{}，原始报文{}", queryBody.toJSONString(), queryResult.toString(), JSONObject.toJSONString(billInfo));
            throw new JianshuiServiceException("日期处理错误，请联系管理员！");
        }
        invoice.setBuyerName(ddfpxx.getGMFMC()); // "购方名称"
        invoice.setBuyerTaxnum(ddfpxx.getGMFSBH()); // "购方税号"
        invoice.setBuyerAddress(ddfpxx.getGMFDZ()); // "购方地址"
        invoice.setBuyerTelephone(ddfpxx.getGMFDH()); // "购方电话"
        invoice.setBuyerAccount(ddfpxx.getGMFYH() + ddfpxx.getGMFZH()); // "购方开户行及账户"
        invoice.setBuyerEmail(originBillInfo.getBuyerEmail()); // "购方邮箱"
        invoice.setBuyerPhone(originBillInfo.getBuyerPhone()); // "购方联系电话，可空"
        invoice.setSellerName(ddfpxx.getXHFMC()); // "销方名称"
        invoice.setSellerTaxnum(ddfpxx.getXHFSBH()); // "销方税号"
        invoice.setSellerAddress(ddfpxx.getXHFDZ()); // "销方地址"
        invoice.setSellerTelephone(ddfpxx.getXHFDH()); // "销方电话"
        invoice.setSellerAccount(ddfpxx.getXHFYH() + ddfpxx.getXHFZH()); // "销方开户行及账户"
        invoice.setMessage(ddfpxx.getBZ()); // "备注"
        invoice.setClerk(ddfpxx.getKPR()); // "开票人"
        invoice.setPayee(ddfpxx.getSKR()); // "收款人"
        invoice.setChecker(ddfpxx.getFHR()); // "复核人"
        invoice.setTaxfreeamt(new BigDecimal(ddfpxx.getHJJE())); // "不含税金额"
        invoice.setTax(new BigDecimal(ddfpxx.getHJSE())); // "税额"
        invoice.setTaxamt(new BigDecimal(ddfpxx.getJSHJ())); // "含税金额"
        invoice.setOriginFpdm(ddfpxx.getYFPDM()); // "原发票代码"
        invoice.setOriginFphm(ddfpxx.getYFPHM()); // "原发票号码"
        invoice.setJym(ddfpxx.getJYM()); // "校验码"
        invoice.setQrCode(ddfpxx.getDTM()); // "二维码" 动态码是二维码吗？
        invoice.setMachineCode(ddfpxx.getJQBH()); //  "税控设备号"
        // invoice.setCipherText(); // "发票密文"
        // invoice.setInvoicePdfUrl(); // "发票 pdf 地址"
        // invoice.setInvoiceJpgUrl(); // "发票详情地址"
        invoice.setInvoiceMsg(ddfpxx.getDDZTXX()); // "开票信息，成功或者失败的信息"
        invoice.setInvoiceResultMsg(ddfpxx.getDDZTXX()); // "结果信息"
        String oilFlag = "0";
        String qdbz = "0";
        if (StringUtils.equals(ddfpxx.getQDBZ(), "4")) {
            oilFlag = "1";
        }
        if (StringUtils.equals(ddfpxx.getQDBZ(), "1")) {
            qdbz = "1";
        }
        invoice.setProductOilFlag(oilFlag); // "成品油标志"
        invoice.setQdbz(qdbz); // "清单标志"
        // invoice.setcOfdUrl(); // "ofdUrl"
        invoice.setFjh(ddfpxx.getKPJH()); // "分机号"
        invoice.setTerminalNumber(ddfpxx.getKPZD()); // "终端号"
        invoice.setJqbh(ddfpxx.getKPZD());
        debugLog("断点12", uuid, timestamp);
        // 上传文件到oss
        String defaultStorage = configService.selectConfigByKey("default_storage");


        // 2023/12/4 存储文件流至数据库，方便迁移，提供文件下载接口。 start
        // invoiceFileMapper
        String fileId = IdUtils.randomUUID();
        String fileName = invoice.getFphm();

        if(ddfpxx.getPDFZJL() != null && StrUtil.isNotEmpty(ddfpxx.getPDFZJL())){
            InvoiceFile invoiceFile = new InvoiceFile();
            invoiceFile.setId(fileId);
            invoiceFile.setFileContent(ddfpxx.getPDFZJL());
            invoiceFile.setFileId(fileId);
            invoiceFile.setFileName(fileName);
            invoiceFile.setCreateTime(new Date());
            invoiceFile.setIdentity(companyservice.getIdentity());
            invoiceFile.setTax(companyservice.getSellertax());
            invoiceFileMapper.insertInvoiceFile(invoiceFile);

            // 2023/11/16  kk:上传OSS转下载地址关闭，改为直接返回大象的文件流
            invoice.setInvoicePdfUrl(ELE_File_URL + fileId);
        }
        // end


        /*if (StringUtils.isNotEmpty(defaultStorage) && StringUtils.isEmpty(invoice.getInvoicePdfUrl())) {
            try {
                IStorageService service = storageFactory.getStorageInstance(defaultStorage);
                String pdfzjl = ddfpxx.getPDFZJL();
                String zjllx = ddfpxx.getZJLLX();
                String pdfName = IdUtils.fastSimpleUUID() + "." + (StringUtils.equals(zjllx, "PDF") ? "pdf" : "ofd");
                if (StringUtils.isNotEmpty(pdfzjl)) {
                    byte[] pdfBytes = Base64.decode(pdfzjl);
                    String invoicePath = Constants.RESOURCE_PREFIX + "/invoice/" + pdfName;
                    AjaxResult uploadResult = service.upload(pdfBytes, invoicePath);
                    if (uploadResult.isSuccess()) {
                        StorageUrlDTO uploadResultDTO = (StorageUrlDTO) uploadResult.get("data");
                        String fileUrl = configService.selectConfigByKey("file_url");
                        if (StringUtils.isNotEmpty(fileUrl)) {
                            uploadResultDTO.setContentType(zjllx.toLowerCase());
                            String pdfUrl = fileUrl + "/" + Base64.encode(JSONObject.toJSONString(uploadResultDTO));
                            invoice.setInvoicePdfUrl(pdfUrl);
                            invoice.setInvoiceFileStorage(uploadResultDTO.getServiceProvider());
                            if (StringUtils.equals(zjllx, "OFD")) {
                                invoice.setcOfdUrl(pdfUrl);
                            }
                        }
                    }
                }
            } catch (JianshiSystemErrorException e) {
                e.printStackTrace();
            }
        }*/
        debugLog("断点13", uuid, timestamp);

        if (invoice.getId() != null) {
            invoiceMapper.updateInvoice(invoice);
        } else {
            invoiceMapper.insertInvoice(invoice);
        }
        debugLog("断点14", uuid, timestamp);
        // TODO 处理发票详情
        invoiceMapper.deleteInvoiceDetailByInvoiceId(invoice.getId()); // 删除发票明细
        List<InvoiceDetail> invoiceDetailList = new ArrayList<>();
        List<DDMXXX> ddmxxxList = ddfpzxx.getDDMXXX();
        for (int i = 0; i < ddmxxxList.size(); i++) {
            DDMXXX ddmxxx = ddmxxxList.get(i);
            InvoiceDetail tempDetail = new InvoiceDetail();
            // tempDetail.setId(); // id
            tempDetail.setInvoiceId(invoice.getId()); // 发票主键
            tempDetail.setIndex(Long.parseLong(StringUtils.isEmpty(ddmxxx.getXH()) ? "" : ddmxxx.getXH())); // 顺序
            tempDetail.setGoodName(StringUtils.isEmpty(ddmxxx.getXMMC()) ? "" : ddmxxx.getXMMC()); // 商品名称
            tempDetail.setNum(ddmxxx.getSPSL()); // 商品数量
            tempDetail.setPrice(new BigDecimal(StringUtils.isEmpty(ddmxxx.getDJ()) ? "0" : ddmxxx.getDJ())); // 商品单价
            tempDetail.setHsbz(Integer.parseInt(StringUtils.isEmpty(ddmxxx.getHSBZ()) ? "0" : ddmxxx.getHSBZ())); // 含税标志
            tempDetail.setTaxrate(new BigDecimal(StringUtils.isEmpty(ddmxxx.getSL()) ? "0" : ddmxxx.getSL())); // 税率
            tempDetail.setSpec(StringUtils.isEmpty(ddmxxx.getGGXH()) ? "" : ddmxxx.getGGXH()); // 规格型号
            tempDetail.setUnit(StringUtils.isEmpty(ddmxxx.getDW()) ? "" : ddmxxx.getDW()); // 单位
            tempDetail.setSpbm(StringUtils.isEmpty(ddmxxx.getSPBM()) ? "" : ddmxxx.getSPBM()); // 税收分类编码
            tempDetail.setBmbbh(ddfpxx.getBMBBBH()); // 商品编码版本号
            tempDetail.setZsbm(StringUtils.isEmpty(ddmxxx.getZXBM()) ? "" : ddmxxx.getZXBM()); // 自行编码
            tempDetail.setFphxz(Integer.parseInt(StringUtils.isEmpty(ddmxxx.getFPHXZ()) ? "0" : ddmxxx.getFPHXZ())); // 发票行性质
            tempDetail.setYhzcbs(Integer.parseInt(StringUtils.isEmpty(ddmxxx.getYHZCBS()) ? "0" : ddmxxx.getYHZCBS())); // 优惠政策标识
            tempDetail.setZzstsgl(StringUtils.isEmpty(ddmxxx.getZZSTSGL()) ? "" : ddmxxx.getZZSTSGL()); // 增值税特殊管理
            tempDetail.setLslbs(StringUtils.isEmpty(ddmxxx.getLSLBS()) ? "" : ddmxxx.getLSLBS()); // 零税率标识
            if (ddmxxx.getKCE() != null && !"".equals(ddmxxx.getKCE())) {
                tempDetail.setKce(new BigDecimal(ddmxxx.getKCE())); // 扣除额
            }
            tempDetail.setTax(new BigDecimal(ddmxxx.getSE())); // 税额
            if (tempDetail.getHsbz() == 0) {
                tempDetail.setTaxfreeamt(new BigDecimal(ddmxxx.getJE())); // 不含税金额
                // 计算含税金额
                tempDetail.setTaxamt(tempDetail.getTaxfreeamt().add(tempDetail.getTax()));
            } else {
                tempDetail.setTaxamt(new BigDecimal(ddmxxx.getJE())); // 含税金额
                tempDetail.setTaxfreeamt(tempDetail.getTaxamt().subtract(tempDetail.getTax())); // 计算不含税金额
            }
            // tempDetail.setTspz(ddmxxx.getts); // 特殊票种

            invoiceDetailList.add(tempDetail);
        }

        invoice.setInvoiceDetailList(invoiceDetailList);
        invoiceMapper.batchInvoiceDetail(invoiceDetailList);
        debugLog("断点15", uuid, timestamp);
        // 更新原来的billInfo
        originBillInfo.setState(invoice.getState());
        if (StringUtils.equals(originBillInfo.getKptype(), "2")) {
            originBillInfo.setOriginFpdm(invoice.getOriginFpdm());
            originBillInfo.setOriginFphm(invoice.getOriginFphm());
            // 如果是红票，开票状态为成功，还需要对原来的蓝票进行状态修改
            if (invoice.getState() == 2) {
                Invoice originInvoice = invoiceMapper.selectByFpdmFphm(companyservice.getCompanyid(), invoice.getOriginFpdm(), invoice.getOriginFphm());
                if (originInvoice != null) {
                    originBillInfo.setOriginSystemOrderno(originInvoice.getSystemOrderno());
                    QueryWrapper<BillInfo> myQueryWrapper = new QueryWrapper<>();
                    myQueryWrapper.eq("company_id", companyservice.getCompanyid());
                    myQueryWrapper.eq("system_orderno", originInvoice.getSystemOrderno());
                    BillInfo originBlueBillInfo = billInfoMapper.selectOne(myQueryWrapper);
                    if (originBlueBillInfo != null) {
                        originBlueBillInfo.setState(99);
                        billInfoMapper.updateBillInfo(originBlueBillInfo);
                    }
                    originInvoice.setState(99);
                    invoiceMapper.updateInvoice(originInvoice);
                }
            }
        }
        debugLog("断点16", uuid, timestamp);
        billInfoMapper.updateBillInfo(originBillInfo);
        debugLog("断点17", uuid, timestamp);
        try {
            if (billInfo != null && billInfo.getPushBillInfo() != null && billInfo.getPushBillInfo()) {
                log.info("推送订单信息,id:{}", originBillInfo.getId());
                billInfoService.pushBillInfo(originBillInfo.getId());
            }
        } catch (Exception e) {
            log.error("推送订单信息失败,id:{}", originBillInfo.getId(), e);
            e.printStackTrace();
        }
        debugLog("断点18", uuid, timestamp);
        HXResponse response = new HXResponse("0000", "查询成功", invoice);
        return response;
    }

    /**
     * 批量发票查询接口
     *
     * @param billInfo
     * @return
     */
    @Override
    public HXResponse batchQueryInvoices(BillInfo billInfo, String byWhat, Companyservice companyservice) {
        String fpqqlsh = billInfo.getFpqqlsh();
        String orderNo = billInfo.getOutTradeOrderno();
        List<Object> result = new ArrayList<>();
        List<BillInfo> queryBillInfo = new ArrayList<>();
        if (StringUtils.equals("fpqqlsh", byWhat)) {
            JSONArray fpqqlshs = JSONArray.parseArray(fpqqlsh);
            if (fpqqlshs == null) {
                fpqqlshs = new JSONArray();
                fpqqlshs.add(fpqqlsh);
            }
            fpqqlshs.forEach(i -> {
                BillInfo tempBillInfo = new BillInfo();
                tempBillInfo.setCompanyId(companyservice.getCompanyid());
                tempBillInfo.setFpqqlsh((String) i);
                queryBillInfo.add(tempBillInfo);
            });
        }

        if (StringUtils.equals("orderno", byWhat)) {
            JSONArray fpqqlshs = JSONArray.parseArray(orderNo);
            if (fpqqlshs == null) {
                fpqqlshs = new JSONArray();
                fpqqlshs.add(orderNo);
            }
            fpqqlshs.forEach(i -> {
                BillInfo tempBillInfo = new BillInfo();
                tempBillInfo.setCompanyId(companyservice.getCompanyid());
                tempBillInfo.setOutTradeOrderno((String) i);
                queryBillInfo.add(tempBillInfo);
            });
        }

        queryBillInfo.forEach(i -> {
            QueryBillInfoDTO queryBillInfoDTO = new QueryBillInfoDTO();
            BeanUtils.copyProperties(i, queryBillInfoDTO);
            HXResponse tempResult = this.queryInvoice(queryBillInfoDTO, companyservice);
            // if (tempResult.isSuccess()) {
            //     result.add(tempResult.getData());
            // }
            result.add(tempResult.getData());
        });

        return new HXResponse("0000", "查询成功", result);

    }


    /**
     * 范围查询接口
     *
     * @param queryJson
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse scopeQueryInvoices(JSONObject queryJson, Companyservice companyservice) {
        // 获取基本参数
        QueryWrapper<Invoice> queryWrapper = new QueryWrapper<>();
        String period = queryJson.getString("period"); // 开始结束时间，用&间隔
        if (StringUtils.isNotEmpty(period)) {
            List<String> periodSplit = Arrays.asList(period.split("&"));
            if (periodSplit != null && periodSplit.size() > 0) {
                // 订单开始日期
                if (periodSplit.get(0) != null) {
                    queryWrapper.ge("kprq", periodSplit.get(0));
                }
                // 订单截止日期
                if (periodSplit.get(1) != null) {
                    queryWrapper.le("kprq", periodSplit.get(0));
                }
            }
        }
        String buyername = queryJson.getString("buyername"); // 购方名称
        if (StringUtils.isNotEmpty(buyername)) {
            // buyername
            queryWrapper.eq("buyer_name", buyername);
        }
        String buyertaxno = queryJson.getString("buyertaxno"); // 购方taxno
        if (StringUtils.isNotEmpty(buyertaxno)) {
            queryWrapper.eq("buyer_taxnum", buyertaxno);
        }
        String fpdm = queryJson.getString("fpdm"); // 发票代码
        if (StringUtils.isNotEmpty(fpdm)) {
            queryWrapper.eq("fpdm", fpdm);
        }
        String fphm = queryJson.getString("fphm"); // 发票号码
        if (StringUtils.isNotEmpty(fphm)) {
            queryWrapper.eq("fphm", fphm);
        }

        // 开始查询数据库，invoice
        List<Invoice> invoices = invoiceMapper.selectList(queryWrapper);
        List<Object> result = new ArrayList<>();
        for (Invoice tempInvoice : invoices) {
            QueryBillInfoDTO tempBillInfo = new QueryBillInfoDTO();
            tempBillInfo.setFpqqlsh(tempInvoice.getFpqqlsh());
            HXResponse tempResult = this.queryInvoice(tempBillInfo, companyservice);
            result.add(tempResult.getData());
        }

        return new HXResponse("0000", "查询成功", result);

    }

    /**
     * 功能描述: 红字信息查询
     *
     * @param findRedInfo
     * @param companyservice
     * @return : java.lang.Object
     */
    @Override
    public EleNewMessage findRedInfo(FindRedInfo findRedInfo, Companyservice companyservice) {
        log.info("传入信息", JSONUtil.toJsonStr(findRedInfo));
        if (StringUtils.isEmpty(findRedInfo.getSQBQQPCH()) || StringUtils.isEmpty(findRedInfo.getNSRSBH())) {
            log.error("传入信息为空");
            EleNewMessage eleNewMessage = new EleNewMessage();
            eleNewMessage.setStatus("9999");
            eleNewMessage.setMessage("接口请求失败");
            return eleNewMessage;
        }
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.REDINFO_FIND_LOCALHOST, ElephantConstantsV6.REDINFO_FIND_METHOD, JSONUtil.parse(findRedInfo), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【红字信息表查询】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(findRedInfo).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        String data = dxhyInterfaceResponse.getData();
        cn.hutool.json.JSONObject dataStr = new cn.hutool.json.JSONObject(data);
        if ("000000".equals(dataStr.getStr("ZTDM"))) {
            Gson gson = new Gson();
            EleOuterMessage eleOuterMessage = gson.fromJson(data, EleOuterMessage.class);
            String inMsgInfo = "";
            List<HZSQDMessage> hzsqdxzzxx = eleOuterMessage.getHZSQDXZZXX();
            for (HZSQDMessage hzsqdMessage : hzsqdxzzxx) {
                hzsqdMessage.getHZSQDXZTXX().setZTDM(hzsqdMessage.getHZSQDXZTXX().getZTDM().substring(hzsqdMessage.getHZSQDXZTXX().getZTDM().length() - 4));
                inMsgInfo = hzsqdMessage.getHZSQDXZTXX().getZTXX();
                hzsqdMessage.getHZSQDXZTXX().setBillNo(findRedInfo.getSQBQQPCH());
            }
            EleNewMessage eleNewMessage = new EleNewMessage();
            BeanUtil.copyProperties(eleOuterMessage, eleNewMessage);
            eleNewMessage.setStatus(eleOuterMessage.getZTDM().substring(eleOuterMessage.getZTDM().length() - 4));
            if ("审核通过".equals(inMsgInfo)) {
                eleNewMessage.setMessage(eleOuterMessage.getZTXX());
                eleNewMessage.setData(eleOuterMessage.getHZSQDXZZXX());
                return eleNewMessage;
            } else {
                for (HZSQDMessage hzsqdMessage : hzsqdxzzxx) {
                    hzsqdMessage.getHZSQDXZTXX().setZTDM("1999");
                }
                eleNewMessage.setMessage(eleOuterMessage.getZTXX());
                eleNewMessage.setData(eleOuterMessage.getHZSQDXZZXX());
                return eleNewMessage;
            }
        } else {
            EleNewMessage eleNewMessage = new EleNewMessage();
            eleNewMessage.setStatus("9999");
            eleNewMessage.setMessage("接口请求失败");
            return eleNewMessage;
        }


    }

    /**
     * 生成动态二维码接口
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse generateDynamicCode(JSONObject decryptResult, Companyservice companyservice) {

        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.GEN_DYNAMIC_CODE_LOCALHOST, ElephantConstantsV6.GEN_DYNAMIC_CODE_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【生成动态二维码】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }

    @Override
    public HXResponse exportVehicleInvoice(JSONObject decryptResult, Companyservice companyservice) {
        return null;
    }

    /** 获取人脸识别结果*/
    @Override
    public HXResponse qrcodeResult(JSONObject decryptResult, Companyservice companyservice) {

        InvoiceAllQycodeResultDTO qycodeResultDTO = BeanUtil.copyProperties(decryptResult,InvoiceAllQycodeResultDTO.class);
        if(BeanUtil.isEmpty(qycodeResultDTO)){
            return new HXResponse("参数为空！");
        }

        // 报文组装
        GetRpaAuthStatusDTO getRpaAuthStatusDTO = new GetRpaAuthStatusDTO();
        getRpaAuthStatusDTO.setYhm(qycodeResultDTO.getYhm());
        getRpaAuthStatusDTO.setRzid(qycodeResultDTO.getRzid());
        getRpaAuthStatusDTO.setNsrsbh(qycodeResultDTO.getNsrsbh());

        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6
                    (ElephantConstantsV6.GET_RPA_AUTH_STATUS_LOCALHOST, ElephantConstantsV6.GET_RPA_AUTH_STATUS_METHOD, JSONUtil.parse(getRpaAuthStatusDTO), companyservice);


        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【获取人脸识别结果】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        // 返回结果处理
        HXResponse hxResponseT = parseResult(dxhyInterfaceResponse);
        if("000000".equals(hxResponseT.get("code")) && hxResponseT.get("data") != null  && !"".equals(hxResponseT.get("data"))){
            InvoiceAllQycodeResultElEVO qycodeResultVO = BeanUtil.copyProperties(JSONUtil.parse(hxResponseT.get("data")),InvoiceAllQycodeResultElEVO.class);
            HXResponse response = new HXResponse("0000", "请求成功", qycodeResultVO);
            return response;
        } else {
            return new HXResponse(hxResponseT.getMessage() != null ? hxResponseT.getMessage():"");
        }

    }

    @Override
    public void callBackAisino(InvoiceBack invoiceBack, String callBackUrl, String identity,Long id) {

    }

    /** 邮箱交付 */
    @Override
    public HXResponse mailDelivery(InvoiceMailDeliveryDTO mailDeliveryDTO, Companyservice companyservice) {

        ValidateUtils.validate(mailDeliveryDTO, "发票请求参数不能为空！");

        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(
                    ElephantConstantsV6.MAIL_DELIVERY_LOCALHOST, ElephantConstantsV6.MAIL_DELIVERY_METHOD, JSONUtil.parse(mailDeliveryDTO)
                    , companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【邮箱交付接口】请求异常，请求报文{}，销方信息{}", JSONUtil.parse(mailDeliveryDTO), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);

    }

    /**
     * 红字确认单列表查询（数电专用）
     */
    @Override
    public HXResponse queryRedConfirmationList(JSONObject decryptResult, Companyservice companyservice) {

        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.QUERY_RED_CONFIRMATION_LIST_LOCALHOST, ElephantConstantsV6.QUERY_RED_CONFIRMATION_LIST_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【红字确认单列表查询】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }


    /**
     * 红字确认单明细查询(数电专用)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse queryRedConfirmationItemList(JSONObject decryptResult, Companyservice companyservice) {

        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.QUERY_RED_CONFIRMATION_ITEM_LIST_LOCALHOST, ElephantConstantsV6.QUERY_RED_CONFIRMATION_ITEM_LIST_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【红字确认单明细查询】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }

    /**
     * 红字确认单申请(数电专用)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse redConfirmationApply(JSONObject decryptResult, Companyservice companyservice) {

        String fpdm = decryptResult.getString("lzfppzdm");
        decryptResult.put("lzfppzdm", InvoiceType.getEleCode(fpdm));
        // TODO kk:2024/1/8 红字申请表申请用的是01 02
        String lzfpdm = decryptResult.get("lzfppzdm") != null ? decryptResult.get("lzfppzdm").toString():"";
        if("001".equals(lzfpdm)){
            lzfpdm = "01";
        }else if("002".equals(lzfpdm)){
            lzfpdm = "02";
        }
        decryptResult.put("lzfppzdm", lzfpdm);

        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.RED_CONFIRMATION_LOCALHOST, ElephantConstantsV6.RED_CONFIRMATION_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【红字确认单申请】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }


    /**
     * 红字确认单确认接口
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse redConfirmationConfirm(JSONObject decryptResult, Companyservice companyservice) {

        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.RED_CONFIRMATION_CONFIRM_LOCALHOST, ElephantConstantsV6.RED_CONFIRMATION_CONFIRM_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【红字确认单确认接口】发票请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }

    /**
     * 数电登录接口(数电专用接口)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse rpaLogin(JSONObject decryptResult, Companyservice companyservice) {

        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.RPA_LOGIN_LOCALHOST, ElephantConstantsV6.RPA_LOGIN_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【数电登录接口】请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }


    /**
     * 数电实名认证状态查询接口(数电专用接口)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse getRpaAuthStatus(JSONObject decryptResult, Companyservice companyservice) {
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.GET_RPA_AUTH_STATUS_LOCALHOST, ElephantConstantsV6.GET_RPA_AUTH_STATUS_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【数电实名认证状态查询接口】请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }

    /**
     * 发票平台电子税局账号查询接口(数电专用接口)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse queryRpaTaxAccount(JSONObject decryptResult, Companyservice companyservice) {
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.QUERY_RPA_TAX_ACCOUNT_LOCALHOST, ElephantConstantsV6.QUERY_RPA_TAX_ACCOUNT_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【发票平台电子税局账号查询接口】请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }


    /**
     * 大象通用返回处理
     *
     * @param dxhyInterfaceResponse
     * @return
     */
    public HXResponse parseResult(DxhyInterfaceResponse dxhyInterfaceResponse) {

        if (BeanUtil.isEmpty(dxhyInterfaceResponse)) {
            return new HXResponse("9999", "接口请求失败！返回内容不存在！", "", false);
        }

        // 大象通用返回处理，返回简税HXResponse
        Object data = dxhyInterfaceResponse.getData() != null ? dxhyInterfaceResponse.getData() : "";
        String code = dxhyInterfaceResponse.getCode() != null ? dxhyInterfaceResponse.getCode() : "";

        if ("000000".equals(code)) {
            if (ObjUtil.isNotEmpty(data)) {
                cn.hutool.json.JSONObject dataJson = JSONUtil.parseObj(data);
                String ztdm = dataJson.get("ZTDM") != null ? dataJson.get("ZTDM").toString() : "";
                String ztxx = dataJson.get("ZTXX") != null ? dataJson.get("ZTXX").toString() : "";
                String dataTemp = dataJson.get("DATA") != null ? dataJson.get("DATA").toString() : "";

                if ("000000".equals(ztdm)) {
                    cn.hutool.json.JSONObject json = null;
                    if (StrUtil.isNotEmpty(dataTemp)) {
                        json = JSONUtil.parseObj(dataTemp);
                    } else {
                        json = JSONUtil.parseObj(data);
                    }
                    // 键值转小写
                    JSONObject lowerCaseJson = new JSONObject();
                    json.forEach((key, value) -> {
                        String lowerCaseKey = key.toLowerCase();
                        lowerCaseJson.put(lowerCaseKey, value);
                    });
                    return new HXResponse(code, "", lowerCaseJson, true);
                } else {
                    return new HXResponse(ztdm, ztxx, "", true);
                }
            }
        } else {
            return new HXResponse(code, "接口请求失败！", "", false);
        }

        return new HXResponse(code, "接口请求失败！", "", false);
    }



    /**
     * 申请/上传 红字发票
     *
     * @param redinfo
     */
    @Override
    public HXResponse uploadRedInfo(Redinfo redinfo, Companyservice companyservice) {

        // TODO: 2023/10/23 一步的红字上传接口


        // 处理redinfo
        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;
        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());
        }
        redinfoMapper.batchRedinfodetail(redinfodetailList);

        String fplxdm = "";
        String invioceType = redinfo.getInvoiceType();
        fplxdm = ElephantUtils.transElephantType(invioceType, 1);

        RedUpload redUpload = BeanUtil.copyProperties(redinfo, RedUpload.class);

        // 报文组装
        Invoice invoice = invoiceMapper.selectByFpdmFphm(companyservice.getCompanyid(), redinfo.getOriginFpdm(), redinfo.getOriginFphm());
        if (BeanUtil.isEmpty(invoice)) {
            return new HXResponse("009999", "未查询到原蓝字发票信息！");
        }
        // 蓝字发票信息补全
        redUpload.setLZHJJE(String.valueOf(invoice.getTaxfreeamt()));
        redUpload.setLZHJSE(String.valueOf(invoice.getTax()));
        redUpload.setLZFPPZDM(invoice.getInvoiceType());
        redUpload.setLZFPTDYSLXDM(invoice.getTdyslxdm());
        redUpload.setLZFPQDHM(invoice.getFphm());
        // TODO: 2023/9/22 是否纸质发票这里判断一下
        redUpload.setSFZZFPBZ("Y");

        List<InvoiceDetail> invoiceDetail = invoice.getInvoiceDetailList();
        if (CollectionUtils.isEmpty(invoiceDetail)) {
            return new HXResponse("009999", "未查询到原蓝字发票明细信息！");
        }

        List<HZQRDMXLIST> hzqrdmxlistList = new ArrayList<>();
        for (InvoiceDetail detail : invoiceDetail) {

            // 根据蓝字发票组装报文
            HZQRDMXLIST hzqrdmxlist = new HZQRDMXLIST();
            hzqrdmxlist.setLZMXXH(String.valueOf(detail.getIndex()));
            hzqrdmxlist.setXH(String.valueOf(detail.getIndex()));
            hzqrdmxlist.setSPHFWSSFLHBBM(detail.getSpbm());
            hzqrdmxlist.setXMMC(detail.getGoodName());
            hzqrdmxlist.setGGXH(detail.getSpec());
            hzqrdmxlist.setDW(detail.getUnit());
            hzqrdmxlist.setFPSPDJ(String.valueOf(detail.getPrice()));
            hzqrdmxlist.setFPSPSL(String.valueOf(detail.getNum()));
            hzqrdmxlist.setJE(String.valueOf(detail.getTaxfreeamt()));
            hzqrdmxlist.setSLV(String.valueOf(detail.getTaxrate()));
            hzqrdmxlist.setSE(String.valueOf(detail.getTax()));

            hzqrdmxlistList.add(hzqrdmxlist);
        }
        redUpload.setHZQRDMXLIST(hzqrdmxlistList);

        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.RED_CONFIRMATION_LOCALHOST, ElephantConstantsV6.RED_CONFIRMATION_METHOD, JSONUtil.parse(redUpload), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【红字确认单申请】发票请求异常，请求报文{}，销方信息{}", JSONUtil.toJsonStr(redUpload), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        // 组装通用报文
        AjaxResult queryResult = null;
        queryResult.put("code", dxhyInterfaceResponse.getCode());
        queryResult.put("data", dxhyInterfaceResponse.getData());
        queryResult.put("msg", dxhyInterfaceResponse.getMessage());


        log.info("【销项发票】【大象发票V6】红字信息表上传请求结果{}", queryResult.toString());

        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        Object contentObject = queryResult.getData();
        JSONObject contentJson = new JSONObject();
        // 如果是json array
        if (contentObject.getClass().getName().equals("com.alibaba.fastjson.JSONArray")) {
            JSONArray contentArray = (JSONArray) contentObject;
            contentJson = contentArray.getJSONObject(0);
        } else {
            contentJson = queryResult.getJsonData();
        }

        // TODO: 2023/10/23 处理回填字段

        // 外部状态代码
        String ztdm = contentJson.getString("ZTDM");
        if (StringUtils.equals("060111", ztdm) || StringUtils.equals("060001", ztdm)) {
            redinfo.setRedInfoStatus("0");
            redinfo.setRedInfoMessage(contentJson.getString("ZTXX"));
            redinfoMapper.updateRedinfo(redinfo);
            return new HXResponse("8888", "数据上传成功，请调用查询接口，查询审核状态！");
        }
        if (!StringUtils.equals("0000", ztdm)) {
            redinfo.setRedInfoStatus("2");
            redinfo.setRedInfoMessage(contentJson.getString("ZTXX"));
            redinfoMapper.updateRedinfo(redinfo);
            return new HXResponse(contentJson.getString("ZTXX"));
        }


        // HZSQDSCJG内部状态diamante
        JSONArray hzsqdscjg = contentJson.getJSONArray("HZSQDSCJG");
        String ztxx = "同步成功";
        ztdm = "0000";
        String queryId = "";
        for (int i = 0; i < hzsqdscjg.size(); i++) {
            JSONObject temp = hzsqdscjg.getJSONObject(i);
            QueryWrapper<Redinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("system_orderno", temp.getString("SQBSCQQLSH"));
            queryWrapper.orderByDesc("id");
            queryWrapper.last(" limit 1");
            Redinfo myRedinfo = redinfoMapper.selectOne(queryWrapper);
            if (myRedinfo != null) {
                String tempZtdm = temp.getString("ZTDM");
                if (StringUtils.equals(tempZtdm, "060000")) {
                    myRedinfo.setRedInfoStatus("1");
                    myRedinfo.setRedInfoMessage(temp.getString("ZTXX"));
                    ztxx = temp.getString("ZTXX");
                    ztdm = "0000";
                } else if (StringUtils.equals(tempZtdm, "060001")) {
                    myRedinfo.setRedInfoStatus("0");
                    myRedinfo.setRedInfoMessage(temp.getString("ZTXX"));
                    ztxx = temp.getString("ZTXX");
                    ztdm = "0000";
                } else {
                    myRedinfo.setRedInfoStatus("2");
                    myRedinfo.setRedInfoMessage(temp.getString("ZTXX"));
                    ztxx = temp.getString("ZTXX");
                    ztdm = "9999";
                }
                queryId = myRedinfo.getSystemOrderno();
                redinfoMapper.updateRedinfo(myRedinfo);
            }
        }

        // 存入金四关联日志表
        if("0000".equals(ztxx) && StrUtil.isNotEmpty(queryId)){
            InvoiceAllApiLog allApiLog = new InvoiceAllApiLog();
            allApiLog.setUrl(WebServiceConstant.SQHZFPXXQRD);
            allApiLog.setSendMsg("");
            // 添加对应uuid
            allApiLog.setResultMsg("");
            allApiLog.setCompany(companyservice.getSellertax());
            allApiLog.setIdentityId(companyservice.getIdentity());
            allApiLog.setRequestId(queryId);
            allApiLog.setCreateTime(new Date());
            allApiLog.setCompanyName("大象V6");
            allApiLogMapper.insertInvoiceAllApiLog(allApiLog);

            HXResponse response = new HXResponse("0000", "申请成功");
            response.put("queryid", queryId);
            return response;
        }else{
            return new HXResponse(ztxx);
        }

    }


    /**
     * 红字信息申请查询
     *
     * @param redinfo
     */
    @Override
    public AjaxResult queryRedInfo(Redinfo redinfo, Companyservice companyservice) {
        return AjaxResult.error("系统维护中");
    }

    /**
     * 红字信息表下载
     */
    @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;
        }

        String taxno = redInfoResult.getReqnsrsbh() == null ? companyservice.getSellertax() : redInfoResult.getReqnsrsbh();

        RedDownload redDownload = new RedDownload();
        redDownload.setNSRSBH(taxno);
        // UUID=申请单号
        redDownload.setUUID(downloadRedInfoDTO.getBillNo());
        // 信息表编号
        redDownload.setHZQRDBH(redinfo.getRedInfoNo());
        // 确认类型
        redDownload.setQRLX(downloadRedInfoDTO.getBillInfoNo());

        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.REDINFO_DOWNLOAD_LOCALHOST, ElephantConstantsV6.REDINFO_DOWNLOAD_METHOD, JSONUtil.parse(redDownload), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【红字信息表下载】发票请求异常，请求报文{}，销方信息{}", null, JSONObject.toJSONString(companyservice));
        }
        log.info("【销项发票】【大象发票】发票红字信息表下载请求结果{}", dxhyInterfaceResponse.toString());

        return parseResult(dxhyInterfaceResponse);
    }

    /**
     * 发票作废
     *
     * @param billInfo
     * @return AjaxResult
     */
    @Override
    public HXResponse deprecateInvoice(JSONObject billInfo, Companyservice companyservice) {

        // TODO-: 2022/10/7  发票作废，兼容支持通过代码、号码获取。现在必须要开票返回的流水号。
        // 查找原来的发票
        String fpqqlsh = billInfo.getString("fpqqlsh");
        String fpdm = billInfo.getString("fpdm");
        String fphm = billInfo.getString("fphm");

        // 发票查询
        Invoice invoice = null;
        if (StringUtils.isNotEmpty(fpqqlsh)) {
            invoice = invoiceMapper.selectBySystemOrderNo(companyservice.getCompanyid(), fpqqlsh);
        } else if (StringUtils.isNotEmpty(fpdm) && StringUtils.isNotEmpty(fphm)) {
            invoice = invoiceMapper.selectByFpdmFphm(companyservice.getCompanyid(), fpdm, fphm);
        } else {
            throw new JianshuiParamErrorException(ErrorCode.EMPTY_FPQQLSH, companyservice, "invoice");
        }

        //发票不存在
        if (invoice == null) {
            throw new JianshuiParamErrorException(ErrorCode.INVOICE_NOT_EXISTS, companyservice, "invoice");
        }

        // TODO 发票状态查询

        // 发起作废
        JSONObject queryBody = new JSONObject();
        queryBody.put("XHFSBH", companyservice.getSellertax()); // 销货方纳税人识别号
        queryBody.put("FPLXDM", ElephantUtils.transElephantType(invoice.getInvoiceType(), 1));
        queryBody.put("FPDM", invoice.getFpdm());
        queryBody.put("FPHM", invoice.getFphm());
        queryBody.put("FPQH", invoice.getFphm());
        queryBody.put("FPZH", invoice.getFphm());
        queryBody.put("ZFLX", "1");
        queryBody.put("ZFPCH", IdUtils.randomSystemOrderno());
        // AjaxResult queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.DEPRECATE_INVOICE, JSONUtil.parse(queryBody));
        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutToken(ElephantConstantsV6.DEPRECATE_INVOICE_LOCALHOST, ElephantConstantsV6.DEPRECATE_INVOICE_METHOD, JSONUtil.parse(queryBody), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【发票作废】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(queryBody).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】发票作废请求结果{}", queryResult.toString());

        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        // 处理返回报文
        JSONObject content = queryResult.getJsonData();
        String ztdm = content.getString("ZTDM");
        if (!StringUtils.equalsAny(ztdm, "040000")) {
            return new HXResponse(content.getString("ZTXX"));
        }
        // TODO 发票作废通过接口查询
        // // 获取作废状态
        // queryBody = new JSONObject();
        // queryBody.put("XHFSBH", companyservice.getSellertax()); // 销货方纳税人识别号
        // queryBody.put("FPDM", invoice.getFpdm());
        // queryBody.put("FPHM", invoice.getFphm());
        // // queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.DEPRECATE_INVOICE_RESULT, JSONUtil.parse(queryBody));
        // try {
        //     queryResult = ElephantUtils.sendRequestWithoutToken(ElephantConstantsV6.DEPRECATE_INVOICE_RESULT_LOCALHOST, ElephantConstantsV6.DEPRECATE_INVOICE_RESULT_METHOD, JSONUtil.parse(queryBody), companyservice);
        // } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
        //     log.error("【销项发票】【大象接口】【发票开具】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(queryBody).toString(), JSONObject.toJSONString(companyservice));
        //     e.printStackTrace();
        //     throw new JianshuiServiceException("系统异常！");
        // }
        // log.info("【销项发票】【大象发票】发票开具请求结果{}", queryResult.toString());
        //
        // // 判断外层报文是否成功
        // if (queryResult.isError()) {
        //     throw new JianshuiServiceException(queryResult.getMsg());
        // }
        //
        // // 处理返回报文
        // content = queryResult.getJsonData();
        // ztdm = content.getString("ZTDM");
        // if (!StringUtils.equals(ztdm, "000000")) {
        //     return new HXResponse(content.getString("ZTXX"));
        // }

        // 修改原有发票状态为已作废
        invoice.setState(3);
        invoiceMapper.updateInvoice(invoice);

        // 更新原有订单
        BillInfo originBillInfo = billInfoMapper.selectBySystemOrderNo(companyservice.getCompanyid(), invoice.getSystemOrderno());
        // BillInfo originBillInfo = new BillInfo();
        if (originBillInfo == null) {
            log.error("【销项】【大象发票】作废发票，无法查找到原有发票{}", JSONObject.toJSONString(invoice));
        } else {
            originBillInfo.setState(3);
            billInfoMapper.updateBillInfo(originBillInfo);
        }

        String callbackUrl = originBillInfo.getCallbackUrl();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            RedisQueueUtil.build().setData(invoice).onQueue("invoice_deprecate_callback_consumer").retry(0).dispatch();
        }

        return new HXResponse("0000", "操作完成", null, false);
    }

    /**
     * 发票作废结果查询
     *
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse deprecateQueryInvoice(DeprecateQueryInvoiceDTO deprecateQueryInvoiceDTO, Companyservice companyservice) {
        Invoice invoice = new Invoice();
        invoice.setSellerTaxnum(companyservice.getSellertax());
        invoice.setFpdm(deprecateQueryInvoiceDTO.getFpdm());
        invoice.setFphm(deprecateQueryInvoiceDTO.getFphm());
        QueryWrapper<Invoice> queryWrapper = new QueryWrapper<>(invoice);
        queryWrapper.last(" limit 1 ");
        Invoice result = invoiceMapper.selectOne(queryWrapper);
        if (result == null) {
            return new HXResponse("9999", "发票不存在");
        }

        JSONObject status = new JSONObject();
        status.put("status", result.getState());
        return new HXResponse("0000", "操作完成", status);
    }

    /**
     * 打印接口
     *
     * @param invoice
     * @return
     */
    @Override
    public AjaxResult printInvoice(Invoice invoice, Companyservice companyservice) {
        return AjaxResult.error("系统维护中");
    }

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

        JSONObject query = new JSONObject();
        query.put("NSRSBH", companyservice.getSellertax());
        query.put("DYJMC", queryPrinterDTO.getPrinterName());
        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutToken(ElephantConstantsV6.QUERY_PRINTER_LOCALHOST, ElephantConstantsV6.QUERY_PRINTER, JSONUtil.parse(query), companyservice);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("【销项发票】【大象接口】【打印机查询】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(query).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】打印机查询请求结果{}", queryResult.toString());


        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        JSONObject result = queryResult.getJsonData();
        JSONObject contentJson = result;

        // 如果content不为空，判断状态代码
        if (contentJson != null) {
            String ztdm = contentJson.getString("ZTDM");
            if (!StringUtils.equals("0000", ztdm) && !StringUtils.equals("000000", ztdm)) {
                return new HXResponse(contentJson.getString("ZTXX"));
            }
        }

        JSONArray printerList = contentJson.getJSONArray("DYJXX"); // 获取打印机信息
        List<QueryPrinterResultDTO> resultDTOS = new ArrayList<>();
        for (Object printerTemp : printerList) {
            QueryPrinterResultDTO temp = new QueryPrinterResultDTO();
            JSONObject printer = (JSONObject) printerTemp;
            temp.setPrinterId(printer.getString("DYJID"));
            temp.setPrinterName(printer.getString("DYJMC"));
            temp.setXxpy(printer.getString("XXPY"));
            temp.setXypy(printer.getString("XYPY"));
            temp.setBz(printer.getString("BZ"));
            resultDTOS.add(temp);
        }

        return new HXResponse("0000", "操作完成", resultDTOS);
    }


    /**
     * 推送消息
     *
     * @return
     */
    @Override
    public HXResponse pushData(BillInfo billInfo, Companyservice companyservice) {
        // TODO 获取发票数据
        return new HXResponse("0000", "操作完成");
    }


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

        JSONObject query = new JSONObject();
        query.put("NSRSBH", companyservice.getSellertax()); // "纳税人识别号",
        query.put("FJH", printDTO.getFjh()); // "分机号",
        query.put("DYJID", printDTO.getPrinterId()); // "打印机ID",
        query.put("DYPCH", printDTO.getDypch()); // "打印批次号",
        query.put("FPBS", printDTO.getFpbs());// "发票标识",
        List<PrintDetailDTO> printDetailDTOS = printDTO.getDetails();
        if (CollectionUtils.isNotEmpty(printDetailDTOS)) {
            JSONArray tmepDetails = new JSONArray();
            for (PrintDetailDTO temp : printDetailDTOS) {
                JSONObject tempQuery = new JSONObject();
                tempQuery.put("FPZLDM", ElephantUtils.transElephantType(temp.getInvoiceType(), 1)); // "发票种类代码",
                tempQuery.put("FPDM", temp.getFpdm()); // "发票代码",
                tempQuery.put("FPQH", temp.getFpqh()); // "发票起号",
                tempQuery.put("FPZH", temp.getFpzh()); // "发票止号"
                tempQuery.put("FJH", printDTO.getFjh()); // "分机号"
                tmepDetails.add(tempQuery);
            }
            query.put("DYFPXX", tmepDetails);
        }

        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(ElephantConstantsV6.BATCH_PRINT_LOCALHOST, ElephantConstantsV6.BATCH_PRINT, JSONUtil.parse(query), companyservice);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("【销项发票】【大象接口】【批量打印V5】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(query).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】批量打印V5请求结果{}", queryResult.toString());


        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }

        JSONObject result = queryResult.getJsonData();
        JSONObject contentJson = result;

        // 如果content不为空，判断状态代码
        if (contentJson != null) {
            String ztdm = contentJson.getString("ZTDM");
            if (!StringUtils.equals("0000", ztdm) && !StringUtils.equals("000000", ztdm)) {
                return new HXResponse(contentJson.getString("ZTXX"));
            }
        }

        return new HXResponse("0000", "操作完成");
    }

    /**
     * 同步发票库存
     *
     * @param companyservice
     * @return
     */
    @Override
    public AjaxResult syncStockInfo(Companyservice companyservice) {
        return AjaxResult.error("系统维护中");
    }


    /**
     * 发票签章
     *
     * @param signESealDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse signInvoice(SignESealDTO signESealDTO, Companyservice companyservice) {

        if (BeanUtil.isEmpty(signESealDTO)) {
            HXResponse response = new HXResponse("9999", "传输参数为空！");
            return response;
        }
        AjaxResult queryResult = null;
        System.out.println(JSONUtil.parse(signESealDTO).toString());
        try {
            queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.SIGN
                    , JSONUtil.parse(signESealDTO), companyservice, true);
        } catch (Exception e) {
            log.error("【销项发票】【大象接口】【发票签章】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(signESealDTO).toString()
                    , JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        // 判断外层报文是否成功
        if (queryResult.isError()) {
            log.info("【销项发票】【大象发票】发票签章外层报文异常{}", queryResult.toString());
            throw new JianshuiServiceException(queryResult.getMsg());
        }
        JSONObject result = queryResult.getJsonData();
        return new HXResponse("0000", "操作完成", result);
    }

    /**
     * 发票专用章图片生成
     *
     * @param createESealDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse createESeal(CreateESealDTO createESealDTO, Companyservice companyservice) {
        if (BeanUtil.isEmpty(createESealDTO)) {
            HXResponse response = new HXResponse("9999", "传输参数为空！");
            return response;
        }

        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.SIGN_CREATE
                    , JSONUtil.parse(createESealDTO), companyservice, true);
        } catch (Exception e) {
            log.error("【销项发票】【大象接口】【发票专用章图片生成】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(createESealDTO).toString()
                    , JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】发票专用章图片生成请求结果{}", queryResult.toString());


        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }
        JSONObject result = queryResult.getJsonData();
        return new HXResponse("0000", "操作完成", result);
    }

    /**
     * 发票专用章导入
     *
     * @param createESealDTO
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse registerESeal(RegisterESealDTO createESealDTO, Companyservice companyservice) {
        if (BeanUtil.isEmpty(createESealDTO)) {
            HXResponse response = new HXResponse("9999", "传输参数为空！");
            return response;
        }

        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequest(ElephantConstantsV6.SIGN_REGISTER
                    , JSONUtil.parse(createESealDTO), companyservice, true);
        } catch (Exception e) {
            log.error("【销项发票】【大象接口】【发票专用章导入】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(createESealDTO).toString()
                    , JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        log.info("【销项发票】【大象发票】发票专用章导入请求结果{}", queryResult.toString());


        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }
        JSONObject result = queryResult.getJsonData();
        return new HXResponse("0000", "操作完成", result);
    }

    /**
     * 月度汇总信息查询
     *
     * @param summaryReportQueryDTO
     * @param companyservice
     * @return
     */
    @Override
    public AjaxResult SummaryReport(SummaryReportQueryDTO summaryReportQueryDTO, Companyservice companyservice) {
        return AjaxResult.error("系统维护中");
    }

    /**
     * 回调处理
     *
     * @param request
     * @return
     */
    @Override
    public Object callback(HttpServletRequest request) {
        String respBody = HttpHelper.getBodyString(request);
        log.info("【销项发票】【大象发票】回调接口数据：{}", respBody);
        // 对content进行解码
        JSONObject jsonRaw = JSONObject.parseObject(respBody);
        String content = jsonRaw.getString("jsonRaw");
        // TODO 不止发票作废，发票开具成功等均有回调
        // 处理发票作废
        JSONObject json = JSONObject.parseObject(content);
        Long companyId = null;
        Companyservice companyservice = companyserviceMapper.selectFirstCompanyserviceBySellerTax(json.getString("XHFSBH"));
        if (companyservice != null) {
            companyId = companyservice.getCompanyid();
        }

        return AjaxResult.success();
    }

    @Override
    public Object addCallback(HttpServletRequest request) {
        String respBody = HttpHelper.getBodyString(request);
        log.info("【销项发票】【大象发票】开票回调接口数据：{}", respBody);
        // 对content进行解码
        JSONObject jsonRaw = JSONObject.parseObject(respBody);
        String content = jsonRaw.getString("content");
        content = Base64.decodeStr(content);
        JSONObject contentJson = JSONObject.parseObject(content);
        Long companyId = null;
        if (!StringUtils.equals("0000", contentJson.getString("ZTDM"))) {
            log.info("【销项发票】【大象发票】开票回调接口数据：{},状态代码非0000，异常", respBody);
            JSONObject resp = new JSONObject();
            resp.put("ZTDM", "009999");
            resp.put("ZTXX", "接收失败");
            return resp;
            // JSONArray array = new JSONArray();
            // resp.put("DDFPTS", "接受失败");
        }

        JSONArray respInvoiceArray = new JSONArray();
        JSONArray DDFZPXX = contentJson.getJSONArray("DDFPZXX");
        log.info("【销项发票】【大象发票】开票回调接口数据：{},共{}张明细", respBody, DDFZPXX.size());
        for (int i = 0; i < DDFZPXX.size(); i++) {
            JSONObject fp = DDFZPXX.getJSONObject(i);
            JSONObject DDFPXX = fp.getJSONObject("DDFPXX");
            String DDH = DDFPXX.getString("DDH");
            QueryWrapper<BillInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("system_orderno", DDH);
            queryWrapper.eq("seller_taxnum", DDFPXX.getString("NSRSBH"));
            BillInfo billInfo = billInfoMapper.selectOne(queryWrapper);
            if (billInfo == null) {
                log.info("【销项发票】【大象发票】开票回调接口数据：{},订单号{}不存在", respBody, DDH);
                continue;
            }

            companyId = billInfo.getCompanyId();
            Companyservice companyservice = companyserviceMapper.selectCompanyserviceByCompanyid(companyId);
            if (companyservice == null) {
                log.info("【销项发票】【大象发票】开票回调接口数据：{},销方不存在，订单号：{}", respBody, DDH);
                continue;
            }

            String DDQQLSH = DDFPXX.getString("DDQQLSH");
            QueryBillInfoDTO queryBillInfoDTO = new QueryBillInfoDTO();
            queryBillInfoDTO.setFpqqlsh(DDQQLSH);
            queryBillInfoDTO.setCompanyId(companyId);
            queryBillInfoDTO.setPushBillInfo(true); // 推送发票信息
            HXResponse queryResp = queryInvoice(queryBillInfoDTO, companyservice);
            log.info("【销项发票】【大象发票】开票回调接口查询发票信息：{}", JSONObject.toJSONString(queryResp));

            JSONObject tempResp = new JSONObject();
            tempResp.put("DDQQLSH", DDQQLSH);
            tempResp.put("DDH", DDH);
            tempResp.put("ZTDM", "000000");
            tempResp.put("ZTDM", "009999");
            respInvoiceArray.add(tempResp);
        }

        JSONObject resp = new JSONObject();
        resp.put("ZTDM", "000000");
        resp.put("ZTXX", "接收成功");
        resp.put("DDFPTS", respInvoiceArray);
        log.info("【销项发票】【大象发票】回调处理完成，开票回调接口返回数据：{}", JSONObject.toJSONString(resp));
        return resp;
    }

    @Override
    public Object decryptCallback(HttpServletRequest request) {
        String respBody = HttpHelper.getBodyString(request);
        log.info("【销项发票】【大象发票】作废回调接口数据：{}", respBody);
        // 对content进行解码
        JSONObject jsonRaw = JSONObject.parseObject(respBody);
        String content = jsonRaw.getString("content");
        content = Base64.decodeStr(content);
        JSONObject contentJson = JSONObject.parseObject(content);
        Long companyId = null;
        String sellerTaxno = contentJson.getString("XHFSBH");
        if (StringUtils.isEmpty(sellerTaxno)) {
            return AjaxResult.error("销方识别号为空");
        }
        Companyservice companyservice = companyserviceMapper.selectCompanyserviceByTaxcode(sellerTaxno);
        if (companyservice == null) {
            return AjaxResult.error("销方识别号不存在");
        }
        companyId = companyservice.getCompanyid();

        JSONArray jsonArray = contentJson.getJSONArray("ZFFPXX");
        JSONArray respArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject fpxx = jsonArray.getJSONObject(i);
            String fpdm = fpxx.getString("FPDM");
            String fphm = fpxx.getString("FPHM");
            QueryWrapper<Invoice> temp = new QueryWrapper<>();
            temp.eq("fpdm", fpdm);
            temp.eq("fphm", fphm);
            temp.eq("company_id", companyId);
            temp.last("limit 1");
            Invoice invoice = invoiceMapper.selectOne(temp);
            boolean flag = false;
            if (invoice != null) {
                flag = true;
                String ztdm = fpxx.getString("ZTDM");
                if (StringUtils.equals(ztdm, "163000")) {
                    invoice.setState(3);
                    invoiceMapper.updateInvoice(invoice);
                }
            }
            if (!flag) {
                fpxx.put("ZTDM", "163999");
            } else {
                fpxx.put("ZTDM", "163000");
            }
            respArray.add(fpxx);
        }
        JSONObject resp = new JSONObject();
        resp.put("ZFPCH", contentJson.getString("ZFPCH"));
        resp.put("ZFFPXX", respArray);
        return resp;
    }

    @Override
    public HXResponse getFileUrl(InvoiceAllFileAcquisitionTWODTO invoiceAllFileAcquisitionTWODTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse getFileAcquisitionOn(InvoiceAllFileAcquisitionOnTWODTO invoiceAllFileAcquisitionOnTWODTO, Companyservice companyservice) {
        return null;
    }

    /**
     * 数电获取实名认证二维码接口(数电专用接口)
     *
     * @param decryptResult
     * @param companyservice
     * @return
     */
    @Override
    public HXResponse qrcode(JSONObject decryptResult, Companyservice companyservice) {


        decryptResult = JsonKeyCase.JsonKeyCase(decryptResult);
        log.info("调用大象V6接口报文key转大写后的报文为{}",decryptResult);
        DxhyInterfaceResponse dxhyInterfaceResponse = null;
        try {
            dxhyInterfaceResponse = ElephantUtils.sendRequestWithoutTokenV6(ElephantConstantsV6.GET_RPA_QY_CODE_LOCALHOST, ElephantConstantsV6.GET_RPA_QY_CODE_METHOD, JSONUtil.parse(decryptResult), companyservice);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【数电】【数电获取实名认证二维码接口】请求异常，请求报文{}，销方信息{}", decryptResult, JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            return new HXResponse("009999", "系统异常！");
        }

        return parseResult(dxhyInterfaceResponse);
    }


    @Override
    public HXResponse query(InvoiceAllFileQueryTWODTO invoiceAllFileQueryTWODTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse getPrintXML(InvoiceAllPrintXMLTWODTO invoiceAllPrintXMLTWODTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse issueFastRedInvoice(InvoiceAllKshcJsonDataTWODTO invoiceAllKshcDTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse invoiceStatic(JSONObject decryptResult, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse auditRedInfo(InvoiceAllShhzJsonDataTWODTO invoiceAllShhzTWODTO, Companyservice companyservice) {
        return null;
    }

    @Override
    public HXResponse queryRedInfoDetail(InvoiceAllRedInvoiceDetailTWODTO invoiceAllRedInvoiceDetailDTO, Companyservice companyservice) {
        return null;
    }

    /**
    * @author kk
     * 通用查询接口
    */
    @Override
    public HXResponse queryResultInfo(InvoiceAllQueryTWODTO invoiceAllYhdjDTO, Companyservice companyservice) {

        //存入金财的调用接口表里去
        String requestId = invoiceAllYhdjDTO.getRequestId() != null ? invoiceAllYhdjDTO.getRequestId() : "";
        if(StrUtil.isEmpty(requestId)){
            return new HXResponse("requestId不能为空！");
        }

        // 查询调用记录
        QueryWrapper<InvoiceAllApiLog> apiLogQueryWrapper = new QueryWrapper<>();
        apiLogQueryWrapper.eq("request_id", requestId);
        InvoiceAllApiLog allApiLog = allApiLogMapper.selectOne(apiLogQueryWrapper);

        if (BeanUtil.isEmpty(allApiLog) || StrUtil.isEmpty(allApiLog.getRequestId())) {
            return new HXResponse("serviceId异常！");
        }

        String finalServiceId = allApiLog.getUrl();

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

        // 蓝字发票开具
        if (WebServiceConstant.LZFPKJ.equals(finalServiceId)) {

            // 先执行获取
            QueryBillInfoDTO queryBillInfoDTO = new QueryBillInfoDTO();
            queryBillInfoDTO.setFpqqlsh(requestId);
            HXResponse hxResponseTemp = queryInvoice(queryBillInfoDTO, companyservice);

            // 查询同金财数科返回一样
            QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
            invoiceQueryWrapper.eq("fpqqlsh", requestId);
            invoiceQueryWrapper.orderByDesc("id").last("limit 1");
            Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);

            response.put("data", invoice);

            return response;
        }else if (WebServiceConstant.QRCODE.equals(finalServiceId)) {
            // 获取人脸二维码

            //获取税局用户名称
            JSONObject param = new JSONObject();
            param.put(ElephantConstants.NSRSBH,companyservice.getSellertax());
            HXResponse hxResponse = queryRpaTaxAccount(param, companyservice);
            if (!StringUtils.equals("000000",hxResponse.getCode())){
                return hxResponse;
            }
            JSONObject resp = JSONObject.parseObject(JSON.toJSONString(hxResponse.getData()));

            param.put(ElephantConstants.YHM,resp.getString(ElephantConstants.YHM));

            HXResponse rpaAuthStatus = qrcode(param, companyservice);
            log.info("获取人脸二维码大象返回报文封装后：{}",JSONUtil.toJsonStr(hxResponse));

//            if (StringUtils.equals("000000",rpaAuthStatus.getCode())){
//                rpaAuthStatus.setCode("200");
//                rpaAuthStatus.setMessage("处理成功");
//                JSONObject data = JSONObject.parseObject(JSON.toJSONString(rpaAuthStatus.getData()));
//                String ewm = data.getString(ElephantConstants.EWM);
//                rpaAuthStatus.setData(new HashMap<>().put(ElephantConstants.EWM.toLowerCase(),ewm));
//            }
            return rpaAuthStatus;

        }else if (WebServiceConstant.SQHZFPXXQRD.equals(finalServiceId)) {
            // 申请红字信息表

            //查询红字信息表入库信息
            LambdaQueryWrapper<Redinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Redinfo::getFpqqlsh,requestId);
            Redinfo redinfo = redinfoMapper.selectOne(queryWrapper);
            HXResponse hxResponse = queryRedInfoByElepant(redinfo,companyservice,allApiLog);

            return hxResponse;

        }else if (WebServiceConstant.ADD_RED_INVOICE.equals(finalServiceId)) {
            // 红字发票开具

            //调用大象接口获取数据入库
            QueryBillInfoDTO queryBillInfoDTO = new QueryBillInfoDTO();
            queryBillInfoDTO.setFpqqlsh(requestId);
            HXResponse hxResponse = queryInvoice(queryBillInfoDTO, companyservice);

            if(StringUtils.equals("0000",hxResponse.getCode())){
                return hxResponse;
            }

            //查询数据库信息并返回
            LambdaQueryWrapper<Invoice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Invoice::getFpqqlsh,requestId);
            queryWrapper.orderByDesc(Invoice::getId).last("limit 1");
            Invoice invoice = invoiceMapper.selectOne(queryWrapper);

            response.put("data",invoice);

            return response;

        }else if (WebServiceConstant.CXHZFPXXQRD.equals(finalServiceId)) {
            // 查询红字信息表

            CxhzJsonDataTwoDTO cxhzJsonDataTwoDTO = null;
            try {
                String sendMsg = allApiLog.getSendMsg();
                cxhzJsonDataTwoDTO= JSONObject.parseObject(sendMsg, CxhzTwoDTO.class).getJsonData();

            }catch (Exception e){
                log.error("反序列化失败异常",e);
                throw new JianshuiServiceException("起始日期反序列化失败");
            }
            JSONObject param = new JSONObject();
            param.put(ElephantConstants.YHJSLX,ElephantConstants.STRING_0);
            param.put(ElephantConstants.XSFNSRSBH,companyservice.getSellertax());
            param.put(ElephantConstants.XSFMC,companyservice.getSellername());
            param.put(ElephantConstants.LRFSF,ElephantConstants.STRING_0);
            param.put(ElephantConstants.LRRQQ,cxhzJsonDataTwoDTO.getKprqq());
            param.put(ElephantConstants.LRRQZ,cxhzJsonDataTwoDTO.getKprqz());


            HXResponse hxResponse = queryRedConfirmationList(param, companyservice);
            log.info(" 查询红字信息表大象返回报文封装后：{}",JSONUtil.toJsonStr(hxResponse));

            HZXXLIST hzxxlist = JSONObject.parseObject(JSONObject.toJSONString(hxResponse.getData()), HZXXLIST.class);

            return convertToJcData(hzxxlist);

        } else if (WebServiceConstant.SHHZFPXXQRD.equals(finalServiceId)) {
            // 审核红字信息表
            LambdaQueryWrapper<Redinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Redinfo::getFpqqlsh,requestId);
            queryWrapper.orderByDesc(Redinfo::getId).last("limit 1");

            Redinfo redinfo = redinfoMapper.selectOne(queryWrapper);

            return auditRedInfoResult(allApiLog.getResultMsg(),redinfo,companyservice);

        } else if (WebServiceConstant.FPEWMXZ.equals(finalServiceId)) {
            // 获取发票下载地址

        }  else if (WebServiceConstant.KSHC.equals(finalServiceId)) {
            // 快速红冲


        } else if (WebServiceConstant.QDFPWJHQ.equals(finalServiceId)) {
            // 全电发票文件获取

        }  else{
            return new HXResponse("功能升级中~请稍等~");
        }

        return new HXResponse("功能升级中~请稍等~");


    }

    private HXResponse convertToJcData(HZXXLIST hzxxlist) {
        HZQRXXLIST hzqrxxlist = hzxxlist.getHZQRXXLIST();
        List<Redinfo> redinfos = new ArrayList<>(hzqrxxlist.getTOTAL());

        List<HZXXDATA> list = hzqrxxlist.getLIST();

        List<HZXXDATACase> hzxxList = new ArrayList<>();

        for (HZXXDATA hzxxdata : list) {
            LambdaQueryWrapper<Redinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Redinfo::getRedInfoNo,hzxxdata.getHZFPXXQRDBH());
            queryWrapper.orderByDesc(Redinfo::getId).last("limit 1");
            //根据红字信息表编号查询红字信息
            Redinfo redinfo = redinfoMapper.selectOne(queryWrapper);
            //不存在就创建对象
            if (ObjectUtils.isEmpty(redinfo)){
                redinfo = new Redinfo();
            }
            redinfo.setRedInfoNo(hzxxdata.getHZFPXXQRDBH());
            redinfo.setSellerTaxnum(hzxxdata.getXSFNSRSBH());
            redinfo.setSellerName(hzxxdata.getXSFMC());
            redinfo.setBuyerName(hzxxdata.getGMFMC());
            redinfo.setBuyerTaxnum(hzxxdata.getGMFNSRSBH());
            redinfo.setOriginFpdm(hzxxdata.getLZFPDM());
            redinfo.setOriginFphm(hzxxdata.getLZFPHM());
            redinfo.setOriginKprq(hzxxdata.getLZKPRQ());
            redinfo.setReqnsrsbh(hzxxdata.getXSFNSRSBH());
            redinfos.add(redinfo);
            //判断是否存在红字信息，存在执行更新
            if (ObjectUtils.isEmpty(redinfo.getId())){
                //处理发票表和红字信息表
                redInfoAndInvoiceUpdate(hzxxdata, redinfo);
            }
            //封装返回数据
            HZXXDATACase hzxxdataCase = new HZXXDATACase();
            hzxxdataCase.setUuid(hzxxdata.getUUID());
            hzxxdataCase.setRedInfoNo(hzxxdata.getHZFPXXQRDBH());
            hzxxdataCase.setLrfsf(hzxxdata.getLRFSF());
            hzxxdataCase.setSellerTaxnum(hzxxdata.getXSFNSRSBH());
            hzxxdataCase.setSellerName(hzxxdata.getXSFMC());
            hzxxdataCase.setBuyerTaxnum(hzxxdata.getGMFNSRSBH());
            hzxxdataCase.setBuyerName(hzxxdata.getGMFMC());
            hzxxdataCase.setLzfpdm(hzxxdata.getLZFPDM());
            hzxxdataCase.setLzfphm(hzxxdata.getLZFPHM());
            hzxxdataCase.setSfzzfpbz(hzxxdata.getSFZZFPBZ());
            hzxxdataCase.setLzkprq(hzxxdata.getLZKPRQ());
            hzxxdataCase.setLzhjje(hzxxdata.getLZHJJE());
            hzxxdataCase.setLzhjse(hzxxdata.getLZHJSE());
            hzxxdataCase.setLzfppzdm(hzxxdata.getLZFPPZDM());
            hzxxdataCase.setLzfptdyslxdm(hzxxdata.getLZFPTDYSLXDM());
            hzxxdataCase.setHzcxje(hzxxdata.getHZCXJE());
            hzxxdataCase.setHzcxse(hzxxdata.getHZCXSE());
            hzxxdataCase.setHzqrdmxsl(hzxxdata.getHZQRDMXSL());
            hzxxdataCase.setChyydm(hzxxdata.getCHYYDM());
            hzxxdataCase.setHzqrdztdm(hzxxdata.getCHYYDM());
            hzxxdataCase.setQrrq(hzxxdata.getQRRQ());
            hzxxdataCase.setYkjhzfpbz(hzxxdata.getYKJHZFPBZ());
            hzxxdataCase.setHzfphm(hzxxdata.getHZFPHM());
            hzxxdataCase.setHzkprq(hzxxdata.getHZKPRQ());
            hzxxdataCase.setYxbz(hzxxdata.getYXBZ());
            hzxxList.add(hzxxdataCase);

        }

        return new HXResponse("200","查询成功",hzxxList,true);
    }

    @Async
    public void redInfoAndInvoiceUpdate(HZXXDATA hzxxdata, Redinfo redinfo) {
        redinfoMapper.updateRedinfo(redinfo);
        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.eq("fphm", redinfo.getOriginFphm());
        Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        //更新蓝字发票状态为冲红 99
        invoice.setState(99);
        invoiceMapper.updateInvoice(invoice);
        invoice.setId(null);
        invoice.setOriginFphm(invoice.getFphm());
        invoice.setFphm(hzxxdata.getHZFPHM());
        invoice.setBillInfoId(redinfo.getId());
        invoice.setSystemOrderno(redinfo.getSystemOrderno());
        invoice.setOutTradeOrderno(redinfo.getOutTradeOrderno());
        invoice.setFpqqlsh(redinfo.getFpqqlsh());
        invoice.setKprq(DateUtil.parse(hzxxdata.getHZKPRQ()));
        invoice.setState(2);
        invoiceMapper.insertInvoice(invoice);
    }

    private HXResponse auditRedInfoResult(String uuid,Redinfo redinfo, Companyservice companyservice) {
        if (ObjectUtils.isEmpty(companyservice)){
            log.info("请求日志为空或者企业服务为空");
            return new HXResponse("9998","请求日志为空或者企业服务为空");
        }
        if (ObjectUtils.isEmpty(redinfo)){
            log.info("不存在该红字信息");
            return new HXResponse("9998","不存在该红字信息");
        }

        if (StringUtils.isBlank(uuid)){
            log.info("红字确认单UUID不能为空");
            return new HXResponse("9998","红字确认单UUID不能为空");
        }

        JSONObject param = new JSONObject();
        param.put(ElephantConstants.NSRSBH,companyservice.getSellertax());
        param.put(ElephantConstants.UUID,uuid);
        param.put(ElephantConstants.HZQRDBH,redinfo.getRedInfoNo());
        param.put(ElephantConstants.QRLX,ElephantConstants.QRLX_Y);

        //调用大象接口获取确认日期

        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(ElephantConstantsV6.QUERY_INVOICE_LOCALHOST, ElephantConstantsV6.QUERY_INVOICE_METHOD, JSONUtil.parse(param), companyservice);
            log.info("大象返回报文封装后：{}",JSONUtil.toJsonStr(queryResult));
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【发票开具】发票请求异常，请求报文{}，销方信息{}", param.toJSONString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        //转换成小写
        JSONObject data = queryResult.getJsonData();
        String qrrq = data.getString(ElephantConstants.QRRQ);
        data.clear();
        data.put(ElephantConstants.CASE_QRRQ,qrrq);

        return new HXResponse(String.valueOf(queryResult.getCode()),queryResult.getMsg(),data,true);
    }

    //    @Transactional(rollbackFor = Exception.class)
    public HXResponse queryRedInfoByElepant(Redinfo redinfo, Companyservice companyservice,InvoiceAllApiLog apiLog) {
        //返回信息

        if (ObjectUtils.isEmpty(redinfo)){
            return new HXResponse("9998","红字信息未查询到");
        }

        //日志uuid
        String uuid = UUID.randomUUID().toString();

        //封装请求参数
        JSONObject param = new JSONObject();
        param.put(ElephantConstants.NSRSBH,companyservice.getSellertax());
        param.put(ElephantConstants.UUID,apiLog.getResultMsg());
        param.put(ElephantConstants.XSFNSRSBH,companyservice.getSellertax());

        debugLog("红字信息表申请查询断点1",uuid,System.currentTimeMillis());
        //调用大象接口查询红字信息表明细
        AjaxResult queryResult = null;
        try {
            queryResult = ElephantUtils.sendRequestWithoutTokenV6New(ElephantConstantsV6.QUERY_RED_CONFIRMATION_ITEM_LIST_LOCALHOST, ElephantConstantsV6.QUERY_RED_CONFIRMATION_ITEM_LIST_METHOD, JSONUtil.parse(param), companyservice);
            log.info(" 红字信息表申请大象返回报文封装后：{}",JSONUtil.toJsonStr(queryResult));
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("【销项发票】【大象接口】【红字信息表申请】发票请求异常，请求报文{}，销方信息{}", JSONUtil.parse(param).toString(), JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }
        debugLog("断点5", uuid, System.currentTimeMillis());

        // 判断外层报文是否成功
        if (queryResult.isError()) {
            throw new JianshuiServiceException(queryResult.getMsg());
        }
        debugLog("断点6", uuid, System.currentTimeMillis());

        JSONObject contentJson = queryResult.getJsonData();
        debugLog("断点7", uuid, System.currentTimeMillis());

        ElephantRedInfoQueryResultDTO queryResultDTO = contentJson.toJavaObject(ElephantRedInfoQueryResultDTO.class);
        debugLog("断点8", uuid, System.currentTimeMillis());

        ElephantRedInfo elephantRedInfo = queryResultDTO.getDATA();
        //原发票处理
        String originFphm = redinfo.getOriginFphm();
        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.eq("fphm", originFphm);
        Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        //更新蓝字发票状态为冲红 99
        invoice.setState(99);
        invoiceMapper.updateInvoice(invoice);
        invoice.setId(null);
        invoice.setOriginFphm(invoice.getFphm());
        invoice.setFphm(elephantRedInfo.getHZFPHM());
        invoice.setBillInfoId(redinfo.getId());
        invoice.setSystemOrderno(redinfo.getSystemOrderno());
        invoice.setOutTradeOrderno(apiLog.getRequestId());
        invoice.setFpqqlsh(redinfo.getFpqqlsh());
        invoice.setKprq(DateUtil.parse(elephantRedInfo.getHZKPRQ()));
        invoice.setState(2);
        invoiceMapper.insertInvoice(invoice);
        //红字信息表主信息封装
        redinfo.setRedInfoNo(elephantRedInfo.getHZFPXXQRDBH());
        redinfo.setSqlb(Integer.parseInt(elephantRedInfo.getLRFSF()));
        redinfo.setSellerTaxnum(elephantRedInfo.getXSFNSRSBH());
        redinfo.setSellerName(elephantRedInfo.getXSFMC());
        redinfo.setBuyerTaxnum(elephantRedInfo.getGMFNSRSBH());
        redinfo.setBuyerName(elephantRedInfo.getGMFMC());
        redinfo.setOriginFpdm(elephantRedInfo.getLZFPDM());
        redinfo.setOriginFphm(elephantRedInfo.getLZFPHM());
        redinfo.setOriginKprq(elephantRedInfo.getLZKPRQ());
        //todo 返回信息中不知道金额含税不含税
        redinfo.setTaxamt(new BigDecimal(elephantRedInfo.getHZCXJE()));
        redinfo.setTax(new BigDecimal(elephantRedInfo.getHZCXSE()));
        redinfo.setTaxfreeamt(redinfo.getTaxamt().subtract(redinfo.getTaxamt()));

        redinfo.setRedInfoStatus(elephantRedInfo.getHZQRXXZTDM());
        redinfo.setBillInputTime(elephantRedInfo.getHZKPRQ());

        int i = redinfoMapper.updateRedinfo(redinfo);
        debugLog("断点9", uuid, System.currentTimeMillis());
        if (i<1){
            debugLog("红字订单更新主表信息失败",uuid,System.currentTimeMillis());
            throw new JianshuiServiceException("红字订单更新主表信息失败");
        }

        //返回报文
        AddRedInfoInvoiceTWOVO addRedInfoInvoiceTWO = new AddRedInfoInvoiceTWOVO();

        addRedInfoInvoiceTWO.setHzfpxxqrdbh(elephantRedInfo.getHZFPXXQRDBH());
        addRedInfoInvoiceTWO.setHzfpxxqrdid(elephantRedInfo.getUUID());
        addRedInfoInvoiceTWO.setHzfpxxqrdZtdm(queryResultDTO.getZTDM());

        AddRedInfoInvoiceTWOVOSub addRedInfoInvoiceJsonDataTWOVO = new AddRedInfoInvoiceTWOVOSub();
        addRedInfoInvoiceJsonDataTWOVO.setFpqqlsh(redinfo.getFpqqlsh());
        addRedInfoInvoiceJsonDataTWOVO.setFphm(elephantRedInfo.getHZFPHM());


        addRedInfoInvoiceJsonDataTWOVO.setKprq(elephantRedInfo.getHZKPRQ());

        addRedInfoInvoiceJsonDataTWOVO.setUuid(elephantRedInfo.getUUID());
        addRedInfoInvoiceJsonDataTWOVO.setLrfsf(elephantRedInfo.getLRFSF());
        addRedInfoInvoiceJsonDataTWOVO.setHzfpxxqrdbh(elephantRedInfo.getHZFPXXQRDBH());
        addRedInfoInvoiceJsonDataTWOVO.setXsfnsrsbh(elephantRedInfo.getXSFNSRSBH());
        addRedInfoInvoiceJsonDataTWOVO.setXsfmc(elephantRedInfo.getXSFMC());
        addRedInfoInvoiceJsonDataTWOVO.setGmfnsrsbh(elephantRedInfo.getGMFNSRSBH());
        addRedInfoInvoiceJsonDataTWOVO.setGmfmc(elephantRedInfo.getGMFMC());
        addRedInfoInvoiceJsonDataTWOVO.setLzfpdm(elephantRedInfo.getLZFPDM());
        addRedInfoInvoiceJsonDataTWOVO.setLzfphm(elephantRedInfo.getLZFPHM());
        addRedInfoInvoiceJsonDataTWOVO.setSfzzfpbs(elephantRedInfo.getSFZZFPBZ());
        addRedInfoInvoiceJsonDataTWOVO.setLzkprq(elephantRedInfo.getLZKPRQ());
        addRedInfoInvoiceJsonDataTWOVO.setLzhjje(elephantRedInfo.getLZHJJE());
        addRedInfoInvoiceJsonDataTWOVO.setLzfppzdm(elephantRedInfo.getLZFPPZDM());
        addRedInfoInvoiceJsonDataTWOVO.setLzfptdyslxdm(elephantRedInfo.getLZFPTDYSLXDM());
        addRedInfoInvoiceJsonDataTWOVO.setHzcxje(elephantRedInfo.getHZCXJE());
        addRedInfoInvoiceJsonDataTWOVO.setHzcxse(elephantRedInfo.getHZCXSE());
        addRedInfoInvoiceJsonDataTWOVO.setChyydm(elephantRedInfo.getCHYYDM());
        addRedInfoInvoiceJsonDataTWOVO.setHzqrxxztdm(elephantRedInfo.getHZQRXXZTDM());
        addRedInfoInvoiceJsonDataTWOVO.setQrrq(elephantRedInfo.getQRRQ());
        addRedInfoInvoiceJsonDataTWOVO.setYkjhzfpbz(elephantRedInfo.getYKJHZFPBZ());
        addRedInfoInvoiceJsonDataTWOVO.setHzfphm(elephantRedInfo.getHZFPHM());
        addRedInfoInvoiceJsonDataTWOVO.setHzkprq(elephantRedInfo.getHZKPRQ());
        addRedInfoInvoiceJsonDataTWOVO.setYxbs(elephantRedInfo.getYXBZ());
        addRedInfoInvoiceJsonDataTWOVO.setLzmxxh(elephantRedInfo.getLZMXXH());

        List<ElephantRedInfoDetailCase> detailList = new ArrayList<>();
        for (ElephantRedInfoDetail elephantRedInfoDetail : elephantRedInfo.getHZQRXXMXLIST()) {
            ElephantRedInfoDetailCase  detail = new ElephantRedInfoDetailCase();
            detail.setDw(elephantRedInfoDetail.getDW());
            detail.setJe(elephantRedInfoDetail.getJE());
            detail.setSe(elephantRedInfoDetail.getSE());
            detail.setGgxh(elephantRedInfoDetail.getGGXH());
            detail.setXh(elephantRedInfoDetail.getXH());
            detail.setFpspdj(elephantRedInfoDetail.getFPSPDJ());
            detail.setFpspsl(elephantRedInfoDetail.getFPSPSL());
            detail.setLzmxxh(elephantRedInfoDetail.getLZMXXH());
            detail.setSlv(elephantRedInfoDetail.getSLV());
            detail.setSphfwssflhbbm(elephantRedInfoDetail.getSPHFWSSFLHBBM());
            detail.setXmmc(elephantRedInfoDetail.getXMMC());
            detailList.add(detail);

        }
        addRedInfoInvoiceJsonDataTWOVO.setHzqrxxmxlist(detailList);


        addRedInfoInvoiceTWO.setHzfpxx(addRedInfoInvoiceJsonDataTWOVO);

        //金财没有处理明细

//        List<Redinfodetail> redinfodetailList = new ArrayList<>();
//
//        List<Redinfodetail> redinfodetails = redinfoMapper.selectRedinfoDetailList(redinfo.getId());
//
//        Map<Integer, Redinfodetail> redInfoMapByIndex = redinfodetails.stream().collect(Collectors.toMap(e -> e.getIndex(), e -> e));
//
//        for (ElephantRedInfoDetail elephantRedInfoDetail : elephantRedInfo.getHZQRXXMXLIST()) {
//
//            Redinfodetail redinfodetail = redInfoMapByIndex.get(elephantRedInfoDetail.getXH().longValue());
//            redinfodetail.setBillno(redinfo.getRedInfoNo());
//            redinfodetail.setRedinfoId(redinfo.getId());
//            redinfodetail.setIndex(elephantRedInfoDetail.getXH());
//            redinfodetail.setGoodName(elephantRedInfoDetail.getXMMC());
//            redinfodetail.setSpec(elephantRedInfoDetail.getGGXH());
//            redinfodetail.setUnit(elephantRedInfoDetail.getDW());
//            redinfodetail.setPrice(new BigDecimal(elephantRedInfoDetail.getFPSPDJ()));
//            // TODO 不确定金额是否为含税金额
//            redinfodetail.setTaxamt(new BigDecimal(elephantRedInfoDetail.getJE()));
//            redinfodetail.setTax(new BigDecimal(elephantRedInfoDetail.getSE()));
//            redinfodetail.setTaxfreeamt(redinfodetail.getTaxamt().subtract(redinfodetail.getTax()));
//
//            redinfodetail.setTaxrate(new BigDecimal(elephantRedInfoDetail.getSLV()));
//            redinfodetail.setCreateTime(new Date());
//            redinfodetailList.add(redinfodetail);
//        }
//
//        //删除红字信息明细
//        redinfoMapper.deleteRedinfodetailByRedinfoId(redinfo.getId());
//        debugLog("断点10", uuid, System.currentTimeMillis());
//        //批量插入
//        int count = redinfoMapper.batchRedinfodetail(redinfodetailList);
//        debugLog("断点11", uuid, System.currentTimeMillis());
//        if(count <1){
//            debugLog("红字订单更新明细信息失败",uuid,System.currentTimeMillis());
//            throw new JianshuiServiceException("红字订单更新明细信息失败");
//        }


        return new HXResponse("0000","查询成功",addRedInfoInvoiceTWO,true);
    }


}
