package com.tofly.dzfp.common;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.dzfp.config.DzfpConfig;
import com.tofly.dzfp.entity.*;
import com.tofly.dzfp.entity.Invoice.*;
import com.tofly.dzfp.entity.res.EiFpkjResponse;
import com.tofly.dzfp.service.*;
import com.tofly.dzfp.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import nuonuo.open.sdk.NNOpenSDK;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lihaoli
 * @date 2024/11/14 xxx
 */
@Slf4j
@Service
public class DzfpService {

    @Autowired
    private DzfpConfig dzfpConfig;
    @Autowired
    private EiFpkjMxService eiFpkjMxService;
    @Autowired
    private EiFpkjRequestService eiFpkjRequestService;
    @Autowired
    private YySspjxxService yySspjxxService;
    @Autowired
    private YyQfmxService yyQfmxService;
    @Autowired
    private EiYkfpLogService eiYkfpLogService;

    @Autowired
    private EiKprpzService eiKprpzService;
    /**
     * 登录状态
     */
    private Boolean loginzt = false;

    private String digiAccounts = "";//数电账号，数电发票支持指定数电账号重试开票

    private List<Kprxx> kprxxMapList = new ArrayList<>();

    /**
     * 发票开票/冲红
     */
    public void fpkpTask() {

        if (!dlztyz()) {
            return;
        }
        Page page = new Page<>(1, 80);
        Page<EiFpkjRequest> eiFpkjRequestPage = eiFpkjRequestService.page(page,
                new QueryWrapper<EiFpkjRequest>().lambda()
                        .eq(EiFpkjRequest::getFpSfkp, "1")
                        .eq(EiFpkjRequest::getClLock, "0")
                        .in(EiFpkjRequest::getClCljg, "0", "6")
                        .in(EiFpkjRequest::getZfZfbz, "0", "2")
                        .ne(EiFpkjRequest::getOrderamount, "0")
                        .lt(EiFpkjRequest::getFpSqcs, "5")//申请次数小于五
                        .orderByDesc(EiFpkjRequest::getInvoicetype)
                        .orderByAsc(EiFpkjRequest::getSfrq)

        );
        List<EiFpkjRequest> records = eiFpkjRequestPage.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            //xxjl("没有查询到需要开票的记录");
            return;
        }

        List<EiFpkjMx> eiFpkjMxList = eiFpkjMxService.lambdaQuery()
                .in(EiFpkjMx::getLsbh, records.stream().map(EiFpkjRequest::getLsbh).collect(Collectors.toList()))
                .list();
        //锁定开票记录
        eiFpkjRequestService.lambdaUpdate()
                .set(EiFpkjRequest::getClLock, "1")
                .in(EiFpkjRequest::getLsbh, eiFpkjMxList.stream().map(EiFpkjMx::getLsbh).collect(Collectors.toList()))
                .update();

