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

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

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

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

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

    @Autowired
    private SkDyjMapper skDyjMapper;

    @Autowired
    private RedinfoMapper redinfoMapper;

    @Autowired
    private InvoiceAllApiLogMapper allApiLogMapper;

    @Autowired
    private InvoiceAllYhdjMapper yhdjMapper;


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

        // 请求billInfo
        Long billInfoID = 0L;

        // 开票实体转换,校验
        InvoiceAllAddTwoDTO invoiceAllAddTwoDTO = BeanUtil.copyProperties(billInfo, InvoiceAllAddTwoDTO.class);
        ValidateUtils.validate(invoiceAllAddTwoDTO);

        InvoiceAllAddInfoTwoDTO invoiceAllAddInfoTwoDTO = BeanUtil.copyProperties(billInfo, InvoiceAllAddInfoTwoDTO.class);
        ValidateUtils.validate(invoiceAllAddInfoTwoDTO);


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

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

        cn.hutool.json.JSONObject result = null;
        try {

            result = ApiHttp.request(WebServiceConstant.LZFPKJ, WebServiceConstant.URL, invoiceAllAddTwoDTO, companyservice);

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

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

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

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

    }


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


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


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

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

        // TODO: 2023/3/28 查询存库Invoice表

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

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

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

        // TODO: 2023/3/28 用户登记表有问题，数据有重复的，看下什么问题1 



        QueryTwoDTO queryDTO = new QueryTwoDTO();
        queryDTO.setDqbm(invoiceAllYhdj.get);
        queryDTO.setAsync("");
        queryDTO.setBsrysfzjhm("");
        queryDTO.setNsrsbh("");
        queryDTO.setRequestId("");

        // TODO: 2023/3/28 ... 
        
        
        
        ValidateUtils.validate(queryDTO);

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

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


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

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

                // 2022/12/13 这里所有的接口都走，需要根据具体的id判断接口来存库。

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

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

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

                    if(BeanUtil.isNotEmpty(addInvoiceVO)){
                        QueryWrapper<BillInfo> billInfoQueryWrapper = new QueryWrapper<>();
                        billInfoQueryWrapper.eq("out_trade_orderno", requestId);
                        BillInfo billInfo = billInfoMapper.selectOne(billInfoQueryWrapper);
                        if (BeanUtil.isNotEmpty(billInfo)) {
                            QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
                            invoiceQueryWrapper.eq("out_trade_orderno", requestId);
                            Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                            if (BeanUtil.isNotEmpty(invoice)) {
                                invoice = BeanUtil.copyProperties(billInfo, Invoice.class);
                                invoice.setFphm(addInvoiceVO.getFphm());
                                invoice.setKprq(DateUtil.parse(addInvoiceVO.getKprq()));
                                invoice.setZzfpdm(addInvoiceVO.getZzfpdm());
                                invoice.setZzfphm(addInvoiceVO.getZzfphm());
                                //二维码=二维码下载地址
                                invoice.setQrCode(addInvoiceVO.getEwmUrl());
                                //发票 pdf 地址=PDF格式下载地址
                                invoice.setInvoicePdfUrl(addInvoiceVO.getPdfUrl());
                                //发票详情地址=OFD格式下载地址
                                invoice.setInvoiceJpgUrl(addInvoiceVO.getOfdUrl());
                                //ofdUrl=XML格式下载地址
                                invoice.setcOfdUrl(addInvoiceVO.getXmlUrl());
                                invoice.setState(2);
                                invoiceMapper.updateInvoice(invoice);
                                billInfo.setState(2);
                                billInfoMapper.updateById(billInfo);
                            } else {
                                invoice = BeanUtil.copyProperties(billInfo, Invoice.class);
                                invoice.setFphm(addInvoiceVO.getFphm());
                                invoice.setKprq(DateUtil.parse(addInvoiceVO.getKprq()));
                                invoice.setZzfpdm(addInvoiceVO.getZzfpdm());
                                invoice.setZzfphm(addInvoiceVO.getZzfphm());
                                //二维码=二维码下载地址
                                invoice.setQrCode(addInvoiceVO.getEwmUrl());
                                //发票 pdf 地址=PDF格式下载地址
                                invoice.setInvoicePdfUrl(addInvoiceVO.getPdfUrl());
                                //发票详情地址=OFD格式下载地址
                                invoice.setInvoiceJpgUrl(addInvoiceVO.getOfdUrl());
                                //ofdUrl=XML格式下载地址
                                invoice.setcOfdUrl(addInvoiceVO.getXmlUrl());
                                invoice.setState(2);
                                invoiceMapper.insertInvoice(invoice);
                                billInfo.setState(2);
                                billInfoMapper.updateById(billInfo);
                            }
                            // 返回数据
                            response.put("data", invoice);
                        } else {
                            log.error("【金四服务类】【金财数科】【通用查询接口】API请求异常，billInfo未查询到，requestId={}。", requestId);
//                            return AjaxResult.error(ErrorCode.INCOME_ERROR);
                        }
                    }
                } /*else if (WebServiceConstant.FPEWMXZ.equals(finalServiceId)) {
                    // 获取发票下载地址
                    cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                    String ewmUrl = json.getOrDefault("ewmUrl", "").toString();
                    String pdfUrl = json.getOrDefault("pdfUrl", "").toString();
                    String ofdUrl = json.getOrDefault("ofdUrl", "").toString();
                    String xmlUrl = json.getOrDefault("xmlUrl", "").toString();
                    if (StrUtil.isNotEmpty(requestId)) {
                        QueryWrapper<Invoice> invoiceQueryWrapper = new QueryWrapper<>();
                        invoiceQueryWrapper.eq("out_trade_orderno", requestId);
                        Invoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
                        if (BeanUtil.isNotEmpty(invoice)) {
                            invoice.setInvoicePdfUrl(pdfUrl);
                            invoice.setcOfdUrl(ofdUrl);
                            invoiceMapper.updateInvoice(invoice);
                        }
                    }


                }*/

                /*else if (WebServiceConstant.ADD_RED_INVOICE.equals(finalServiceId)) {
                    // 查找原发票信息
                    AddRedInvoiceVO addRedInvoiceVO = BeanUtil.copyProperties(data, AddRedInvoiceVO.class);
                    QueryWrapper<BillInfo> billInfoQueryWrapper = new QueryWrapper<>();
                    billInfoQueryWrapper.eq("fpqqlsh", requestId);
                    BillInfo billInfo = billInfoMapper.selectOne(billInfoQueryWrapper);
                    if (billInfo != null) {
//                        return AjaxResult.error("未查询到原发票信息");
                        // 根据billInfo获得原发票号码
                        QueryWrapper<BillInfo> originBillInfoWrapper = new QueryWrapper<>();
                        originBillInfoWrapper.eq("origin_fphm", billInfo.getOriginFphm());
                        BillInfo originBillInfo = billInfoMapper.selectOne(originBillInfoWrapper);
                        if (originBillInfo != null) {
//                        return AjaxResult.error("未查询到原发票信息");
                            // 查找原发票信息
                            Invoice originInvoice = invoiceMapper.selectInvoiceByBillInfoId(originBillInfo.getId());
                            Invoice invoice = BeanUtil.copyProperties(originInvoice, Invoice.class);
                            invoice.setFphm(addRedInvoiceVO.getFphm());
                            invoice.setBillInfoId(billInfo.getId());
                            invoice.setSystemOrderno(billInfo.getSystemOrderno());
                            invoice.setOutTradeOrderno(billInfo.getOutTradeOrderno());
                            invoice.setFpqqlsh(billInfo.getFpqqlsh());
                            invoice.setKprq(DateUtil.parse(addRedInvoiceVO.getKprq()));
                            invoice.setZzfpdm(addRedInvoiceVO.getZzfpdm());
                            invoice.setZzfphm(addRedInvoiceVO.getZzfphm());
                            //二维码=二维码下载地址
                            invoice.setQrCode(addRedInvoiceVO.getEwmUrl());
                            //发票 pdf 地址=PDF格式下载地址
                            invoice.setInvoicePdfUrl(addRedInvoiceVO.getPdfUrl());
                            //发票详情地址=OFD格式下载地址
                            invoice.setInvoiceJpgUrl(addRedInvoiceVO.getOfdUrl());
                            //ofdUrl=XML格式下载地址
                            invoice.setcOfdUrl(addRedInvoiceVO.getXmlUrl());
                            invoice.setState(2);
                            invoiceMapper.insertInvoice(invoice);
                            billInfo.setState(2);
                            billInfoMapper.updateById(billInfo);
                        }
                    }
                    response.put("data", JSONUtil.parseObj(data));

                }*/

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

                }else if (WebServiceConstant.SQHZFPXXQRD.equals(finalServiceId)) {
                    // 申请红字信息表
                    // TODO: 后期存库
                }else if (WebServiceConstant.CXHZFPXXQRD.equals(finalServiceId)) {
                    // 查询红字信息表
                    // TODO: 后期存库
                }else if (WebServiceConstant.SHHZFPXXQRD.equals(finalServiceId)) {
                    // 审核红字信息表
                    // TODO: 后期存库
                }else if (WebServiceConstant.QDFPWJHQ.equals(finalServiceId)) {
                    // 审核红字信息表
                    // TODO: 全电发票文件获取
                }*/
                return response;
            } else {
                return new HXResponse(msg);
            }

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

    }

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

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

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

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

        String spbm = "";

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

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

        // TODO: 2023/3/9 设备号是 jspbh 并非billNO？  申请方税号reqnsrsbh
        //
        redinfo.setJspbh("661024643068230218103524".substring(0,12));
        redinfo.setReqnsrsbh("9113093067851155XY");
        redinfo.setFjh("123");
        redinfo.setMultTaxRate("0");
        redinfo.setBillInputTime("2022-11-11");
        redinfo.setBmbbh("2323232");
        redinfo.setTaxrate(new BigDecimal("0.03"));
        //

        redinfoMapper.batchRedinfodetail(redinfodetailList);

        // 参数校验及参数处理
        AisinoConsoleInvoiceRedUploadDTO redUploadDTO = BeanUtil.copyProperties(redinfo,AisinoConsoleInvoiceRedUploadDTO.class);
        // 填开日期
        redUploadDTO.setDate(redinfo.getBillInputTime());
        // 信息表类型
        redUploadDTO.setBillType("0");
        // TODO-dxk: 2023/2/27 含税、不含税金额  含税标志，这里需要确定
        // 合计金额计算
        redUploadDTO.setAmount(String.valueOf(taxfreeamt));
        // 含税税率标识
        redUploadDTO.setSLBZ("0");
        // 税种类别
        redUploadDTO.setSzlb("1");
        ValidateUtils.validate(redUploadDTO);



        if(redinfo.getRedinfodetailList() == null || redinfo.getRedinfodetailList().size() == 0){
            return new HXResponse("格式校验失败，请上传明细信息！");
        }


        String paramChild = "";
        List<AisinoConsoleInvoiceRedUploadChildDTO> redUploadChildDTO = BeanUtil.copyToList(redinfo.getRedinfodetailList(),AisinoConsoleInvoiceRedUploadChildDTO.class);
        for (AisinoConsoleInvoiceRedUploadChildDTO childDTO : redUploadChildDTO) {

            // TODO-dxk: 2023/2/27 含税、不含税金额
            childDTO.setHS_BZ(childDTO.getHS_BZ().equals("false")? "N":"Y");

            paramChild = "<GoodsMx>" + JSONUtil.toXmlStr(JSONUtil.parse(childDTO)) + " </GoodsMx>";

            ValidateUtils.validate(childDTO);
        }

        // 组装xml报文
        String param = JSONUtil.toXmlStr(JSONUtil.parse(redUploadDTO));