        for (EiFpkjRequest item : records) {
            try {
                String result = "";
                Kprxx kprxx = null;
                if (item.getInvoicetype().equals(2)) {
                    JSONObject jsonObject = new JSONObject();
                    if (StringUtil.isNotEmpty(item.getBillstatus()) && item.getBillstatus().equals("16")) {
                        xxjl("红字确认单重推：" + (String.format("[流水编号：%s]", item.getLsbh())));
                        jsonObject = RedInvoiceApplyFor(item);
                    } else if (StringUtil.isEmpty(item.getNnwFplsh())) {
                        jsonObject = RedInvoiceApplyFor(item);
                    } else {
                        jsonObject = RedInvoiceQuery(item.getNnwFplsh(), item.getLsbh());
                    }
                    if (StringUtil.isNull(jsonObject) || jsonObject.isEmpty()) {
                        xxjl(String.format("流水编号：[%s],没有获取到红字确认单相关记录！", item.getLsbh()));
                        continue;
                    }
                    ReverseInvoice reverseInvoice = new ReverseInvoice();
                    String fpdm = item.getNextinvoicecode();
                    String fphm = item.getNextinvoicenum();
                    if (StringUtil.isNotEmpty(fphm)) {
                        fphm = padLeft(fphm, 8, '0');
                    }
                    if (StringUtil.isNotEmpty(fpdm)) {
                        if (fpdm.length() == 11)
                            fpdm = padLeft(fpdm, 12, '0');
                    }
                    if (item.getInvoiceline().equals("bs")) {
                        reverseInvoice.setElecInvoiceNumber(fphm);
                    } else {
                        reverseInvoice.setInvoiceCode(fpdm);
                        reverseInvoice.setInvoiceNumber(fphm);
                    }
                    reverseInvoice.setOrderNo(item.getLsbh());
                    reverseInvoice.setBillNo(jsonObject.getString("billNo"));
                    reverseInvoice.setBillUuid(jsonObject.getString("billUuid"));
                    reverseInvoice.setTaxNum(dzfpConfig.getTaxnum());
                    reverseInvoice.setInvoiceLine(item.getInvoiceline());
                    String json = JSONObject.toJSONString(reverseInvoice);
                    result = sendPostSyncRequest("nuonuo.OpeMplatform.fastInvoiceRed", json);

                } else {
                    InvoiceOrder order = new InvoiceOrder();
                    InvoiceMain main = new InvoiceMain();
                    main.setSalerTaxNum(dzfpConfig.getTaxnum());
                    main.setListFlag(0);
                    if (item.getPushmode().trim().equals("0")) {
                        if (StringUtil.isNotEmpty(item.getEmail())) {
                            main.setEmail(item.getEmail());
                            main.setPushMode(item.getPushmode().trim());
                        }
                    }
//                    else if (item.getPushmode().trim().equals("1")) {
//                        if (StringUtil.isNotEmpty(item.getBuyerphone())) {
//                            main.setBuyerPhone(item.getBuyerphone());
//                            main.setPushMode(item.getPushmode().trim());
//                        }
//                    }
//                    else if (item.getPushmode().trim().equals("2")) {
//                        if (StringUtil.isNotEmpty(item.getBuyerphone()) && StringUtil.isNotEmpty(item.getEmail())) {
//                            main.setBuyerPhone(item.getBuyerphone());
//                            main.setEmail(item.getEmail());
//                            main.setPushMode(item.getPushmode().trim());
//                        }
//                    }
                    else {
                        main.setPushMode("-1");
                    }
                    main.setShowCheckerType("0");
                    //判断微信或支付宝开票人默认
//                    if (item.getClerk().equals("微信支付") || item.getClerk().equals("支付宝支付")) {
//                        item.setClerk(dzfpConfig.getWxorzfbmrkpr());
//                    }
                    //判断开票人
                    String strkprxx = dzfpConfig.getKprxx();
                    List<Kprxx> kprxxList = JSONArray.parseArray(strkprxx, Kprxx.class);
                    kprxx = kprxxList.stream().filter(e -> e.getMc().equals(item.getClerk())).findFirst().orElse(null);
                    if (StringUtil.isNull(kprxx)) {
//                        Random random = new Random();
//                        kprxx = kprxxList.get(random.nextInt(kprxxList.size()));
                        EiKprpz eiKprpz = eiKprpzService.lambdaQuery()
                                .eq(EiKprpz::getIsdisabled, "1")
                                .one();
                        kprxx = kprxxList.stream().filter(e -> e.getMc().equals(eiKprpz.getKprxm())).findFirst().orElse(null);
                    }
//                    kprxx = kprxxMapList.stream().filter(e -> e.getMc().equals(item.getClerk())).findFirst().orElse(null);
//                    if (StringUtil.isNull(kprxx)) {
//                        kprxx = kprxxMapList.get(0);
//                    }
                    main.setExtensionNumber(kprxx.getFjh());
                    main.setClerk(kprxx.getMc());
                    main.setRemark(item.getRemark());
                    main.setInvoiceType(item.getInvoicetype());
                    main.setBuyerName(item.getBuyername());
                    main.setBuyerTaxNum(StringUtil.isNotEmpty(item.getBuyertaxnum()) ? item.getBuyertaxnum() : "");
                    String buyeraccount = StringUtil.isNotEmpty(item.getBuyerbank()) ? item.getBuyerbank() : "";
                    buyeraccount = buyeraccount + (StringUtil.isNotEmpty(item.getBuyeraccount()) ? item.getBuyeraccount() : "");

                    String buyeraddress = StringUtil.isNotEmpty(item.getBuyeraddress()) ? item.getBuyeraddress() : "";
                    buyeraddress = buyeraddress + (StringUtil.isNotEmpty(item.getBuyertel()) ? item.getBuyertel() : "");
                    if (StringUtil.isNotEmpty(buyeraccount)) {
                        main.setBuyerAccount(buyeraccount);
                    }
                    if (StringUtil.isNotEmpty(buyeraddress)) {
                        main.setBuyerAddress(buyeraddress);
                    }
                    main.setOrderNo(item.getLsbh());
                    main.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.getSfrq()));
                    main.setInvoiceLine(item.getInvoiceline());
                    main.setBuyerTel(item.getBuyertel());
                    main.setSalerAccount(item.getSalerbank() + item.getSaleraccount());
                    //3安装服务、10、11建筑服务
                    if (item.getYhlx().equals(3) || item.getYhlx().equals(10) || item.getYhlx().equals(11)) {
                        InvoiceBuildingInfo invoiceBuildingInfo = new InvoiceBuildingInfo();
                        invoiceBuildingInfo.setItemName(item.getListname());
                        invoiceBuildingInfo.setBuildingAddress("凉山彝族自治州会东县");
                        invoiceBuildingInfo.setDetailedAddress(item.getBzAddr());
                        invoiceBuildingInfo.setLandVatItemNo("");
                        invoiceBuildingInfo.setCrossCityFlag("0");
                        main.setSpecificFactor("3");
                        main.setInvoiceBuildingInfo(invoiceBuildingInfo);
                        List<InvoiceDetail> invoiceDetailList = new ArrayList<>();
                        for (EiFpkjMx eiFpkjMx : eiFpkjMxList.stream()
                                .filter(
                                        x -> x.getLsbh().equals(item.getLsbh())
                                )
                                .collect(Collectors.toList())) {
                            InvoiceDetail invoiceDetail = new InvoiceDetail();
                            BigDecimal taxIncludedAmount;
                            BigDecimal taxExcludedAmount;
                            BigDecimal tax = BigDecimal.valueOf(eiFpkjMx.getTax());
                            BigDecimal spje = BigDecimal.valueOf(eiFpkjMx.getTaxincludedamount());
                            taxIncludedAmount = spje;
                            taxExcludedAmount = spje.subtract(tax);
                            invoiceDetail.setWithTaxFlag("1");
                            invoiceDetail.setTaxIncludedAmount(taxIncludedAmount.toString());
                            invoiceDetail.setTaxExcludedAmount(taxExcludedAmount.toString());
                            invoiceDetail.setGoodsName(eiFpkjMx.getGoodsname());
                            invoiceDetail.setGoodsCode(eiFpkjMx.getGoodscode());
                            invoiceDetail.setTax(eiFpkjMx.getTax().toString());
                            invoiceDetail.setTaxRate(eiFpkjMx.getTaxrate().toString());
                            if (item.getInvoiceline().equals("p")) {
                                invoiceDetail.setFavouredPolicyFlag(eiFpkjMx.getFavouredpolicyflag());
                                if (invoiceDetail.getFavouredPolicyFlag().equals("1")) {
                                    invoiceDetail.setFavouredPolicyName(eiFpkjMx.getFavouredpolicyname());
                                }
                                invoiceDetail.setZeroRateFlag(eiFpkjMx.getZerorateflag());
                            } else {
                                invoiceDetail.setFavouredPolicyFlag(eiFpkjMx.getFavouredpolicyflag());
                            }
                            invoiceDetailList.add(invoiceDetail);
                        }
                        main.setInvoiceDetail(invoiceDetailList);

                    } else {
                        List<InvoiceDetail> invoiceDetailList = new ArrayList<>();
                        for (EiFpkjMx eiFpkjMx : eiFpkjMxList.stream()
                                .filter(
                                        x -> x.getLsbh().equals(item.getLsbh())
                                )
                                .collect(Collectors.toList())) {
                            InvoiceDetail invoiceDetail = new InvoiceDetail();
                            BigDecimal taxIncludedAmount;
                            BigDecimal taxExcludedAmount;
                            BigDecimal tax = BigDecimal.valueOf(eiFpkjMx.getTax());
                            BigDecimal spje = BigDecimal.valueOf(eiFpkjMx.getTaxincludedamount());
                            taxIncludedAmount = spje;
                            taxExcludedAmount = spje.subtract(tax);
                            if (StringUtil.isNotEmpty(eiFpkjMx.getSpectype())) {
                                invoiceDetail.setSpecType(eiFpkjMx.getSpectype());
                            } else {
                                invoiceDetail.setSpecType("无");
                            }
                            invoiceDetail.setWithTaxFlag("1");
                            invoiceDetail.setTaxIncludedAmount(taxIncludedAmount.toString());
                            invoiceDetail.setTaxExcludedAmount(taxExcludedAmount.toString());

                            if (StringUtil.isNotNull(eiFpkjMx.getPrice()) &&
                                    eiFpkjMx.getPrice() != 0 &&
                                    StringUtil.isNotNull(eiFpkjMx.getNum()) &&
                                    eiFpkjMx.getNum() != 0
                            ) {
                                invoiceDetail.setNum(eiFpkjMx.getNum().toString());
                                invoiceDetail.setPrice(eiFpkjMx.getPrice().toString());
                            }
                            invoiceDetail.setGoodsName(eiFpkjMx.getGoodsname());
                            //611的重写商品名称与规格型号
                            if ("611".equals(eiFpkjMx.getGoodscode())) {
                                invoiceDetail.setGoodsName("不征增值税自来水");
                                invoiceDetail.setSpecType(eiFpkjMx.getGoodsname());
                            }
                            //自来水规格信型号重写
                            if ("自来水".equals(eiFpkjMx.getGoodsname())) {
                                invoiceDetail.setSpecType("");
                            }
                            invoiceDetail.setGoodsCode(eiFpkjMx.getGoodscode());
                            invoiceDetail.setTax(eiFpkjMx.getTax().toString());
                            invoiceDetail.setTaxRate(eiFpkjMx.getTaxrate().toString());
                            invoiceDetail.setUnit(eiFpkjMx.getUnit());
                            if (item.getInvoiceline().equals("p")) {
                                invoiceDetail.setFavouredPolicyFlag(eiFpkjMx.getFavouredpolicyflag());
                                if (invoiceDetail.getFavouredPolicyFlag().equals("1")) {
                                    invoiceDetail.setFavouredPolicyName(eiFpkjMx.getFavouredpolicyname());
                                }
                                invoiceDetail.setZeroRateFlag(eiFpkjMx.getZerorateflag());
                            } else {
                                invoiceDetail.setFavouredPolicyFlag(eiFpkjMx.getFavouredpolicyflag());
                            }
                            invoiceDetailList.add(invoiceDetail);
                        }
                        main.setInvoiceDetail(invoiceDetailList);
                    }
                    order.setOrder(main);
                    String json = JSONObject.toJSONString(order);
                    xxjl("输出信息：" + json);
                    result = sendPostSyncRequest("nuonuo.OpeMplatform.requestBillingNew", json);

                }
                JSONObject info = JSONObject.parseObject(result);
                if (info.get("code").equals("E0000")) {
                    xxjl(item.getLsbh() +
                            (item.getInvoicetype().equals(2) ? "开具红票" : "开具蓝票") +
                            info.get("describe") +
                            String.format("[发票流水号：%s]", info.get("result")));
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getNnwFplsh, JSONObject.parseObject(info.get("result").toString()).get("invoiceSerialNum"))
                            .set(EiFpkjRequest::getClLock, 0)
                            .set(EiFpkjRequest::getClCljg, 3)
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .set(StringUtil.isNotNull(kprxx), EiFpkjRequest::getClerk, kprxx.getMc())
                            .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                            .update();
                } else {
                    xxjl(item.getLsbh() +
                            (item.getInvoicetype().equals(2) ? "开具红票" : "开具蓝票") + "-开票失败：" +
                            info.get("describe"));
                    xxjl(item.getLsbh() +
                            (item.getInvoicetype().equals(2) ? "开具红票" : "开具蓝票") + "-开票失败返回参数：" + info);
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getClLock, 1)
                            .set(EiFpkjRequest::getClCljg, 2)
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .set(EiFpkjRequest::getClRemessage, info.get("describe"))
                            .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                            .update();
                }
            } catch (Exception e) {
                xxjl("电子发票开具/红冲报错：" + e.getMessage());
            }
        }
    }

    /**
     * 发票查询
     */
    public void fpcxTask() {
//        if (!dlztyz()) {
//            return;
//        }
        try {
            Page page = new Page<>(1, 1000);
            Page<EiFpkjRequest> eiFpkjRequestPage = eiFpkjRequestService.page(page,
                    new QueryWrapper<EiFpkjRequest>().lambda()
                            .eq(EiFpkjRequest::getFpSfkp, 1)
                            .eq(EiFpkjRequest::getClCljg, 3)
                            .eq(EiFpkjRequest::getClLock, 0)
                            .isNotNull(EiFpkjRequest::getNnwFplsh)
                            .orderByDesc(EiFpkjRequest::getInvoicetype)
                            .orderByAsc(EiFpkjRequest::getSfrq)
            );
            List<EiFpkjRequest> records = eiFpkjRequestPage.getRecords();
            if (records.size() == 0) {
                //xxjl("没有查询到需要同步的开票记录！");
                return;
            }
            xxjl("电子发票信息同步中...");
            List<List<EiFpkjRequest>> lists = Lists.partition(records, 50);
            for (List<EiFpkjRequest> item : lists) {
                JSONArray array = new JSONArray();
                for (EiFpkjRequest eiFpkjRequest : item) {
                    array.add(eiFpkjRequest.getNnwFplsh());
                }
                cxfpinfo(array);
            }

        } catch (
                Exception e) {
            xxjl("电子发票查询报错：" + e.getMessage());
        }

    }

    public void fpcx() {
        JSONArray array = new JSONArray();
        array.add("26040715000319030345");
        //fpcx(array);
        cxfpinfo(array);
    }

    /**
     * 发票重推
     */
    public void fpctTask() {

        if (!dlztyz()) {
            return;
        }
        Page page = new Page<>(1, 1001);
        Page<EiFpkjRequest> eiFpkjRequestPage = eiFpkjRequestService.page(page,
                new QueryWrapper<EiFpkjRequest>().lambda()
                        .eq(EiFpkjRequest::getClLock, 1)
                        .eq(EiFpkjRequest::getClCljg, 5)
                        .eq(EiFpkjRequest::getFpSfkp, 1)
                        .isNotNull(EiFpkjRequest::getNnwFplsh)
                        .orderByAsc(EiFpkjRequest::getSfrq)

        );
        List<EiFpkjRequest> records = eiFpkjRequestPage.getRecords();
        if (records.size() == 0) {
            //xxjl("没有查询到需要开票重推的记录的记录！");
            return;
        }
        for (EiFpkjRequest item : records) {
            try {
                //判断微信或支付宝开票人默认
//                if (item.getClerk().equals("微信支付") || item.getClerk().equals("支付宝支付")) {
//                    item.setClerk(dzfpConfig.getWxorzfbmrkpr());
//                }
//                Kprxx kprxx = kprxxMapList.stream().filter(e -> e.getMc().equals(item.getClerk())).findFirst().orElse(null);
//                if (StringUtil.isNotNull(kprxx)) {
//                    digiAccounts = kprxx.getSj();
//                } else {
//                    digiAccounts = kprxxMapList.get(0).getSj();
//                }
                String strkprxx = dzfpConfig.getKprxx();
                List<Kprxx> kprxxList = JSONArray.parseArray(strkprxx, Kprxx.class);
                Kprxx kprxx = kprxxList.stream().filter(e -> e.getMc().equals(item.getClerk())).findFirst().orElse(null);
                if (StringUtil.isNull(kprxx)) {
                    Random random = new Random();
                    kprxx = kprxxList.get(random.nextInt(kprxxList.size()));
                }
                digiAccounts = kprxx.getSj();
                xxjl(String.format("电子发票重推中...  重推账号：%s！", digiAccounts));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("fpqqlsh", item.getLsbh());
                jsonObject.put("orderno", item.getLsbh());
                jsonObject.put("digiAccount", digiAccounts);
                jsonObject.put("invoiceCode", "");
                jsonObject.put("invoiceNumStart", "");
                jsonObject.put("invoiceNumEnd", "");
                String json = JSONObject.toJSONString(jsonObject);
                String result = sendPostSyncRequest("nuonuo.OpeMplatform.reInvoice", json);
                if (StringUtil.isNotEmpty(result)) {
                    JSONObject info = JSONObject.parseObject(result);
                    if (info.get("code").equals("E0000")) {
                        eiFpkjRequestService.lambdaUpdate()
                                .set(EiFpkjRequest::getClLock, 0)
                                .set(EiFpkjRequest::getClCljg, 3)
                                .set(EiFpkjRequest::getClClsj, new Date())
                                .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                                .update();
                    } else {
                        xxjl(item.getLsbh() + "重推失败：" + info.get("describe"));
                        eiFpkjRequestService.lambdaUpdate()
                                .set(EiFpkjRequest::getClLock, 1)
                                .set(EiFpkjRequest::getClCljg, 2)
                                .set(EiFpkjRequest::getClClsj, new Date())
                                .set(EiFpkjRequest::getClRemessage, info.get("describe"))
                                .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                                .update();
                    }
                }
            } catch (Exception e) {
                xxjl("电子发票重推报错：" + e.getMessage());
            }
        }
    }

    public void fpcx(JSONArray array) {
        JSONObject data = new JSONObject();
        data.put("orderNos", array);
        data.put("isOfferInvoiceDetail", "1");
        String json = data.toJSONString();
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.queryInvoiceResult", json);
        if (StringUtil.isEmpty(result)) {
            xxjl("电子发票信息同步失败，返回数据为空！");
            return;
        }
        JSONObject info = JSONObject.parseObject(result);
        if (info.get("code").equals("E0000")) {
            JSONArray dataArray = info.getJSONArray("result");
            for (JSONObject jsonObject : dataArray.toJavaList(JSONObject.class)) {
                xxjl("电子发票同步返回信息：" + jsonObject.toJSONString());
            }
        }
    }

    /**
     * 红字确认单撤销接口
     */
    public void hzqrdcx(String ss) {
        JSONObject data = new JSONObject();
        data.put("identity", "0");
        data.put("billId", ss);
        String json = data.toJSONString();
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.confirmInfoCancel", json);
        if (StringUtil.isEmpty(result)) {
            xxjl("电子发票信息红字确认单申请撤销失败，返回数据为空！");
            return;
        }
        JSONObject info = JSONObject.parseObject(result);
        xxjl("电子发票同步返回信息：" + result);
    }


    /**
     * 发票删除
     */
    public void fpscTask() {
        if (!dlztyz()) {
            return;
        }
        //查询需要删除的记录
        Page page = new Page<>(1, 50);
        Page<EiFpkjRequest> eiFpkjRequestPage = eiFpkjRequestService.page(page,
                new QueryWrapper<EiFpkjRequest>().lambda()
                        .select(EiFpkjRequest::getLsbh)
                        .eq(EiFpkjRequest::getClLock, 0)
                        .eq(EiFpkjRequest::getClCljg, 9)
                        .isNotNull(EiFpkjRequest::getNnwFplsh)
                        .orderByAsc(EiFpkjRequest::getSfrq)
        );
        List<EiFpkjRequest> records = eiFpkjRequestPage.getRecords();
        if (records.size() == 0) {
            //xxjl("没有查询到需要删除记录的记录！");
            return;
        }
        for (EiFpkjRequest item : records) {
            fpsc(item.getLsbh());
        }
    }

    /**
     * 发票删除
     */
    public void fpsc() {
        fpsc("30DFE5AA1F4B40C99124460FFBC308CE");
    }

    private void fpsc(String orderNo) {
        JSONObject data = new JSONObject();
        data.put("orderNo", orderNo);
        data.put("saleTaxnum", dzfpConfig.getTaxnum());
        String json = data.toJSONString();
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.delInvoice", json);
        if (StringUtil.isEmpty(result)) {
            xxjl(String.format("流水号：%s发票删除失败，返回数据为空！", orderNo));
            return;
        }
        JSONObject info = JSONObject.parseObject(result);
        xxjl("电子发票同步返回信息：" + result);
        if (info.get("code").equals("E0000")) {
            eiFpkjRequestService.lambdaUpdate()
                    .set(EiFpkjRequest::getClCljg, 0)
                    .set(EiFpkjRequest::getClLock, 0)
                    .set(EiFpkjRequest::getClRecode, "")
                    .set(EiFpkjRequest::getNnwFplsh, "")
                    .set(EiFpkjRequest::getClRemessage, "")
                    .eq(EiFpkjRequest::getLsbh, orderNo)
                    .update();
        }
    }

    public void fpcxjfTask() {
        if (!dlztyz()) {
            return;
        }
        Page page = new Page<>(1, 1001);
        Page<EiFpkjRequest> eiFpkjRequestPage = eiFpkjRequestService.page(page,
                new QueryWrapper<EiFpkjRequest>().lambda()
                        .eq(EiFpkjRequest::getClLock, 0)
                        .eq(EiFpkjRequest::getClCljg, 1)
                        .eq(EiFpkjRequest::getFpSfkp, 2)
                        .eq(EiFpkjRequest::getJfYxbz, 0)
                        .lt(EiFpkjRequest::getFpSqcs, "5")//申请次数小于五
                        .orderByAsc(EiFpkjRequest::getSfrq)
        );
        List<EiFpkjRequest> records = eiFpkjRequestPage.getRecords();
        if (records.size() == 0) {
            //xxjl("没有查询到需要开票重新交付的的记录！");
            return;
        }
        for (EiFpkjRequest item : records) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("taxnum", dzfpConfig.getTaxnum());
                jsonObject.put("invoiceNum", item.getInvoicenum());
                if (item.getPushmode().trim().equals("0")) {
                    jsonObject.put("mail", item.getEmail());
                } else if (item.getPushmode().trim().equals("1")) {
                    jsonObject.put("phone", item.getBuyerphone());
                } else if (item.getPushmode().trim().equals("2")) {
                    jsonObject.put("mail", item.getEmail());
                    jsonObject.put("phone", item.getBuyerphone());
                }
                String json = JSONObject.toJSONString(jsonObject);
                String result = sendPostSyncRequest("nuonuo.OpeMplatform.deliveryInvoice", json);
                if (StringUtil.isNotEmpty(result)) {
                    JSONObject info = JSONObject.parseObject(result);
                    if (info.get("code").equals("E0000")) {
                        eiFpkjRequestService.lambdaUpdate()
                                .set(EiFpkjRequest::getJfYxbz, 1)
                                .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                                .update();
                    } else {
                        eiFpkjRequestService.lambdaUpdate()
                                .setSql("FP_SQCS=nvl(FP_SQCS,0)+1")
                                .eq(EiFpkjRequest::getLsbh, item.getLsbh())
                                .update();
                        xxjl(item.getLsbh() + "电子发票重交付失败：" + info.get("describe"));
                    }
                }
            } catch (Exception e) {
                xxjl("电子发票重交付报错：" + e.getMessage());
            }
        }
    }

    /**
     * 登录状态
     */
    public void dlztTask() {
        try {
            kprxxMapList = new ArrayList<>();
            boolean loginzt_ = false;
            boolean dlzt = false;
            boolean zrzt = false;
            String kprxx = dzfpConfig.getKprxx();
            List<Kprxx> kprxxList = JSONArray.parseArray(kprxx, Kprxx.class);
            for (Kprxx item : kprxxList) {
                xxjl("开始获取登录状态信息！JSON:" + JSONObject.toJSONString(item));
                //获取登录状态信息
                String result = RzLoginStatus(item.getFjh(), "2");
                JSONObject info = JSONObject.parseObject(result);
                if (info.getString("code").equals("E0000")) {
                    JSONObject data = info.getJSONObject("result");
                    if (data.containsKey("certificationStatus") && data.getString("certificationStatus").equals("1")) {
                        //获取认证状态信息
                        result = RzLoginStatus(item.getFjh(), "1");
                        info = JSONObject.parseObject(result);
                        if (info.getString("code").equals("E0000")) {
                            data = info.getJSONObject("result");
                            if (data.containsKey("certificationStatus") && data.getString("certificationStatus").equals("1")) {
                                loginzt_ = true;
                                kprxxMapList.add(item);
                                xxjl(item.getMc() + "已登录已认证！");
                            }
                            if (data.containsKey("certificationStatus") && data.getString("certificationStatus").equals("2")) {
                                xxjl("账号已登录但未认证，请到诺税平台认证！");
                            }
                        }
                    }
                }
            }
            String bz = "";
            String dlrzzt = "";
            if (!dlzt) {
                dlrzzt = "0";
                bz = String.format("%s登录认证验证：未登录", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
            if (dlzt && !zrzt) {
                dlrzzt = "1";
                bz = String.format("%s登录认证验证：已登录未认证", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
            if (dlzt && zrzt) {
                dlrzzt = "2";
                bz = String.format("%s登录认证验证：已登录已认证", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
            loginzt = loginzt_;
        } catch (Exception e) {
            xxjl("账号登录报错：" + e.getMessage());
        }

    }

    /**
     * 公共请求接口
     */
    private String sendPostSyncRequest(String method, String json) {
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，由企业自己生成32位随机码
        log.info("请求诺税通参数 ==============================> {}", json);
        String result = sdk.sendPostSyncRequest(
                dzfpConfig.getUrl(),
                senid,
                dzfpConfig.getAppKey(),
                dzfpConfig.getAppSecret(),
                dzfpConfig.getToken(),
                dzfpConfig.getTaxnum(),
                method,
                json);
        log.info("诺税通响应 ==============================> {}", result);
        return result;
    }

    /**
     * 验证登录状态
     *
     * @return
     */
    private Boolean dlztyz() {
        if (!loginzt) {
            String msg = "请登录电子发票服务平台，使用短信验证码登录";
            xxjl(msg);
            return loginzt;
        }
        return loginzt;
    }

    /**
     * 登录认证状态获取
     *
     * @param extensionNumber 分机号
     * @param queryType       查询类型，1：认证状态，2：登录状态
     * @return 返回结果json
     */
    private String RzLoginStatus(String extensionNumber, String queryType) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("authQrType", dzfpConfig.getTaxnum());
        jsonObject.put("eleAccount", "");
        jsonObject.put("extensionNumber", extensionNumber);
        jsonObject.put("deptId", "");
        jsonObject.put("clerkId", "");
        jsonObject.put("authId", "");
        jsonObject.put("queryType", queryType);
        String json = jsonObject.toJSONString();
        return sendPostSyncRequest("nuonuo.OpeMplatform.getCertificationStatus", json);
    }

    /**
     * 消息记录
     *
     * @param msg 记录内容
     */
    private void xxjl(String msg) {
        SimpleDateFormat srcSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        msg = srcSdf.format(new Date()) + "：" + msg;
        log.info(msg);
    }

    /**
     * 红字确认单申请
     *
     * @param eiFpkjRequest 发票信息
     * @return 返回指定对象信息
     */
    private JSONObject RedInvoiceApplyFor(EiFpkjRequest eiFpkjRequest) {
        String fpdm = eiFpkjRequest.getNextinvoicecode();
        String fphm = eiFpkjRequest.getNextinvoicenum();
        if (StringUtil.isNotEmpty(fphm)) {
            fphm = padLeft(fphm, 8, '0');
        }
        if (StringUtil.isNotEmpty(fpdm)) {
            if (fpdm.length() == 11)
                fpdm = padLeft(fpdm, 12, '0');
        }
        RedInvoiceApplyFor redInvoiceApplyFor = new RedInvoiceApplyFor();
        redInvoiceApplyFor.setBlueInvoiceLine(eiFpkjRequest.getInvoiceline());
        redInvoiceApplyFor.setApplySource("0");
        redInvoiceApplyFor.setBlueInvoiceNumber(fphm);
        redInvoiceApplyFor.setBlueInvoiceCode(fpdm);
        redInvoiceApplyFor.setSellerTaxNo(dzfpConfig.getTaxnum());
        redInvoiceApplyFor.setBuyerName(eiFpkjRequest.getBuyername());
        redInvoiceApplyFor.setBuyerTaxNo(eiFpkjRequest.getBuyertaxnum());
        redInvoiceApplyFor.setRedReason("2");
        if (eiFpkjRequest.getYhlx().equals(2)) {
            redInvoiceApplyFor.setRedReason("3");
        }
//        //判断微信或支付宝开票人默认
//        if (eiFpkjRequest.getClerk().equals("微信支付") || eiFpkjRequest.getClerk().equals("支付宝支付")) {
//            eiFpkjRequest.setClerk(dzfpConfig.getWxorzfbmrkpr());
//        }
//        Kprxx kprxx = kprxxMapList.stream().filter(e -> e.getMc().equals(eiFpkjRequest.getClerk())).findFirst().orElse(null);
//        if (StringUtil.isNotNull(kprxx)) {
//            redInvoiceApplyFor.setExtensionNumber(kprxx.getFjh());
//        } else {
//            xxjl("开票人未登录！");
//            return null;
//            //redInvoiceApplyFor.setExtensionNumber(kprxxMapList.get(0).getFjh());
//        }
        //判断开票人
        String strkprxx = dzfpConfig.getKprxx();
        List<Kprxx> kprxxList = JSONArray.parseArray(strkprxx, Kprxx.class);
        Kprxx kprxx = kprxxList.stream().filter(e -> e.getMc().equals(eiFpkjRequest.getClerk())).findFirst().orElse(null);
        if (StringUtil.isNotNull(kprxx)) {
            redInvoiceApplyFor.setExtensionNumber(kprxx.getFjh());
        }
        String json = JSONObject.toJSONString(redInvoiceApplyFor);
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.saveInvoiceRedConfirm", json);
        xxjl(result);
        JSONObject info = JSONObject.parseObject(result);
        if (info.getString("code").equals("E0000")) {
            String billId = info.getString("result");
            eiFpkjRequestService.lambdaUpdate()
                    .set(EiFpkjRequest::getNnwFplsh, billId)
                    .set(EiFpkjRequest::getClCljg, 6)
                    .set(EiFpkjRequest::getClLock, 0)
                    .set(EiFpkjRequest::getBillstatus, "")
                    .setSql("FP_SQCS=nvl(FP_SQCS,0)+1")
                    .eq(EiFpkjRequest::getLsbh, eiFpkjRequest.getLsbh())
                    .update();
            return RedInvoiceQuery(billId, eiFpkjRequest.getLsbh());
        }
        return null;
    }

    /**
     * 红字确认单查询
     *
     * @param billId 返回的单据ID
     * @param lsbh   流水编号
     * @return 返回指定对象信息
     */
    private JSONObject RedInvoiceQuery(String billId, String lsbh) {
        RedInvoiceQuery redInvoiceQuery = new RedInvoiceQuery();
        redInvoiceQuery.setBillId(billId);
        redInvoiceQuery.setIdentity("0");
        String json = JSONObject.toJSONString(redInvoiceQuery);
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.queryInvoiceRedConfirm", json);
        JSONObject info = JSONObject.parseObject(result);
        JSONObject resultData = new JSONObject();
        if (info.getString("code").equals("E0000")) {
            JSONObject data = info.getJSONObject("result");
            JSONArray jsonArray = data.getJSONArray("list");
            if (CollectionUtil.isNotEmpty(jsonArray)) {
                if (String.valueOf(jsonArray.getJSONObject(0).get("openStatus")).equals("1")) {
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getClLock, 0)
                            .set(EiFpkjRequest::getClCljg, 3)
                            .set(EiFpkjRequest::getNnwFplsh, jsonArray.getJSONObject(0).get("invoiceSerialNum"))
                            .eq(EiFpkjRequest::getLsbh, lsbh)
                            .update();
                    log.info(String.format("红字发票已开具，红票流水号：%s，流水编号：%s，红字确单申请号：%s"
                            , jsonArray.getJSONObject(0).get("billId")
                            , lsbh
                            , billId
                    ));
                }
                if (String.valueOf(jsonArray.getJSONObject(0).get("openStatus")).equals("0")
                        && jsonArray.getJSONObject(0).get("billStatus").equals("01")) {
                    if (StringUtil.isNotEmpty(String.valueOf(jsonArray.getJSONObject(0).get("billNo")))
                            && StringUtil.isNotEmpty(String.valueOf(jsonArray.getJSONObject(0).get("billUuid")))
                            && StringUtil.isNotEmpty(String.valueOf(jsonArray.getJSONObject(0).get("billId")))) {
                        resultData.put("billNo", jsonArray.getJSONObject(0).get("billNo"));
                        resultData.put("billUuid", jsonArray.getJSONObject(0).get("billUuid"));
                        resultData.put("billId", jsonArray.getJSONObject(0).get("billId"));
                    }
                    return resultData;
                } else if (String.valueOf(jsonArray.getJSONObject(0).get("openStatus")).equals("0")
                        && jsonArray.getJSONObject(0).get("billStatus").equals("16")
                        && !jsonArray.getJSONObject(0).get("billMessage").equals("请求超时")) {
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getBillstatus, 16)
                            .set(EiFpkjRequest::getClRemessage, jsonArray.getJSONObject(0).get("billMessage"))
                            .eq(EiFpkjRequest::getLsbh, lsbh)
                            .update();
                } else if (String.valueOf(jsonArray.getJSONObject(0).get("openStatus")).equals("0")
                        && "05,06,07,08,16".indexOf(jsonArray.getJSONObject(0).get("billStatus").toString()) > 0
                        && !jsonArray.getJSONObject(0).get("billMessage").equals("请求超时")) {
                    String billMessage = jsonArray.getJSONObject(0).get("billMessage").toString();
                    if (StringUtil.isEmpty(billMessage)) {
                        if (jsonArray.getJSONObject(0).get("billStatus").equals("05")) {
                            billMessage = "红字确认单：作废（销方录入购方否认）";
                        }
                        if (jsonArray.getJSONObject(0).get("billStatus").equals("06")) {
                            billMessage = "红字确认单：作废（购方录入销方否认）";
                        }
                        if (jsonArray.getJSONObject(0).get("billStatus").equals("07")) {
                            billMessage = "红字确认单：作废（超72小时未确认）";
                        }
                        if (jsonArray.getJSONObject(0).get("billStatus").equals("08")) {
                            billMessage = "红字确认单： 作废（发起方已撤销）";
                        }
                        if (jsonArray.getJSONObject(0).get("billStatus").equals("16")) {
                            billMessage = "红字确认单：作废（确认后撤销）";
                        }
                    }
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getClLock, 1)
                            .set(EiFpkjRequest::getClCljg, 2)
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .set(EiFpkjRequest::getClRemessage, billMessage)
                            .eq(EiFpkjRequest::getLsbh, lsbh)
                            .update();
                } else if (String.valueOf(jsonArray.getJSONObject(0).get("openStatus")).equals("0")
                        && jsonArray.getJSONObject(0).get("billStatus").equals("02")) {
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getClRemessage, "购方已入账，需联系购方进电子税务局进行冲红确认！")
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .eq(EiFpkjRequest::getLsbh, lsbh)
                            .eq(EiFpkjRequest::getBillstatus, 02)
                            .eq(EiFpkjRequest::getClCljg, 2)
                            .eq(EiFpkjRequest::getClLock, 1)
                            .update();
                }
            }
        } else {
            eiFpkjRequestService.lambdaUpdate()
                    .set(EiFpkjRequest::getClLock, 0)
                    .eq(EiFpkjRequest::getLsbh, lsbh)
                    .update();
        }
        return resultData;
    }

    /**
     * 补全字符串长度
     *
     * @param input   原字符串
     * @param length  补全长度
     * @param padChar 补全字符
     * @return 返回新字符串
     */
    public String padLeft(String input, int length, char padChar) {
        StringBuilder sb = new StringBuilder(input);
        while (sb.length() < length) {
            sb.insert(0, padChar);
        }
        return sb.toString();
    }

    /**
     * 查询发票信息
     *
     * @param array 诺诺网发票流水号集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void cxfpinfo(JSONArray array) {
        JSONObject data = new JSONObject();
        data.put("serialNos", array);
        data.put("isOfferInvoiceDetail", "1");
        String json = data.toJSONString();
        String result = sendPostSyncRequest("nuonuo.OpeMplatform.queryInvoiceResult", json);
        if (StringUtil.isEmpty(result)) {
            xxjl("电子发票信息同步失败，返回数据为空！");
            return;
        }
        JSONObject info = JSONObject.parseObject(result);
        if (info.get("code").equals("E0000")) {
            JSONArray dataArray = info.getJSONArray("result");
            for (JSONObject jsonObject : dataArray.toJavaList(JSONObject.class)) {
                if (jsonObject.get("status").equals("2")) {
                    Boolean tf = false;
                    String orderNo = jsonObject.getString("orderNo");
                    String strdate = new SimpleDateFormat("yyyyMM").format(new Date());
                    String pdfUrl = dzfpConfig.getPdfpath() + strdate;
                    EiFpkjRequest eiFpkjRequest = eiFpkjRequestService.getOne(new QueryWrapper<EiFpkjRequest>().lambda()
                            .eq(EiFpkjRequest::getLsbh, orderNo));
                    if (eiFpkjRequest == null) {
                        String serialNo = jsonObject.getString("serialNo");
                        eiFpkjRequest = eiFpkjRequestService.getOne(new QueryWrapper<EiFpkjRequest>().lambda()
                                .eq(EiFpkjRequest::getNnwFplsh, serialNo));
                        if (eiFpkjRequest == null) {
                            xxjl(String.format("查询发票信息失败，发票流水号【%s】不存在或流水编号【%s】错误", serialNo, orderNo));
                            continue;
                        }
                        orderNo = eiFpkjRequest.getLsbh();
                    }
                    tf = downloadFile(jsonObject.getString("pdfUrl"), pdfUrl, orderNo + ".pdf");
                    if (!tf) {
                        xxjl("电子发票信息同步失败，下载发票失败！");
                        continue;
                    } else {
                        xxjl(String.format("电子发票下载成功,下载地址：%s/%s.pdf", pdfUrl, orderNo));
                    }
                    String invoiceTime = jsonObject.getString("invoiceTime");
                    String invoiceTimestr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(invoiceTime)));
                    tf = eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getInvoicecode, jsonObject.getString("invoiceCode"))
                            .set(EiFpkjRequest::getInvoicenum, jsonObject.getString("invoiceNo"))
                            .set(EiFpkjRequest::getInvoicetime, invoiceTimestr)
                            .set(EiFpkjRequest::getStatus, jsonObject.getString("status"))
                            .set(EiFpkjRequest::getFpSfkp, 2)
                            .set(EiFpkjRequest::getClLock, 0)
                            .set(EiFpkjRequest::getClCljg, 1)
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .set(EiFpkjRequest::getJfJsurl, jsonObject.getString("pdfUrl"))
                            .set(EiFpkjRequest::getJfPdffilename, orderNo + ".pdf")
                            .set(EiFpkjRequest::getJfYxbz, "1")
                            .set(EiFpkjRequest::getPdfurl, String.format("%s/%s.pdf", pdfUrl, orderNo))
                            .eq(EiFpkjRequest::getLsbh, orderNo)
                            .update();
                    String ywlx = eiFpkjRequest.getYhlx().toString();
                    //invoiceType  1为蓝票  2为红票
                    //String invoiceType = jsonObject.getString("invoiceType");
                    String invoiceType = eiFpkjRequest.getInvoicetype().toString();
                    if (Objects.equals(ywlx, "1")) {
                        //用于判断实收是否存在（由于预开发票）
                        long yysspjxxcount = yySspjxxService.lambdaQuery()
                                .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                .count();
                        if (invoiceType.equals("1")) {
                            if (StringUtil.isNotEmpty(eiFpkjRequest.getIsykfp()) && eiFpkjRequest.getIsykfp().equals("1")) {
                                //水资源费
                                if ("3".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yyQfmxService.lambdaUpdate()
                                            .set(YyQfmx::getFpz3, jsonObject.getString("invoiceCode"))
                                            .set(YyQfmx::getFph3, jsonObject.getString("invoiceNo"))
                                            .eq(YyQfmx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                    try {
                                        eiYkfpLogService.lambdaUpdate()
                                                .set(EiYkfpLog::getSzyfFph, jsonObject.getString("invoiceNo"))
                                                .set(EiYkfpLog::getKpsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(invoiceTimestr))
                                                .eq(EiYkfpLog::getFpglh, eiFpkjRequest.getSfid())
                                                .update();
                                    } catch (Exception e) {
                                        xxjl("电子发票信息同步失败，更新预开发票日志信息失败！");
                                    }
                                }
                                //污水费
                                else if ("2".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yyQfmxService.lambdaUpdate()
                                            .set(YyQfmx::getFpz1, jsonObject.getString("invoiceCode"))
                                            .set(YyQfmx::getFph1, jsonObject.getString("invoiceNo"))
                                            .eq(YyQfmx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                    try {
                                        eiYkfpLogService.lambdaUpdate()
                                                .set(EiYkfpLog::getWsfFph, jsonObject.getString("invoiceNo"))
                                                .set(EiYkfpLog::getKpsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(invoiceTimestr))
                                                .eq(EiYkfpLog::getFpglh, eiFpkjRequest.getSfid())
                                                .update();
                                    } catch (Exception e) {
                                        xxjl("电子发票信息同步失败，更新预开发票日志信息失败！");
                                    }
                                } else {
                                    tf = yyQfmxService.lambdaUpdate()
                                            .set(YyQfmx::getFpz, jsonObject.getString("invoiceCode"))
                                            .set(YyQfmx::getFph, jsonObject.getString("invoiceNo"))
                                            .eq(YyQfmx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                    try {
                                        eiYkfpLogService.lambdaUpdate()
                                                .set(EiYkfpLog::getFpz, jsonObject.getString("invoiceCode"))
                                                .set(EiYkfpLog::getFph, jsonObject.getString("invoiceNo"))
                                                .set(EiYkfpLog::getKpsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(invoiceTimestr))
                                                .eq(EiYkfpLog::getFpglh, eiFpkjRequest.getSfid())
                                                .update();
                                    } catch (Exception e) {
                                        xxjl("电子发票信息同步失败，更新预开发票日志信息失败！");
                                    }
                                }
                            }
                            if (yysspjxxcount > 0) {
                                if ("3".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz3, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph3, jsonObject.getString("invoiceNo"))
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                } else if ("2".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz1, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph1, jsonObject.getString("invoiceNo"))
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                } else {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph, jsonObject.getString("invoiceNo"))
                                            .set(YySspjxx::getFplx, 1)
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                }
                            }
                        } else {
                            if (StringUtil.isNotEmpty(eiFpkjRequest.getIsykfp()) && eiFpkjRequest.getIsykfp().equals("1")) {
                                yyQfmxService.lambdaUpdate()
                                        .set(YyQfmx::getFpz3, "")
                                        .set(YyQfmx::getFph3, "")
                                        .set(YyQfmx::getFpz1, "")
                                        .set(YyQfmx::getFph1, "")
                                        .set(YyQfmx::getFpz, "")
                                        .set(YyQfmx::getFph, "")
                                        .eq(YyQfmx::getFpglh, eiFpkjRequest.getSfid())
                                        .update();
                                //冲红删除无用的记录
                                eiYkfpLogService.remove(new QueryWrapper<EiYkfpLog>().lambda()
                                        .eq(EiYkfpLog::getFpglh, eiFpkjRequest.getSfid())
                                );
                            }
                            if (yysspjxxcount > 0) {
                                if ("3".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz3, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph3, jsonObject.getString("invoiceNo"))
                                            .set(YySspjxx::getFplx, 2)
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                } else if ("2".equals(eiFpkjRequest.getKpywlx())) {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz1, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph1, jsonObject.getString("invoiceNo"))
                                            .set(YySspjxx::getFplx, 2)
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                } else {
                                    tf = yySspjxxService.lambdaUpdate()
                                            .set(YySspjxx::getFpz, jsonObject.getString("invoiceCode"))
                                            .set(YySspjxx::getFph, jsonObject.getString("invoiceNo"))
                                            .set(YySspjxx::getFplx, 2)
                                            .eq(YySspjxx::getFpglh, eiFpkjRequest.getSfid())
                                            .update();
                                }
                            }
                        }
                        if (!tf) {
                            xxjl(String.format("%s更新开票失败：实收信息", orderNo));
                        }
                    } else if (Objects.equals(ywlx, "3") && invoiceType.equals("1")) {
                        xxjl(String.format("报装返回参数：%s", JSONObject.toJSONString(jsonObject)));
                        Map map = new HashMap();
                        map.put("id", eiFpkjRequest.getSfid());
                        map.put("invoiceNo", jsonObject.getString("invoiceNo"));
                        map.put("remark", "");
                        map.put("status", "1");
                        String bzresult = HttpRequestUtil.POSTRequest(
                                dzfpConfig.getBzapidz(),
                                JSONObject.toJSONString(map));
                        if (StringUtil.isNotEmpty(bzresult)) {
                            if (JSONObject.parseObject(bzresult).get("code").equals(0)) {
                                xxjl(String.format("%s：报装回调成功", orderNo));
                            } else {
                                //手动回滚
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                xxjl(String.format("%s更新开票失败：报装信息", orderNo));
                            }
                        } else {
                            //手动回滚
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            xxjl(String.format("%s更新开票失败：报装信息", orderNo));
                        }
                    }
//                    else if (Objects.equals(ywlx, "3")) {
//                        //暂无燃气改造开票
//                        tf = true;
//                        if (!tf) {
//                            xxjl(String.format("%s更新开票失败：燃气改造信息", orderNo));
//                        }
//                    }

                } else if (jsonObject.get("status").equals("22") || jsonObject.get("status").equals("24")) {
                    xxjl("电子发票同步返回信息：" + jsonObject.toJSONString());
                    String orderNo = jsonObject.getString("orderNo");
                    eiFpkjRequestService.lambdaUpdate()
                            .set(EiFpkjRequest::getClLock, 1)
                            .set(EiFpkjRequest::getClCljg, 4)
                            .set(EiFpkjRequest::getClClsj, new Date())
                            .set(EiFpkjRequest::getClRemessage, String.format("返回代码[%s]--%s", jsonObject.getString("status"),
                                    jsonObject.getString("failCause")))
                            .set(EiFpkjRequest::getClRecode, jsonObject.getString("status"))
                            .eq(EiFpkjRequest::getLsbh, orderNo)
                            .update();
                } else {
                    xxjl("电子发票同步返回错误信息：" + jsonObject.get("statusMsg") + "，" + jsonObject.get("failCause"));
                }
            }
        }
    }

    /**
     * 文件下载
     *
     * @param fileUrl  文件下载地址
     * @param savePath 文件保存路径
     * @param fileName 保存文件名
     * @return
     */
    private Boolean downloadFile(String fileUrl, String savePath, String fileName) {

        Boolean tf = false;
        try {
//            String currentDir = System.getProperty("user.dir"); // 获取当前服务运行目录
//            String savePath1 = currentDir + File.separator + "dzfp" + File.separator + fileName;
//            saveUrlToLocal(fileUrl, savePath1);
//            log.info("文件保存路径：{}", savePath1);
            savePath = savePath + "/" + fileName;
            //log.info("文件保存路径：{}", savePath);
            URL url = new URL(fileUrl);
            InputStream inputStream = url.openStream();
            tf = FtpUtil.uploadFile2Ftp(inputStream, savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tf;
    }

    /**
     * 历史数据下载
     */
    public void oldfpxz() {
        List<EiFpkjRequest> list = eiFpkjRequestService.lambdaQuery()
                .isNotNull(EiFpkjRequest::getPdfurl)
                .list();
        for (EiFpkjRequest eiFpkjRequest : list) {
            if (downloadFile(eiFpkjRequest.getJfJsurl(), dzfpConfig.getPdfpath(), eiFpkjRequest.getLsbh() + ".pdf")) {
                eiFpkjRequestService.lambdaUpdate()
                        .set(EiFpkjRequest::getJfPdffilename, eiFpkjRequest.getLsbh() + ".pdf")
                        .set(EiFpkjRequest::getJfYxbz, "1")
                        .set(EiFpkjRequest::getPdfurl, String.format("%s/%s.pdf", dzfpConfig.getPdfpath(), eiFpkjRequest.getLsbh()))
                        .eq(EiFpkjRequest::getLsbh, eiFpkjRequest.getLsbh())
                        .update();
            }
        }
    }

    public void saveUrlToLocal(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);

        // 1. 创建父目录（不存在则自动创建，避免报错）
        Files.createDirectories(Paths.get(savePath).getParent());

        // 2. 打开网络流
        try (InputStream inputStream = url.openStream();
             FileOutputStream outputStream = new FileOutputStream(savePath)) {

            // 3. 缓冲区读写（高效）
            byte[] buffer = new byte[8192];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            System.out.println("文件保存成功：" + savePath);
        }
    }
}