//        param = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
        param = "" +
                "<FPXT>\n" +
                "    <INPUT>\n" +
                "        <RedInvReqBill>" + param;

        param = param + "<RedInvReqBillMx>";

        param = param + paramChild;

        param = param + "            </RedInvReqBillMx>\n" +
                "        </RedInvReqBill>\n" +
                "    </INPUT>\n" +
                "</FPXT>";


        //发起请求
        AjaxResult ajaxResult = null;
        try{
            ajaxResult = AisinoConsoleUtil.sendRequest(AisinoConsoleConstants.RED_UPLOAD, param, companyservice);
        }catch (Exception e){
            log.error("【销项发票】【总部控制台接口】【发票作废】发票请求异常，请求报文{}，销方信息{}","", JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }

        //返回报文解析
        if (ajaxResult.isError()) {
            throw new JianshuiServiceException(ajaxResult.getMsg());
        }

        // todo-k: 返回报文解析这里还带看下具体的返回形式

        cn.hutool.json.JSONObject resultJSON = JSONUtil.parseObj(ajaxResult.get("data"));
        String retcode = resultJSON.get("retcode") != null ? resultJSON.get("retcode").toString() : "";
        String retmsg = resultJSON.get("retmsg") != null ? resultJSON.get("retmsg").toString() : "";


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

        // TODO-dxk: 2023/2/27 看下 RedInfoStatus 0 1 2代表什么
        redinfo.setRedInfoStatus("1");
        redinfo.setRedInfoMessage(retmsg);
        redinfoMapper.updateRedinfo(redinfo);
        return new HXResponse(retmsg);
    }

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

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

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

        // 组装报文
        AisinoConsoleInvoiceRedDownloadDTO downloadDTO = BeanUtil.copyProperties(redInfoResult,AisinoConsoleInvoiceRedDownloadDTO.class);
        downloadDTO.setYQZT("N");
        downloadDTO.setXXBFW("0");
        downloadDTO.setPAGENO("1");
        downloadDTO.setPAGESIZE("1000");

        String param = JSONUtil.toXmlStr(JSONUtil.parse(downloadDTO));
        param = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<FPXT>\n" +
                "    <INPUT>\n" + param + "</INPUT>\n" +
                "</FPXT>";

        //发起请求
        AjaxResult ajaxResult = null;
        try{
            ajaxResult = AisinoConsoleUtil.sendRequest(AisinoConsoleConstants.RED_DOWLOAD, param, companyservice);
        }catch (Exception e){
            log.error("【销项发票】【总部控制台接口】【发票作废】发票请求异常，请求报文{}，销方信息{}","", JSONObject.toJSONString(companyservice));
            e.printStackTrace();
            throw new JianshuiServiceException("系统异常！");
        }

        //返回报文解析
        if (ajaxResult.isError()) {
            throw new JianshuiServiceException(ajaxResult.getMsg());
        }

        cn.hutool.json.JSONObject resultJSON = JSONUtil.parseObj(ajaxResult.get("data"));
        String retcode = resultJSON.get("retcode") != null ? resultJSON.get("retcode").toString() : "";
        String retmsg = resultJSON.get("retmsg") != null ? resultJSON.get("retmsg").toString() : "";

        // todo-k: 下载的返回报文需要单独处理，更新信息表状态？
        // todo-k: 返回的格式看看怎么处理一把，VO都已经创建

        if (!StringUtils.equals("0000", retcode)) {

            return new HXResponse(retmsg);
        }


        return null;
    }



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


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

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

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

        return null;

    }

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

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

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

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

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

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


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

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

        return -1;
    }

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

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


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

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


}
