package com.jkcredit.invoice.service.lowerservice.impl;

import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleQueryResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleRegisterRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.vehicle.VehicleRegisterResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.InvoiceProcessingListModel;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillCountPageRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillCountQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillCountQueryResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillEndRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillEndResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillHistoryEndRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillHistoryEndResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillHistoryStartRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillHistoryStartResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillInvoiceRedQueryModel;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillInvoiceRedQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillInvoiceRedQueryResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillNumFindInvoiceRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillNumFindInvoiceResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillOriginEndRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillOriginEndResponse;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillStartRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillStartResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.common.CommonConstants;
import com.jkcredit.invoice.mapper.binvoce.BillInvoiceMapper;
import com.jkcredit.invoice.mapper.binvoce.HcInvoiceMapper;
import com.jkcredit.invoice.mapper.calculateinfor.MounthAccMapper;
import com.jkcredit.invoice.mapper.calculateinfor.NoCarCalculateInforMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillMapper;
import com.jkcredit.invoice.model.entity.calculate.MounthAcc;
import com.jkcredit.invoice.model.entity.calculate.NoCarCalculateInfor;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.entity.invoice.BillInvoice;
import com.jkcredit.invoice.model.entity.invoice.HcInvoice;
import com.jkcredit.invoice.model.entity.manager.Param;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBill;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBillFileInfo;
import com.jkcredit.invoice.model.vo.MigrateVo;
import com.jkcredit.invoice.service.lowerservice.NoCarService;
import com.jkcredit.invoice.service.lowerservice.vo.HcInvoiceQueryVo;
import com.jkcredit.invoice.service.lowerservice.vo.MonthAccountQueryVo;
import com.jkcredit.invoice.service.manager.ParamService;
import com.jkcredit.invoice.service.nocar.HcInvoiceService;
import com.jkcredit.invoice.service.nocar.NoCarRecService;
import com.jkcredit.invoice.service.nocar.WayBillFileService;
import com.jkcredit.invoice.service.upservice.NoCarInterface;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.MathUtil;
import com.jkcredit.invoice.util.RespR;
import com.jkcredit.invoice.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.jkcredit.invoice.common.CommonConst.A_THOUSAND;
import static com.jkcredit.invoice.common.CommonConst.EIGHT_NUM;
import static com.jkcredit.invoice.common.CommonConst.FIVE_NUM;
import static com.jkcredit.invoice.common.CommonConst.FOR;
import static com.jkcredit.invoice.common.CommonConst.FOR_NUM;
import static com.jkcredit.invoice.common.CommonConst.INTONE;
import static com.jkcredit.invoice.common.CommonConst.INTTOW;
import static com.jkcredit.invoice.common.CommonConst.NE_FIVE_NUM;
import static com.jkcredit.invoice.common.CommonConst.ONE;
import static com.jkcredit.invoice.common.CommonConst.ONE_NUM;
import static com.jkcredit.invoice.common.CommonConst.THREE_NUM;
import static com.jkcredit.invoice.common.CommonConst.TWO_NUM;

/**
 * 无车操作接口
 * @author mumuxigua
 */
@Repository("noCarService")
@Slf4j
public class NoCarServiceImpl implements NoCarService {


    @Autowired
    NoCarInterface noCarInterface;

    @Autowired
    NoCarWaybillMapper noCarWaybillMapper;

    @Autowired
    CustomerCarRecMapper customerCarRecMapper;

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    CustomerRecMapper customerRecMapper;

    @Autowired
    BillInvoiceMapper billInvoiceMapper;

    @Autowired
    NoCarCalculateInforMapper calculateInforMapper;

    @Autowired
    ParamService paramService;

    @Autowired
    NoCarRecService noCarRecService;
    @Autowired
    HcInvoiceService hcInvoiceService;
    @Autowired
    HcInvoiceMapper hcInvoiceMapper;
    @Autowired
    MounthAccMapper mounthAccMapper;
    @Override
    public RespR customerCarRec(List<CustomerCarRec> customerCarRecs) {
        log.info("车辆备案开始NoCarServiceImpl.customerCarRec{}", customerCarRecs);
        if (customerCarRecs == null || customerCarRecs.size() <= 0) {
            return new RespR(false, "无备案车辆");
        }
        StringBuffer res = new StringBuffer();
        CustomerCarRec customerCarRec2 = customerCarRecs.get(0);
        Customer customer = customerMapper.selectByCustomerName(customerCarRec2.getCustomerName());
        if (customer == null || customer.getAccstatus() != 0) {
            res.append("#客户：" + customerCarRec2.getCustomerName() + "不存在或状态异常");
            log.info("车辆备案异常NoCarServiceImpl.customerCarRec{},msg{}", customerCarRecs, res.toString());
            return new RespR(false, res.toString());
        }
        CustomerRec customerRecP = new CustomerRec();
        customerRecP.setCustomerName(customerCarRec2.getCustomerName());
        customerRecP.setCompanyName(customerCarRec2.getCompanyName());
        CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecP);
        if (customerRec == null) {
            res.append("#客户：" + customerCarRec2.getCustomerName() + "企业:" + customerCarRec2.getCompanyName() + "备案信息不存在");
            log.info("车辆备案异常NoCarServiceImpl.customerCarRec{},msg{}", customerCarRecs, res.toString());
            return new RespR(false, res.toString());
        }
        return customerCarRecForNoCar(customerCarRecs, res, customerRec);
    }

    public RespR customerCarRecForNoCar(List<CustomerCarRec> customerCarRecs, StringBuffer res, CustomerRec customerRec) {
        try {

            //上游成功返回结果
            String resprresult = "";
            for (CustomerCarRec customerCarRec : customerCarRecs) {
                if (!customerRec.getBussinessType().equals(customerCarRec.getBusinessType())) {
                    res.append("#客户：" + customerCarRec.getCustomerName() + "企业:" + customerCarRec.getCompanyName() + "车辆:" + customerCarRec.getCarNum() + "业务类型错误");
                    continue;
                }
                //先查询上游是否是已经备案
                VehicleQueryRequest vehicleQueryRequest = new VehicleQueryRequest();
                String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
                vehicleQueryRequest.setCompanyNum(companyNum);
                vehicleQueryRequest.setPlateColor(Integer.parseInt(customerCarRec.getCarColor()));
                vehicleQueryRequest.setPlateNum(customerCarRec.getCarNum());
                vehicleQueryRequest.setWaybillSource(1);


                //如果是接口，直接调用上游车辆备案
                if (0 != customerCarRec.getInterType()) {
                    RespR<VehicleQueryResponse> responseRespR = noCarInterface.vehicleQuery(vehicleQueryRequest);
                    if (responseRespR.getCode() != 1 && responseRespR.getData().getResult() != null && responseRespR.getData().getResult().size() > 0) {
                        customerCarRec.setRecStatus(CommonConstants.REC_STATUS_SUC);
                        customerCarRec.setSuccTime(DateUtil.getCurrentDateStr());
                        //根据车牌号查询是新增还是更新
                        updateCustomerCarRec(customerCarRec);
                        continue;
                    }
                }
                //如果业务类型是无车
                VehicleRegisterRequest vehicleRegisterRequest = new VehicleRegisterRequest();
                if ("0".equals(customerCarRec.getCarColor())) {
                    if (customerCarRec.getServiceOperation() == null) {
                        res.append("#客户：" + customerCarRec.getCustomerName() + "企业:" + customerCarRec.getCompanyName() + "车辆:" + customerCarRec.getCarNum() + "为蓝牌车，请传入入运营类型");
                        continue;
                    }
                    vehicleRegisterRequest.setServiceOperation(customerCarRec.getServiceOperation());
                }
                vehicleRegisterRequest.setCompanyName(customerCarRec.getCompanyName());
                vehicleRegisterRequest.setCompanyNum(companyNum);
                vehicleRegisterRequest.setPlateColor(Integer.parseInt(customerCarRec.getCarColor()));
                vehicleRegisterRequest.setPlateNum(customerCarRec.getCarNum());
                RespR<VehicleRegisterResponse> respR = noCarInterface.vehicleRegister(vehicleRegisterRequest);
                if (respR.getCode() == 1) {
                    res.append(respR.getMsg());
                    customerCarRec.setRecStatus(CommonConstants.REC_STATUS_FAIL);
                    customerCarRec.setFailReason(respR.getMsg());
                    customerCarRec.setFailTime(DateUtil.getCurrentDateStr());
                } else {
                    //车辆备案成功
                    resprresult = respR.getData().toString();
                    customerCarRec.setRecStatus(CommonConstants.REC_STATUS_SUC);
                    customerCarRec.setSuccTime(DateUtil.getCurrentDateStr());
                }
                //根据车牌号查询是新增还是更新
                updateCustomerCarRec(customerCarRec);

            }
            if (StringUtils.isEmpty(res.toString())) {
                log.info("车辆备案成功");
                return new RespR(resprresult);
            } else {
                log.info("车辆备案异常NoCarServiceImpl.customerCarRec{},msg{}", customerCarRecs, res.toString());
                return new RespR(false, res.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }

    }

    @Override
    public RespR customerCarRecQueryUpper(CustomerCarRec customerCarRec) {
        StringBuffer res = new StringBuffer();
        log.info("车辆备案查询NoCarServiceImpl.customerCarRecQueryUpper{}", customerCarRec);
        Customer customer = customerMapper.selectByCustomerName(customerCarRec.getCustomerName());
        if (customer == null || customer.getAccstatus() != 0) {
            res.append("#客户：" + customer.getCustomerName() + "不存在或状态异常");
            return new RespR(false, res.toString());
        }

        VehicleQueryRequest vehicleQueryRequest = new VehicleQueryRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        vehicleQueryRequest.setCompanyNum(companyNum);
        //1 无车承运人
        vehicleQueryRequest.setWaybillSource(1);
        vehicleQueryRequest.setPlateNum(customerCarRec.getCarNum());
        vehicleQueryRequest.setPlateColor(Integer.valueOf(customerCarRec.getCarColor()));

        RespR<VehicleQueryResponse> respR = noCarInterface.vehicleQuery(vehicleQueryRequest);
        if (respR.getCode() == 1) {
            log.info("车辆备案查询失败NoCarServiceImpl.customerCarRecQueryUpper{},msg{}", customerCarRec, respR.getMsg());
        } else if (EIGHT_NUM != customerCarRec.getInterType()) {
            //此处表示仅适用接口查询，不走业务逻辑
            customerCarRec.setRecStatus(1);
            updateCustomerCarRec(customerCarRec);
        }
        return respR;
    }

    public void updateCustomerCarRec(CustomerCarRec customerCarRec) {
        //根据车牌号查询是新增还是更新
        List<CustomerCarRec> customerCarRec1 = customerCarRecMapper.selectByCarNum(customerCarRec.getCarNum());
        if (customerCarRec1 == null || customerCarRec1.size() == 0) {
            customerCarRecMapper.insert(customerCarRec);
        } else {
            customerCarRecMapper.updateByPrimaryKey(customerCarRec);
        }
    }

    @Override
    public RespR customerCarRecQuery(CustomerCarRec customerCarRec) {

        return new RespR(customerCarRecMapper.selectByCustName(customerCarRec.getCustomerName()));
    }

    @Override
    public RespR noCarWaybillStart(NoCarWayBill noCarWayBill) {
        log.info("运单上传开始：NoCarServiceImpl.noCarWaybillStart{}", noCarWayBill);
        NoCarWayBill noCarWayBillDb = null;
        try {
            noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        } catch (Exception e) {
            noCarWaybillMapper.deleteNotRightWayBill(noCarWayBill.getBillNum());
            try {
                noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
            } catch (Exception e1) {
                return new RespR(false, "运单异常，请联系管理员处理");
            }
        }
        if (noCarWayBillDb != null && noCarWayBillDb.getBillwayStatus() > 0) {
            return new RespR(false, "开始指令已经上传成功,请勿重复上传");
        }
        //如果运单时间和当前时间差了三天，直接返回
        if (DateUtil.getDistanceHours(noCarWayBill.getStartTime(), new Date()) < INTONE) {
            noCarWayBill.setFailReason("失败，运单开始时间超72小时");
            noCarWayBill.setBillwayStatus(-2);
            insertOrUpdateBillStart(noCarWayBill);
            return new RespR(false, "失败，运单开始时间超72小时");
        }
        RespR respR = checkCarWayBillAndSetInfo(noCarWayBill);
        if (respR.getCode() == 1) {
            log.info("运单上传失败：NoCarServiceImpl.noCarWaybillStart{}，msg{}", noCarWayBill, respR.getMsg());
            noCarWayBill.setFailReason(respR.getMsg());
            noCarWayBill.setBillwayStatus(-2);
            insertOrUpdateBillStart(noCarWayBill);
            return respR;
        }
        WaybillStartRequest waybillStartRequest = buildWaybillStartRequest(noCarWayBill);
        if(StringUtils.isEmpty(waybillStartRequest.getBase64Str())){
            return new RespR(false,"未上传运单文件");
        }
       if(null != noCarWayBillDb && noCarWayBillDb.getBillwayStatus() == 0){
            RespR<WaybillOriginEndResponse> responseRespR1 = sendOrgWayBillInfo(noCarWayBill);
            if(responseRespR1.getCode() == 1){
                noCarWayBill.setBillwayStatus(0);
                noCarWayBill.setFailReason("ysyd:"+responseRespR1.getMsg());
                insertOrUpdateBillStart(noCarWayBill);
                return new RespR(false, "原始运单上传失败:" + responseRespR1.getMsg());
            }else{
                noCarWayBill.setBillwayStatus(1);
                insertOrUpdateBillStart(noCarWayBill);
            }
            return responseRespR1;
        }
        RespR<WaybillStartResponse> responseRespR = noCarInterface.waybillStart(waybillStartRequest);
        if (responseRespR.getCode() == 1) {
            log.info("运单上传失败：NoCarServiceImpl.noCarWaybillStart{}，msg{}", noCarWayBill, responseRespR.getMsg());
            noCarWayBill.setFailReason(responseRespR.getMsg());
            noCarWayBill.setBillwayStatus(-2);
            insertOrUpdateBillStart(noCarWayBill);
            return new RespR(false, responseRespR.getMsg());
        } else {
            noCarWayBill.setBillwayStatus(0);
            insertOrUpdateBillStart(noCarWayBill);
            RespR<WaybillOriginEndResponse> responseRespR1 = sendOrgWayBillInfo(noCarWayBill);
            if(responseRespR1.getCode() == 1){
                noCarWayBill.setFailReason("ysyd:"+responseRespR1.getMsg());
                insertOrUpdateBillStart(noCarWayBill);
                return new RespR(false, "原始运单上传失败:" + responseRespR1.getMsg());
            }else{
                noCarWayBill.setBillwayStatus(1);
                insertOrUpdateBillStart(noCarWayBill);
            }
        }
        return new RespR(responseRespR.getData());
    }

    /**
     * 插入或者更新运单
     * @param noCarWayBill
     */
    public void insertOrUpdateBillStart(NoCarWayBill noCarWayBill) {
        noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
        noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
        NoCarWayBill curr = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        if (curr == null) {
            noCarWaybillMapper.insert(noCarWayBill);
        } else {
                noCarWaybillMapper.updateByBillNum(noCarWayBill);
        }
    }
    @Autowired
    private com.jkcredit.invoice.service.nocar.WayBillFileService wayBillFileMapper;
    /**
     * 组装指令报文
     */
    public WaybillStartRequest buildWaybillStartRequest(NoCarWayBill noCarWayBill) {
        WaybillStartRequest waybillStartRequest = new WaybillStartRequest();
        //如果调用上游测试环境， 默认自营平台 10000148
        //  String companyNum = "10000148";
       String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillStartRequest.setCompanyNum(companyNum);
        waybillStartRequest.setNum(noCarWayBill.getBillNum());
        waybillStartRequest.setPlateNum(noCarWayBill.getPlateNum());
        waybillStartRequest.setPlateColor(Integer.parseInt(noCarWayBill.getPlateColor()));
        waybillStartRequest.setStartTime(DateUtil.dateFormate(noCarWayBill.getStartTime()));
        waybillStartRequest.setSourceAddr(noCarWayBill.getSourceAddr());
        waybillStartRequest.setDestAddr(noCarWayBill.getDestAddr());
        waybillStartRequest.setPredictEndTime(DateUtil.dateFormate(noCarWayBill.getPredictEndTime()));
        waybillStartRequest.setFee(noCarWayBill.getFee());
        //如果调用上游测试环境， 抬头 默认抬头，不然调用不通
        // waybillStartRequest.setTitleType(1);
        waybillStartRequest.setTitleType(noCarWayBill.getTitleType());
        waybillStartRequest.setTaxplayerCode(noCarWayBill.getTaxplayerCode());
        waybillStartRequest.setName(noCarWayBill.getCompanyName());
        waybillStartRequest.setAddress(noCarWayBill.getCompanyAdress());
        waybillStartRequest.setTel(noCarWayBill.getCompanyTel());
        waybillStartRequest.setBank(noCarWayBill.getCompanyBank());
        waybillStartRequest.setBankAccount(noCarWayBill.getCompanyBankAcc());
        waybillStartRequest.setCompanyName(noCarWayBill.getCompanyName());
        if(noCarWayBill.getBase64Str() == null){
           NoCarWayBillFileInfo noCarWayBillFileInfo =  wayBillFileMapper.selectFileInfo(noCarWayBill.getFileBatchNum(),noCarWayBill.getBillNum());
           if(noCarWayBillFileInfo!=null){
               waybillStartRequest.setWaybillFileName(noCarWayBillFileInfo.getFileName());
               waybillStartRequest.setBase64Str(noCarWayBillFileInfo.getBase64Str());
           }
        }else {
            waybillStartRequest.setWaybillFileName(noCarWayBill.getWaybillFileName());
            waybillStartRequest.setBase64Str(noCarWayBill.getBase64Str());
        }
        waybillStartRequest.setContractType(1);
        return waybillStartRequest;
    }

    public RespR checkCarWayBillAndSetInfo(NoCarWayBill noCarWayBill) {
        try {
            Customer customer = customerMapper.selectByCustomerName(noCarWayBill.getCustomerName());
            if (customer == null || customer.getAccstatus() == 1) {
                return new RespR(false, "客户不存在或者已经停用");
            }
            CustomerRec customerRecParm = new CustomerRec();
            customerRecParm.setCompanyName(noCarWayBill.getCompanyName());
            customerRecParm.setCustomerName(noCarWayBill.getCustomerName());
            CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecParm);
            if (customerRec == null || customerRec.getRecStatus() != 1) {
                //
                return new RespR(true);
            }
            noCarWayBill.setCompanyNum(customerRec.getCompanyNum());
            noCarWayBill.setCompanyAdress(customerRec.getCompanyAdress());
            noCarWayBill.setCompanyTel(customerRec.getCompanyPhone());
            noCarWayBill.setCompanyBank(customerRec.getCompanyOpenbank());
            noCarWayBill.setCompanyBankAcc(customerRec.getCompanyOpenbankAcc());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("运单企业信息设置错误{}", noCarWayBill);
            return new RespR(false, "运单企业信息设置错误" + e.getMessage());
        }

        return new RespR();
    }

    @Override
    public RespR noCarWaybillEnd(NoCarWayBill noCarWayBill) {
        log.info("运单结束开始：NoCarServiceImpl.noCarWaybillEnd{}", noCarWayBill);
        NoCarWayBill noCarWayBillDb = null;
        try {
            noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        } catch (Exception e) {
            noCarWaybillMapper.deleteNotRightWayBill(noCarWayBill.getBillNum());
            try {
                noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
            } catch (Exception e1) {
                return new RespR(false, "运单异常，请联系管理员处理");
            }
        }
        if (noCarWayBillDb == null) {
            try {
                noCarWayBillDb = noCarWayBill.clone();
            } catch (Exception e) {
                e.printStackTrace();
                return new RespR(false, "系统异常，请重试");
            }

        }
        if (noCarWayBillDb.getBillwayStatus() == 0) {
            return new RespR(false, "未上传原始运单，请联系管理员确认");
        }

        if (noCarWayBillDb.getBillwayStatus() > 1) {
            return new RespR(false, "运单已经结束或者是历史已结束运单，请联系管理员确认");
        }
        noCarWayBillDb.setPreEndTime(noCarWayBillDb.getPredictEndTime());
        noCarWayBillDb.setDestAddrPre(noCarWayBillDb.getDestAddr());
        noCarWayBillDb.setDestAddr(noCarWayBill.getDestAddr());
        noCarWayBillDb.setPredictEndTime(noCarWayBill.getPredictEndTime());
        noCarWayBillDb.setBatchNumEnd(noCarWayBill.getBatchNumEnd());
        noCarWayBillDb.setInterType(noCarWayBill.getInterType());

        WaybillEndRequest waybillEndRequest = new WaybillEndRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillEndRequest.setCompanyNum(companyNum);
        waybillEndRequest.setNum(noCarWayBillDb.getBillNum());
        waybillEndRequest.setRealDestAddr(noCarWayBillDb.getDestAddr());
        waybillEndRequest.setEndTime(DateUtil.dateFormate(noCarWayBillDb.getPredictEndTime()));
        RespR<WaybillEndResponse> waybillEndResponseRespR = noCarInterface.waybillEnd(waybillEndRequest);
        if (waybillEndResponseRespR.getCode() == 1) {
            log.info("运单结束失败：NoCarServiceImpl.noCarWaybillEnd{},msg{}", noCarWayBill, waybillEndResponseRespR.getMsg());
            noCarWayBillDb.setBillwayStatus(-3);
            noCarWayBillDb.setFailReason(waybillEndResponseRespR.getMsg());
            insertOrUpdateBillEnd(noCarWayBillDb);
            return new RespR(false, waybillEndResponseRespR.getMsg());
        } else if (FOR.equals(waybillEndResponseRespR.getData().getInfo())) {
            log.info("运单结束失败：NoCarServiceImpl.noCarWaybillEnd{},msg{}", noCarWayBill, "运单已经超时");
            noCarWayBillDb.setBillwayStatus(4);
            noCarWayBillDb.setFailReason(waybillEndResponseRespR.getMsg());
            insertOrUpdateBillEnd(noCarWayBillDb);
            return new RespR(false, "运单已经超时");
        }
        noCarWayBillDb.setInterfaceEndTime(DateUtil.getCurrentDateStr());
        noCarWayBillDb.setBillwayStatus(2);
        noCarWayBillDb.setUpdateTime(DateUtil.getCurrentDateStr());
        insertOrUpdateBillEnd(noCarWayBillDb);
        return new RespR(waybillEndResponseRespR.getData());
    }

    /**
     * 插入或者更新运单
     * @param noCarWayBill
     */
    public void insertOrUpdateBillEnd(NoCarWayBill noCarWayBill) {
        noCarWayBill.setInterfaceEndTime(DateUtil.getCurrentDateStr());
        noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
        NoCarWayBill curr = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        if (curr == null) {
            noCarWaybillMapper.insert(noCarWayBill);
        } else {
            if (curr.getBillwayStatus() > 1) {
                return;
            }
            noCarWaybillMapper.updateByBillNumEnd(noCarWayBill);
        }
    }

    /**
     * 插入或者更新运单
     * @param noCarWayBill
     */
    public void insertOrUpdateBill(NoCarWayBill noCarWayBill) {
        noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
        NoCarWayBill curr = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        if (curr == null) {
            noCarWaybillMapper.insert(noCarWayBill);
        } else {
            if (curr.getBillwayStatus() > TWO_NUM) {
                return;
            }
            noCarWaybillMapper.updateByBillNum(noCarWayBill);
        }
    }

    @Override
    public RespR noCarHisWaybillStart(NoCarWayBill noCarWayBill) {
        log.info("历史运单开始上传：NoCarServiceImpl.noCarHisWaybillStart{},msg{}", noCarWayBill, "开始");
        NoCarWayBill noCarWayBillDb = null;
        try {
            noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        } catch (Exception e) {
            noCarWaybillMapper.deleteNotRightWayBill(noCarWayBill.getBillNum());
            try {
                noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
            } catch (Exception e1) {
                return new RespR(false, "运单异常，请联系管理员处理");
            }
        }
        if (noCarWayBillDb != null && noCarWayBillDb.getBillwayStatus() > 0) {
            return new RespR(false, "开始指令已经上传成功,请勿重复上传");
        }
        if (DateUtil.getDistanceDays(noCarWayBill.getStartTime(), new Date()) > INTTOW) {
            log.info("历史运单开始上传失败：NoCarServiceImpl.noCarHisWaybillStart{},msg{}", noCarWayBill, "必须是二十天前的运单");
            noCarWayBill.setBillwayStatus(-2);
            noCarWayBill.setFailReason("失败，运单未满20天时效");
            insertOrUpdateBillStart(noCarWayBill);
            return new RespR(false, "失败，运单未满20天时效");
        }

        RespR respR = checkCarWayBillAndSetInfo(noCarWayBill);
        if (respR.getCode() == 1) {
            log.info("历史运单开始上传失败：NoCarServiceImpl.noCarHisWaybillStart{},msg{}", noCarWayBill, respR.getMsg());
            noCarWayBill.setBillwayStatus(-2);
            noCarWayBill.setFailReason(respR.getMsg());
            insertOrUpdateBillStart(noCarWayBill);
            return respR;
        }
        String orgBillNum = noCarWayBill.getBillNum();
        if(noCarWayBill.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE){
            //TODO 拆分运单特殊处理
            List<String> startAndEndTimes = DateUtil.getSplitTimeOver96(noCarWayBill.getStartTime(),noCarWayBill.getPredictEndTime());
            int i = 0;
            for(String startAndEndTime :startAndEndTimes ){
                try {
                    String [] startAndEndTimeStr = startAndEndTime.split("#");
                    NoCarWayBill noCarWayBillClone = noCarWayBill.clone();
                    noCarWayBillClone.setStartTime(startAndEndTimeStr[0]);
                    noCarWayBillClone.setPredictEndTime(startAndEndTimeStr[1]);
                    noCarWayBillClone.setBillNum(noCarWayBill.getBillNum()+"-jk0"+i);
                    WaybillHistoryStartRequest waybillHistoryStartRequest = buildNoCarHisWaybill(orgBillNum,noCarWayBillClone);
                    if(StringUtils.isEmpty(waybillHistoryStartRequest.getBase64Str())){
                        return new RespR(false,"运单文件未上传");
                    }
                    RespR<WaybillHistoryStartResponse> responseRespR = noCarInterface.waybillHistoryStart(waybillHistoryStartRequest);
                    if (responseRespR.getCode() == 1) {
                        log.info("历史运单开始上传失败：NoCarServiceImpl.noCarHisWaybillStart{},msg{}", noCarWayBillClone, responseRespR.getMsg());
                        noCarWayBill.setBillwayStatus(-2);
                        noCarWayBill.setFailReason(responseRespR.getMsg());
                        insertOrUpdateBillStart(noCarWayBill);
                        return new RespR(false, responseRespR.getMsg());
                    }
                    RespR<WaybillOriginEndResponse> responseRespR1 = sendOrgWayBillInfo(noCarWayBillClone);
                    if(responseRespR1.getCode() == 1){
                        noCarWayBill.setFailReason("ysyd:"+responseRespR1.getMsg());
                        insertOrUpdateBillStart(noCarWayBill);
                        return new RespR(false, responseRespR1.getMsg());
                    }
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                    noCarWayBill.setBillwayStatus(-2);
                    noCarWayBill.setFailReason(e.getMessage());
                    insertOrUpdateBillStart(noCarWayBill);
                    return new RespR(false,e.getMessage());
                }
                i++;
            }
            noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
            noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
            noCarWayBill.setBillwayStatus(1);
            insertOrUpdateBillStart(noCarWayBill);
            return new RespR(true);
        }else{
            WaybillHistoryStartRequest waybillHistoryStartRequest = buildNoCarHisWaybill(orgBillNum,noCarWayBill);
            if(null != noCarWayBillDb && noCarWayBillDb.getBillwayStatus() == 0){
                RespR<WaybillOriginEndResponse> responseRespR1 = sendOrgWayBillInfo(noCarWayBill);
                if(responseRespR1.getCode() == 1){
                    noCarWayBill.setBillwayStatus(0);
                    noCarWayBill.setFailReason("ysyd:"+responseRespR1.getMsg());
                    insertOrUpdateBillStart(noCarWayBill);
                    return new RespR(false, "原始运单上传失败:" + responseRespR1.getMsg());
                }else{
                    noCarWayBill.setBillwayStatus(1);
                    insertOrUpdateBillStart(noCarWayBill);
                }
                return responseRespR1;
            }
            if(StringUtils.isEmpty(waybillHistoryStartRequest.getBase64Str())){
                return new RespR(false,"运单文件未上传");
            }
            RespR<WaybillHistoryStartResponse> responseRespR = noCarInterface.waybillHistoryStart(waybillHistoryStartRequest);

            if (responseRespR.getCode() == 1) {
                log.info("历史运单开始上传失败：NoCarServiceImpl.noCarHisWaybillStart{},msg{}", noCarWayBill, responseRespR.getMsg());
                noCarWayBill.setBillwayStatus(-2);
                noCarWayBill.setFailReason(responseRespR.getMsg());
                insertOrUpdateBillStart(noCarWayBill);
                return new RespR(false, responseRespR.getMsg());
            } else {
                noCarWayBill.setIntfaceStartTime(DateUtil.getCurrentDateStr());
                noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
                noCarWayBill.setBillwayStatus(0);
                insertOrUpdateBillStart(noCarWayBill);
                RespR<WaybillOriginEndResponse> responseRespR1 = sendOrgWayBillInfo(noCarWayBill);
                if(responseRespR1.getCode() == 1){
                    noCarWayBill.setFailReason("ysyd:"+responseRespR1.getMsg());
                    insertOrUpdateBillStart(noCarWayBill);
                    return new RespR(false, "原始运单上传失败:" + responseRespR1.getMsg());
                } else {
                    noCarWayBill.setBillwayStatus(1);
                    insertOrUpdateBillStart(noCarWayBill);
                }
            }
            return new RespR(responseRespR.getData());
        }
    }

    /**
     * 运单开始指令 上传原始运单功能
     *
     * @param noCarWayBill
     * @return com.jkcredit.invoice.util.RespR<cn.com.taiji.sdk.model.comm.protocol.tts.waybill.WaybillOriginEndResponse>
     * @throws
     * @createDate 2024/4/25 上午9:20
     * @author mashengyi
     */
    public RespR<WaybillOriginEndResponse> sendOrgWayBillInfo(NoCarWayBill noCarWayBill) {
        String param = paramService.getParamsByParamName("SEND_ORG_WAYBILLINFO_ON_OFF").getParamValue();
        if (!StringUtil.equal(ONE, param)) {
            //原始运单 默认不开启，增加开关控制，如果不开启，那就模拟返回成功呗
            RespR<WaybillOriginEndResponse> responseRespR = new RespR<>();
            responseRespR.setCode(0);
            responseRespR.setMsg("success");
            return responseRespR;
        }

        WaybillOriginEndRequest waybillOriginEndRequest = new WaybillOriginEndRequest();
        waybillOriginEndRequest.setNum(noCarWayBill.getBillNum());
        //如果调用上游测试环境， 默认自营平台 10000148
        //waybillOriginEndRequest.setCompanyNum("10000148");
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillOriginEndRequest.setCompanyNum(companyNum);
        waybillOriginEndRequest.setBase64Str(noCarWayBill.getBase64Str());
        waybillOriginEndRequest.setWaybillFileName(noCarWayBill.getWaybillFileName());
        if (noCarWayBill.getBase64Str() == null) {
            NoCarWayBillFileInfo noCarWayBillFileInfo =  wayBillFileMapper.selectFileInfo(noCarWayBill.getFileBatchNum(),noCarWayBill.getBillNum());
            if(noCarWayBillFileInfo!=null){
                waybillOriginEndRequest.setWaybillFileName(noCarWayBillFileInfo.getFileName());
                waybillOriginEndRequest.setBase64Str(noCarWayBillFileInfo.getBase64Str());
            }

        }
        waybillOriginEndRequest.setContractType(2);
        RespR<WaybillOriginEndResponse> responseRespR = noCarInterface.waybillOrgEnd(waybillOriginEndRequest);
        if(responseRespR.getCode() == 1){
            responseRespR = noCarInterface.waybillOrgEnd(waybillOriginEndRequest);
            if(responseRespR.getCode() == 1){
                responseRespR = noCarInterface.waybillOrgEnd(waybillOriginEndRequest);
            }
        }
        return responseRespR;
    }
    public WaybillHistoryStartRequest buildNoCarHisWaybill(String orgBillNum,NoCarWayBill noCarWayBill) {
        WaybillHistoryStartRequest waybillStartRequest = new WaybillHistoryStartRequest();
        //如果调用上游测试环境， 默认自营平台 10000148
        //String companyNum = "10000148";
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillStartRequest.setCompanyNum(companyNum);
        waybillStartRequest.setNum(noCarWayBill.getBillNum());
        waybillStartRequest.setPlateNum(noCarWayBill.getPlateNum());
        waybillStartRequest.setPlateColor(Integer.parseInt(noCarWayBill.getPlateColor()));
        waybillStartRequest.setStartTime(DateUtil.dateFormate(noCarWayBill.getStartTime()));
        waybillStartRequest.setSourceAddr(noCarWayBill.getSourceAddr());
        waybillStartRequest.setDestAddr(noCarWayBill.getDestAddr());
        waybillStartRequest.setPredictEndTime(DateUtil.dateFormate(noCarWayBill.getPredictEndTime()));
        waybillStartRequest.setFee(noCarWayBill.getFee());
        //如果调用上游测试环境， 抬头 默认抬头，不然调用不通
        //waybillStartRequest.setTitleType(1);
        waybillStartRequest.setTitleType(noCarWayBill.getTitleType());
        waybillStartRequest.setTaxplayerCode(noCarWayBill.getTaxplayerCode());
        waybillStartRequest.setName(noCarWayBill.getCompanyName());
        waybillStartRequest.setAddress(noCarWayBill.getCompanyAdress());
        waybillStartRequest.setTel(noCarWayBill.getCompanyTel());
        waybillStartRequest.setBank(noCarWayBill.getCompanyBank());
        waybillStartRequest.setBankAccount(noCarWayBill.getCompanyBankAcc());
        if(noCarWayBill.getBase64Str() == null){
            NoCarWayBillFileInfo noCarWayBillFileInfo =  wayBillFileMapper.selectFileInfo(noCarWayBill.getFileBatchNum(),orgBillNum);
            if(noCarWayBillFileInfo!=null){
                waybillStartRequest.setWaybillFileName(noCarWayBillFileInfo.getFileName());
                waybillStartRequest.setBase64Str(noCarWayBillFileInfo.getBase64Str());
                waybillStartRequest.setContractType(noCarWayBill.getContractType());
            }

        }else {
            waybillStartRequest.setWaybillFileName(noCarWayBill.getWaybillFileName());
            waybillStartRequest.setBase64Str(noCarWayBill.getBase64Str());
            waybillStartRequest.setContractType(noCarWayBill.getContractType());

        }
        return waybillStartRequest;
    }

    @Override
    public RespR noCarHisWaybillEnd(NoCarWayBill noCarWayBill) {
        NoCarWayBill noCarWayBillDb = null;
        try {
            noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
        } catch (Exception e) {
            noCarWaybillMapper.deleteNotRightWayBill(noCarWayBill.getBillNum());
            try {
                noCarWayBillDb = noCarWaybillMapper.selectByBillNum(noCarWayBill.getBillNum());
            } catch (Exception e1) {
                return new RespR(false, "运单异常，请联系管理员处理");
            }
        }
        if (noCarWayBillDb == null) {
            try {
                noCarWayBillDb = noCarWayBill.clone();
            } catch (Exception e) {
                e.printStackTrace();
                return new RespR(false, "系统异常，请重试");
            }

        }
        log.info("历史运单结束上传：NoCarServiceImpl.noCarHisWaybillEnd{},msg{}", noCarWayBill, "开始");

        if (noCarWayBillDb.getBillwayStatus() == 0) {
            return new RespR(false, "原始运单未上传，请联系管理员确认");
        }

        if (noCarWayBillDb.getBillwayStatus() > 1) {
            return new RespR(false, "结束运单已经上传，无需再次上传");
        }
        noCarWayBillDb.setPreEndTime(noCarWayBillDb.getPredictEndTime());
        noCarWayBillDb.setDestAddrPre(noCarWayBillDb.getDestAddr());
        noCarWayBillDb.setDestAddr(noCarWayBill.getDestAddr());
        noCarWayBillDb.setPredictEndTime(noCarWayBill.getPredictEndTime());
        noCarWayBillDb.setInterType(noCarWayBill.getInterType());
        WaybillHistoryEndRequest waybillEndRequest = new WaybillHistoryEndRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillEndRequest.setCompanyNum(companyNum);
        waybillEndRequest.setNum(noCarWayBillDb.getBillNum());
        waybillEndRequest.setRealDestAddr(noCarWayBillDb.getDestAddr());
        waybillEndRequest.setEndTime(DateUtil.dateFormate(noCarWayBillDb.getPredictEndTime()));
        if(noCarWayBillDb.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE){
            List<String> startAndEndTimes = DateUtil.getSplitTimeOver96(noCarWayBillDb.getStartTime(),noCarWayBillDb.getPredictEndTime());
            int i = 0;
            for(String startAndEndTime :startAndEndTimes ){
                String [] startAndEndTimeStr = startAndEndTime.split("#");
                waybillEndRequest.setEndTime(DateUtil.dateFormate(startAndEndTimeStr[1]));
                waybillEndRequest.setNum(noCarWayBillDb.getBillNum()+"-jk0"+i);
                RespR<WaybillHistoryEndResponse> waybillEndResponseRespR = noCarInterface.waybillHistoryEnd(waybillEndRequest);
                if (waybillEndResponseRespR.getCode() == 1) {
                    noCarWayBillDb.setBillwayStatus(-3);
                    noCarWayBillDb.setFailReason(waybillEndResponseRespR.getMsg());
                    insertOrUpdateBillEnd(noCarWayBillDb);
                    log.info("历史运单结束上传失败：NoCarServiceImpl.noCarHisWaybillEnd{},msg{}", noCarWayBillDb, waybillEndResponseRespR.getMsg());

                    return new RespR(false, waybillEndResponseRespR.getMsg());
                }
                i++;
            }
            noCarWayBillDb.setBillwayStatus(2);
            insertOrUpdateBillEnd(noCarWayBillDb);
            return new RespR(true);
        }else{
            RespR<WaybillHistoryEndResponse> waybillEndResponseRespR = noCarInterface.waybillHistoryEnd(waybillEndRequest);
            if (waybillEndResponseRespR.getCode() == 1 && !(waybillEndResponseRespR.getMsg()!=null && waybillEndResponseRespR.getMsg().contains("结束指令已上传"))) {
                noCarWayBillDb.setBillwayStatus(-3);
                noCarWayBillDb.setFailReason(waybillEndResponseRespR.getMsg());
                insertOrUpdateBillEnd(noCarWayBillDb);
                log.info("历史运单结束上传失败：NoCarServiceImpl.noCarHisWaybillEnd{},msg{}", noCarWayBillDb, waybillEndResponseRespR.getMsg());

                return new RespR(false, waybillEndResponseRespR.getMsg());
            } else if (!(waybillEndResponseRespR.getMsg()!=null && waybillEndResponseRespR.getMsg().contains("结束指令已上传")) && FOR.equals(waybillEndResponseRespR.getData().getInfo())) {
                noCarWayBill.setBillwayStatus(4);
                insertOrUpdateBillEnd(noCarWayBillDb);
                log.info("历史运单结束上传失败：NoCarServiceImpl.noCarHisWaybillEnd{},msg{}", noCarWayBillDb, "运单已经超时，请拆分");
                return new RespR(false, "运单已经超时");
            }
            noCarWayBillDb.setBillwayStatus(2);
            insertOrUpdateBillEnd(noCarWayBillDb);
            if(waybillEndResponseRespR.getMsg()!=null && waybillEndResponseRespR.getMsg().contains("结束指令已上传")){
                WaybillHistoryEndResponse waybillEndResponseRespRtmp = new WaybillHistoryEndResponse();
                waybillEndResponseRespRtmp.setInfo("成功");
                waybillEndResponseRespRtmp.setReceiveTime(DateUtil.getCurrentDateStrFormat());
                return new RespR(waybillEndResponseRespRtmp);
            }
            return new RespR(waybillEndResponseRespR.getData());
        }

    }

    public WaybillNumFindInvoiceResponse buildInterFaceVoiceData(NoCarWayBill noCarWayBill, List<BillInvoice> billInvoices) {
        WaybillNumFindInvoiceResponse waybillNumFindInvoiceResponse = new WaybillNumFindInvoiceResponse();
        List<InvoiceProcessingListModel> invoiceProcessingListModels = new ArrayList<>();
        waybillNumFindInvoiceResponse.setResult(invoiceProcessingListModels);
        waybillNumFindInvoiceResponse.setPlateNum(noCarWayBill.getPlateNum());
        waybillNumFindInvoiceResponse.setInfo("成功");
        waybillNumFindInvoiceResponse.setWaybillStartTime(noCarWayBill.getStartTime() == null ? null : DateUtil.dateToTime(noCarWayBill.getStartTime()));
        waybillNumFindInvoiceResponse.setWaybillEndTime(noCarWayBill.getPredictEndTime() == null ? null : DateUtil.dateToTime(noCarWayBill.getPredictEndTime()));
        waybillNumFindInvoiceResponse.setWaybillStatus(noCarWayBill.getBillwayStatus());
        waybillNumFindInvoiceResponse.setReceiveTime(DateUtil.dateToTime(DateUtil.getCurrentDateStr()));
        waybillNumFindInvoiceResponse.setWaybillNum(noCarWayBill.getBillNum());
        if (billInvoices != null && billInvoices.size() > 0) {
            billInvoices.stream().forEach(billInvoice -> {
                InvoiceProcessingListModel invoiceProcessingListModel = new InvoiceProcessingListModel();
                BeanUtils.copyProperties(billInvoice, invoiceProcessingListModel);
                invoiceProcessingListModel.setExTime(invoiceProcessingListModel.getExTime() == null ? null : DateUtil.dateToTime(invoiceProcessingListModel.getExTime()));
                invoiceProcessingListModel.setInvoiceMakeTime(invoiceProcessingListModel.getInvoiceMakeTime() == null ? null : DateUtil.dateToTime(invoiceProcessingListModel.getInvoiceMakeTime()));
                invoiceProcessingListModel.setTradeMatchTime(invoiceProcessingListModel.getTradeMatchTime() == null ? null : DateUtil.dateToTime(invoiceProcessingListModel.getTradeMatchTime()));
                invoiceProcessingListModel.setWaybillStartTime(invoiceProcessingListModel.getWaybillStartTime() == null ? null : DateUtil.dateToTime(invoiceProcessingListModel.getWaybillStartTime()));
                invoiceProcessingListModel.setWaybillEndTime(invoiceProcessingListModel.getWaybillEndTime() == null ? null : DateUtil.dateToTime(invoiceProcessingListModel.getWaybillEndTime()));
                invoiceProcessingListModels.add(invoiceProcessingListModel);
            });
        }
        return waybillNumFindInvoiceResponse;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor=Exception.class)
    public RespR getInvoiceByWayBillNumReal(NoCarWayBill noCarWayBill, boolean isInterface) {
        byte isKf = 1;
        /**
         * 迁移数据
         */
        if (noCarWayBill.getInterType() == THREE_NUM) {
            isKf = 3;
        }
        /**
         * 特殊处理数据
         */
        if (noCarWayBill.getInterType() == FIVE_NUM) {
            isKf = 5;
        }
        log.info("取票啦：NoCarServiceImpl.getInvoiceByWayBillNumReal{},isCurr{}", noCarWayBill, isInterface);
        if (isaBoolean(noCarWayBill, isInterface)) {
            //如果超时运单，直接用数据源的返回
            if (noCarWayBill.getBillwayStatus() == FOR_NUM) {
                //进行取票操作
                WaybillNumFindInvoiceRequest waybillNumFindInvoiceRequest = new WaybillNumFindInvoiceRequest();
                String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
                waybillNumFindInvoiceRequest.setCompanyNum(companyNum);
                waybillNumFindInvoiceRequest.setWaybillNum(noCarWayBill.getBillNum());
                RespR<WaybillNumFindInvoiceResponse> responseRespR = noCarInterface.waybillNumFindInvoice(waybillNumFindInvoiceRequest);
                return new RespR(responseRespR.getData());
            }

            if (isaBoolean(noCarWayBill)) {
                //其余情况直接返回发票信息
                List<BillInvoice> billInvoices = billInvoiceMapper.selectByBillNum(noCarWayBill.getBillNum());
                WaybillNumFindInvoiceResponse waybillNumFindInvoiceResponse = buildInterFaceVoiceData(noCarWayBill, billInvoices);
                return new RespR(waybillNumFindInvoiceResponse);
            } else {
                return new RespR(false, noCarWayBill.getFailReason() == null ? "运单未知异常" : noCarWayBill.getFailReason().equals("网络异常,请联系管理人员") ? "运单编号错误或该运单不存在" : noCarWayBill.getFailReason());
            }
        }
        if (noCarWayBill.getBillwayStatus() != TWO_NUM && noCarWayBill.getBillwayStatus() != NE_FIVE_NUM) {
            return new RespR(false, "不是开票中的状态，别取票啦");
        }
        RespR respR = checkCarWayBillAndSetInfo(noCarWayBill);
        if (respR.getCode() == 1) {
            log.info("取票失败啦：NoCarServiceImpl.getInvoiceByWayBillNumReal{},isCurr{},msg{}", noCarWayBill, isInterface, respR.getMsg());
            return respR;
        }
        RespR<WaybillNumFindInvoiceResponse> responseRespR=null;
        if(noCarWayBill.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE){
            int size = DateUtil.getSplitTimeOver96(noCarWayBill.getStartTime(),noCarWayBill.getPredictEndTime()).size();
            for(int i=0;i<size;i++){
                String newBillNum = noCarWayBill.getBillNum()+"-jk0"+i;
                WaybillNumFindInvoiceRequest waybillNumFindInvoiceRequest = new WaybillNumFindInvoiceRequest();
                String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
                waybillNumFindInvoiceRequest.setCompanyNum(companyNum);
                waybillNumFindInvoiceRequest.setWaybillNum(newBillNum);
                RespR<WaybillNumFindInvoiceResponse> responseRespRrec = noCarInterface.waybillNumFindInvoice(waybillNumFindInvoiceRequest);
                if (responseRespRrec.getCode() == 1) {
                    log.info("取票失败啦：NoCarServiceImpl.getInvoiceByWayBillNumReal{},isCurr{},msg{}", noCarWayBill, isInterface, responseRespR.getMsg());
                    return new RespR(false, responseRespR.getMsg());
                }
                if(responseRespR == null){
                    responseRespR = responseRespRrec;
                    responseRespR.getData().setWaybillNum(noCarWayBill.getBillNum());
                }else{
                    if(responseRespR.getData().getWaybillStatus()>responseRespRrec.getData().getWaybillStatus()){
                        responseRespR.getData().setWaybillStatus(responseRespRrec.getData().getWaybillStatus());
                    }
                    responseRespR.getData().getResult().addAll(responseRespRrec.getData().getResult());
                }
            }

        }else{
            //进行取票操作
            WaybillNumFindInvoiceRequest waybillNumFindInvoiceRequest = new WaybillNumFindInvoiceRequest();
            String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
            waybillNumFindInvoiceRequest.setCompanyNum(companyNum);
            waybillNumFindInvoiceRequest.setWaybillNum(noCarWayBill.getBillNum());
            responseRespR = noCarInterface.waybillNumFindInvoice(waybillNumFindInvoiceRequest);
        }

        if (responseRespR.getCode() == 1) {
            log.info("取票失败啦：NoCarServiceImpl.getInvoiceByWayBillNumReal{},isCurr{},msg{}", noCarWayBill, isInterface, responseRespR.getMsg());
            return new RespR(false, responseRespR.getMsg());
        } else {
            int tempStatus = responseRespR.getData().getWaybillStatus().intValue();
            if (noCarWayBill.getBillwayStatus() == NE_FIVE_NUM) {
                if (isKf != THREE_NUM) {
                    noCarWayBill.setInterType(0);
                } else {
                    if (tempStatus == THREE_NUM) {
                        noCarWayBill.setInterType(4);
                    }
                }
                //更改票状态
                noCarWayBill.setBillwayStatus(tempStatus);
                noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
                insertOrUpdateBill(noCarWayBill);
            } else {
                //更改票状态
                noCarWayBill.setBillwayStatus(tempStatus);
                noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
                noCarWaybillMapper.updateByBillNum(noCarWayBill);
            }

            if (tempStatus == TWO_NUM || tempStatus == THREE_NUM) {
                if (countCalculateInfo(noCarWayBill, isKf, responseRespR)) {
                    return new RespR(responseRespR.getData());
                }

            }
            if (isInterface) {
                return new RespR(responseRespR.getData());
            }
        }
        log.info("99999999{}", noCarWayBill.getBillNum());
        return new RespR("success");
    }

    private boolean isaBoolean(NoCarWayBill noCarWayBill, boolean isInterface) {
        return isInterface &&
                (noCarWayBill.getBillwayStatus() != NE_FIVE_NUM ||
                        noCarWayBill.getInterType() == FOR_NUM);
    }

    private boolean isaBoolean(NoCarWayBill noCarWayBill) {
        return noCarWayBill.getBillwayStatus() == ONE_NUM ||
                noCarWayBill.getBillwayStatus() == TWO_NUM ||
                noCarWayBill.getBillwayStatus() == THREE_NUM ||
                noCarWayBill.getBillwayStatus() == FOR_NUM;
    }

    private boolean countCalculateInfo(NoCarWayBill noCarWayBill, byte isKf, RespR<WaybillNumFindInvoiceResponse> responseRespR) {
        //删除已有发票
        billInvoiceMapper.deleteByBillNum(noCarWayBill.getBillNum());
        /*if(noCarWayBill.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE) {
            int size = DateUtil.getSplitTimeOver96(noCarWayBill.getStartTime(), noCarWayBill.getPredictEndTime()).size();
            for (int i = 0; i < size; i++) {
                String newBillNum = noCarWayBill.getBillNum() + "-jk0" + i;
                billInvoiceMapper.deleteByBillNum(newBillNum);
            }
        }*/
        //发票入库
        List<InvoiceProcessingListModel> invoiceProcessingListModels = responseRespR.getData().getResult();
        //用set来去重计费信息
        Set<NoCarCalculateInfor> carCalculateInfors = new HashSet<>();
        invoiceProcessingListModels.stream().forEach(invoiceProcessingListModel -> {
            log.info("44444{}", invoiceProcessingListModel.getTransactionId());
            BillInvoice billInvoice = buildFromInvoiceProcessingListModel(invoiceProcessingListModel);
            billInvoice.setCompanyName(noCarWayBill.getCompanyName());
            billInvoice.setCompanyNum(noCarWayBill.getCompanyNum());
            billInvoice.setCustomerName(noCarWayBill.getCustomerName());
            billInvoice.setWaybillNumAct(billInvoice.getWaybillNum());
            billInvoice.setWaybillNum(noCarWayBill.getBillNum());
            //扣费明细入账
            NoCarCalculateInfor calculateInfor = new NoCarCalculateInfor();
            if (noCarWayBill.getInterType() != FOR_NUM && noCarWayBill.getInterType() != THREE_NUM) {
                calculateInfor.setCalculateTime(DateUtil.getCurrentDateStr());
            } else {
                calculateInfor.setCalculateTime("2021-01-11 00:00:00");
            }

            calculateInfor.setCompanyNum(noCarWayBill.getCompanyNum());
            calculateInfor.setCtype(1);
            calculateInfor.setCustomId(noCarWayBill.getCustomerName());
            calculateInfor.setBuyerName(invoiceProcessingListModel.getBuyerName());
            calculateInfor.setBuyerTaxpayerCode(invoiceProcessingListModel.getBuyerTaxpayerCode());
            calculateInfor.setInvoiceMakeTime(billInvoice.getInvoiceMakeTime());
            calculateInfor.setTradeId(billInvoice.getTransactionId());
            NoCarCalculateInfor noCarCalculateInfor = calculateInforMapper.selectByTradeId(billInvoice.getTransactionId());
            if (noCarCalculateInfor != null) {
                billInvoice.setCalculateTime(noCarCalculateInfor.getCalculateTime());
            } else {
                carCalculateInfors.add(calculateInfor);
                billInvoice.setCalculateTime(calculateInfor.getCalculateTime());
            }
            billInvoiceMapper.insert(billInvoice);
        });
        log.info("6666666{}", noCarWayBill.getBillNum());
        if (isKf == THREE_NUM) {
            return true;
        }
        //统一插入交易id 和 和计费信息
        Param param = paramService.getParamsByParamName("CUST_NOCAR_FEE");
        Double fee = Double.parseDouble(param.getParamValue());
        Customer customer = customerMapper.selectByCustomerNameForLock(noCarWayBill.getCustomerName());
        log.info("recode customerBlance before:[{}],[{}],[{}]",customer.getCustomerName(),customer.getAccountBalance(),carCalculateInfors.size());
        customer.setInvoiceTime(DateUtil.getCurrentDateStr());
        carCalculateInfors.stream().forEach(calculateInfor -> {
            try {
                calculateInfor.setCompanyLongName(customer.getCompany());
                calculateInfor.setFee(fee);
                calculateInforMapper.insert(calculateInfor);
                customer.setAccountBalance(MathUtil.sub(customer.getAccountBalance(), calculateInfor.getFee()));
            } catch (Exception e) {
                log.error("重复数据来啦" + calculateInfor.getTradeId());
            }


        });
        if (isKf == 1) {
            log.info("recode customerBlance after:[{}],[{}]",customer.getCustomerName(),customer.getAccountBalance());
            customerMapper.updateByPrimaryKeySelective(customer);
        }
        return false;
    }

    public BillInvoice buildFromInvoiceProcessingListModel(InvoiceProcessingListModel invoiceProcessingListModel) {
        BillInvoice billInvoice = new BillInvoice();
        BeanUtils.copyProperties(invoiceProcessingListModel, billInvoice);
        //设置时间
        billInvoice.setExTime(billInvoice.getExTime() == null ? null : DateUtil.tTimeToDate(billInvoice.getExTime()));
        billInvoice.setInvoiceMakeTime(billInvoice.getInvoiceMakeTime() == null ? null : DateUtil.tTimeToDate(billInvoice.getInvoiceMakeTime()));
        billInvoice.setWaybillEndTime(billInvoice.getWaybillEndTime() == null ? null : DateUtil.tTimeToDate(billInvoice.getWaybillEndTime()));
        billInvoice.setTradeMatchTime(billInvoice.getTradeMatchTime() == null ? null : DateUtil.tTimeToDate(billInvoice.getTradeMatchTime()));
        billInvoice.setWaybillStartTime(billInvoice.getWaybillStartTime() == null ? null : DateUtil.tTimeToDate(billInvoice.getWaybillStartTime()));
        return billInvoice;
    }

    @Override
    public RespR hcinvoicequery(HcInvoiceQueryVo hcInvoiceQueryVo) {
        log.info("取红冲票啦：NoCarServiceImpl.hCInvoiceQuery{}", hcInvoiceQueryVo);
        HcInvoice hcInvoiceParam = new HcInvoice();
        hcInvoiceParam.setBuyerName(hcInvoiceQueryVo.getBuyerName());
        hcInvoiceParam.setYearMonth(hcInvoiceQueryVo.getMonth());
        List<HcInvoice> hcInvoices = hcInvoiceMapper.selectInvoiceByCondition(hcInvoiceParam);
        if (hcInvoices == null) {
            hcInvoices = new ArrayList<>();
        }
        Map<String, List<HcInvoice>> map = new HashMap<>(10);
        map.put("result", hcInvoices);
        return new RespR(map);
    }

    @Override
    public RespR hcinvoicequeryinter(HcInvoiceQueryVo hcInvoiceQueryVo) {
        Page page = new Page();
        page.setCurrent(hcInvoiceQueryVo.getPageNo());
        if (StringUtils.isEmpty(hcInvoiceQueryVo.getPageSize())) {
            page.setSize(1000);
        } else {
            page.setSize(hcInvoiceQueryVo.getPageSize());
        }
        HcInvoice hcInvoiceParam = new HcInvoice();
        hcInvoiceParam.setBuyerTaxpayerCode(hcInvoiceQueryVo.getBuyerTaxpayerCode());
        hcInvoiceParam.setYearMonth(hcInvoiceQueryVo.getMonth());
        IPage<HcInvoice> byPageAndWayBill = hcInvoiceService.findByPageAndWayBill(page, hcInvoiceParam);
        Map<String, Object> map = new HashMap<>(10);
        map.put("result", byPageAndWayBill.getRecords());
        map.put("total", byPageAndWayBill.getTotal());
        map.put("pages", byPageAndWayBill.getPages());
        return new RespR(map);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RespR hcinvoiceupdate(HcInvoiceQueryVo hcInvoiceQueryVo) {
        log.info("取红冲票啦：NoCarServiceImpl.hCInvoiceQuery{}", hcInvoiceQueryVo);
        WaybillInvoiceRedQueryRequest redQueryRequest = new WaybillInvoiceRedQueryRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        redQueryRequest.setCompanyNum(companyNum);
        redQueryRequest.setMonth(hcInvoiceQueryVo.getMonth());

        RespR<WaybillInvoiceRedQueryResponse> respR = noCarInterface.waybillInvoiceRedQuery(redQueryRequest);

        if (respR.getCode() == 1) {
            log.info("取红冲票失败啦：NoCarServiceImpl.hCInvoiceQuery{},msg{}", hcInvoiceQueryVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {
            List<WaybillInvoiceRedQueryModel> waybillInvoiceRedQueryModels = respR.getData().getResult();
            if (waybillInvoiceRedQueryModels != null && waybillInvoiceRedQueryModels.size() > 0) {
                //1.删除原有红冲发票
                hcInvoiceMapper.deleteByMounth(hcInvoiceQueryVo.getMonth());
                //逐条插入红冲发票
                for (WaybillInvoiceRedQueryModel waybillInvoiceRedQueryModel : waybillInvoiceRedQueryModels) {
                    HcInvoice hcInvoice = new HcInvoice();
                    BeanUtils.copyProperties(waybillInvoiceRedQueryModel, hcInvoice);
                    hcInvoice.setYearMonth(hcInvoiceQueryVo.getMonth());
                    hcInvoice.setTaxRate(String.valueOf(waybillInvoiceRedQueryModel.getTaxRate()));
                    hcInvoice.setTotalTaxAmount(String.valueOf(waybillInvoiceRedQueryModel.getTotalTaxAmount()));
                    hcInvoice.setInvoiceMakeTime(DateUtil.tLocalDateTimeToString(waybillInvoiceRedQueryModel.getInvoiceMakeTime()));
                    hcInvoiceMapper.insertHcInvoice(hcInvoice);
                }
            }
        }
        return new RespR();
    }

    @Override
    public RespR monthAccQuery(MonthAccountQueryVo monthAccountQueryVo) {
        log.info("取月票啦：NoCarServiceImpl.monthAccQuery{},msg{}", monthAccountQueryVo, "开始");
        CustomerRec customerRecParm = new CustomerRec();
        customerRecParm.setCompanyName(monthAccountQueryVo.getCompanyName());
        customerRecParm.setCustomerName(monthAccountQueryVo.getCustomeName());
        CustomerRec customerRec = null;
        List<CustomerRec> customerRecs = customerRecMapper.selectByCompanyName(monthAccountQueryVo.getCompanyName());
        if (customerRecs != null && customerRecs.size() > 0) {
            customerRec = customerRecs.get(0);
        }
        if (customerRec == null || customerRec.getRecStatus() != 1) {
            log.info("取月票失败啦：NoCarServiceImpl.monthAccQuery{},msg{}", monthAccountQueryVo, "企业未备案成功,查询失败");
            return new RespR(false, "企业未备案成功,查询失败");
        }
        WaybillCountQueryRequest waybillCountQueryRequest = new WaybillCountQueryRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillCountQueryRequest.setCompanyNum(companyNum);
        waybillCountQueryRequest.setTaxCode(customerRec.getCompanyReferencenum());
        waybillCountQueryRequest.setTradeMonth(monthAccountQueryVo.getTradeMonth());
        waybillCountQueryRequest.setWaybillSource(monthAccountQueryVo.getWaybillSource());
        waybillCountQueryRequest.setPageNo(monthAccountQueryVo.getPageNo());
        waybillCountQueryRequest.setPageSize(1000);
        RespR<WaybillCountQueryResponse> waybillCountQueryResponseRespR = noCarInterface.waybillCountQuery(waybillCountQueryRequest);
        log.info("取月票结束：NoCarServiceImpl.monthAccQuery{},msg{}", waybillCountQueryResponseRespR, waybillCountQueryResponseRespR.getMsg());
        return waybillCountQueryResponseRespR;
    }

    @Override
    public RespR monthAccQueryUpdate(MonthAccountQueryVo monthAccountQueryVo) {
        log.info("更新取月票啦：NoCarServiceImpl.monthAccQueryUpdate{},msg{}", monthAccountQueryVo, "开始");
        CustomerRec customerRecParm = new CustomerRec();
        customerRecParm.setCompanyName(monthAccountQueryVo.getCompanyName());
        customerRecParm.setCustomerName(monthAccountQueryVo.getCustomeName());
        CustomerRec customerRec = null;
        List<CustomerRec> customerRecs = customerRecMapper.selectByCompanyName(monthAccountQueryVo.getCompanyName());
        if (customerRecs != null && customerRecs.size() > 0) {
            for (CustomerRec customerRec1 : customerRecs) {
                if ("2".equals(customerRec1.getBussinessType())) {
                    customerRec = customerRec1;
                    break;
                }
            }
        }

        if (customerRec == null || customerRec.getRecStatus() != 1) {
            log.info("取月票失败啦：NoCarServiceImpl.hCInvoiceQuery{},msg{}", monthAccountQueryVo, "企业未备案成功,查询失败");
            return new RespR(false, "企业未备案成功,查询失败");
        }
        String [] dates = DateUtil.getMouthDays(monthAccountQueryVo.getTradeMonth());
        WaybillCountPageRequest waybillCountQueryRequest = new WaybillCountPageRequest();
        String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
        waybillCountQueryRequest.setCompanyNum(companyNum);
        waybillCountQueryRequest.setTaxCode(customerRec.getCompanyReferencenum());
        waybillCountQueryRequest.setWaybillSource(monthAccountQueryVo.getWaybillSource());
        waybillCountQueryRequest.setPageSize(1000);
        for(int i=0;i<dates.length;i++){
            waybillCountQueryRequest.setPageNo(1);
            waybillCountQueryRequest.setTradeDate(dates[i]);
            updateOneDayAcc(waybillCountQueryRequest,customerRec,monthAccountQueryVo);
        }
        return new RespR(true);
    }
    public void updateOneDayAcc(WaybillCountPageRequest waybillCountQueryRequest,CustomerRec customerRec,MonthAccountQueryVo monthAccountQueryVo){
        RespR<WaybillCountQueryResponse> waybillCountQueryResponseRespR = noCarInterface.waybillCountQuery(waybillCountQueryRequest);
        if (waybillCountQueryResponseRespR.getCode() != 1) {
            dealMouthAcc(waybillCountQueryResponseRespR, customerRec);
            log.info(waybillCountQueryResponseRespR.getData().getTotalCount() + "---hehhe----" + monthAccountQueryVo.getCompanyName());
            if (waybillCountQueryResponseRespR.getData().getTotalCount() > A_THOUSAND) {
                long pages = waybillCountQueryResponseRespR.getData().getTotalCount() % 1000 == 0 ? waybillCountQueryResponseRespR.getData().getTotalCount() / 1000 - 1 : waybillCountQueryResponseRespR.getData().getTotalCount() / 1000;
                for (int i = TWO_NUM; i < pages + TWO_NUM; i++) {
                    waybillCountQueryRequest.setPageNo(i);
                    RespR<WaybillCountQueryResponse> waybillCountQueryResponseRespR1 = noCarInterface.waybillCountQuery(waybillCountQueryRequest);
                    dealMouthAcc(waybillCountQueryResponseRespR1, customerRec);
                }
            }
        }

        log.info("更新取月票啦：NoCarServiceImpl.monthAccQueryUpdate{},msg{}", waybillCountQueryResponseRespR, waybillCountQueryResponseRespR.getMsg());
    }
    public void dealMouthAcc(RespR<WaybillCountQueryResponse> waybillCountQueryResponseRespR, CustomerRec customerRec) {
        String customerName = customerRec.getCustomerName();
        String companyName = customerRec.getCompanyBelongName();
        String buyerName = customerRec.getCompanyName();
        String buyerCode = customerRec.getCompanyReferencenum();
        waybillCountQueryResponseRespR.getData().getResult().forEach(waybillCountQueryModel -> {
            MounthAcc mounthAcc = new MounthAcc();
            mounthAcc.setBuyerName(buyerName);
            mounthAcc.setBuyerTaxpayerCode(buyerCode);
            mounthAcc.setCompanyName(companyName);
            mounthAcc.setCustomerId(customerName);
            mounthAcc.setExTime(DateUtil.tTimeToDate(waybillCountQueryModel.getExTime()));
            mounthAcc.setEnStation(waybillCountQueryModel.getEnStation());
            mounthAcc.setExStation(waybillCountQueryModel.getExStation());
            mounthAcc.setFee(waybillCountQueryModel.getFee());
            mounthAcc.setTradeId(waybillCountQueryModel.getTradeId());
            mounthAcc.setWaybillNum(waybillCountQueryModel.getWaybillNum());
            mounthAccMapper.insert(mounthAcc);
        });
    }


    /**
     * 获取发票和运单状态 true 实时 false 走本地 自用，不对外
     *
     * @param noCarWayBill
     * @param isInterface
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor=Exception.class)
    public RespR getInvoiceByWayBillOwnerNumReal(NoCarWayBill noCarWayBill, boolean isInterface) {
        log.info("取票啦：NoCarServiceImpl.getInvoiceByWayBillNumReal{},isCurr{}", noCarWayBill, isInterface);
        if(noCarWayBill.getBillwayStatus() == 3){
            if(noCarWayBill.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE){
                int size = DateUtil.getSplitTimeOver96(noCarWayBill.getStartTime(),noCarWayBill.getPredictEndTime()).size();
                for(int i=0;i<size;i++){
                    String newBillNum = noCarWayBill.getBillNum()+"-jk0"+i;
                    billInvoiceMapper.deleteByBillNum(newBillNum);
                }
            }
             return new RespR("success");
        }
        RespR<WaybillNumFindInvoiceResponse> responseRespR=null;
        if(noCarWayBill.getSplitFlag() == NoCarWayBill.SPLIT_FALG_TRUE){
            int size = DateUtil.getSplitTimeOver96(noCarWayBill.getStartTime(),noCarWayBill.getPredictEndTime()).size();
            for(int i=0;i<size;i++){
                String newBillNum = noCarWayBill.getBillNum()+"-jk0"+i;
                billInvoiceMapper.deleteByBillNum(newBillNum);
                WaybillNumFindInvoiceRequest waybillNumFindInvoiceRequest = new WaybillNumFindInvoiceRequest();
                String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
                waybillNumFindInvoiceRequest.setCompanyNum(companyNum);
                waybillNumFindInvoiceRequest.setWaybillNum(newBillNum);
                RespR<WaybillNumFindInvoiceResponse> responseRespRrec = noCarInterface.waybillNumFindInvoice(waybillNumFindInvoiceRequest);
                if (responseRespRrec.getCode() == 1) {
                    log.info("取票失败啦：AAAAAA:{}",noCarWayBill.getBillNum());
                }else{
                    if(responseRespR == null){
                        responseRespR = responseRespRrec;
                        responseRespR.getData().setWaybillNum(noCarWayBill.getBillNum());
                    }else{
                        if(responseRespR.getData().getWaybillStatus()>responseRespRrec.getData().getWaybillStatus()){
                            responseRespR.getData().setWaybillStatus(responseRespRrec.getData().getWaybillStatus());
                        }
                        responseRespR.getData().getResult().addAll(responseRespRrec.getData().getResult());
                    }
                }

            }
           if(responseRespR == null){
                 return new RespR(false,"失败"+noCarWayBill.getBillNum());
           }
        }else{
            //进行取票操作
            WaybillNumFindInvoiceRequest waybillNumFindInvoiceRequest = new WaybillNumFindInvoiceRequest();
            String companyNum = paramService.getParamsByParamName("REQUEST_COMPANY_NUM").getParamValue();
            waybillNumFindInvoiceRequest.setCompanyNum(companyNum);
            waybillNumFindInvoiceRequest.setWaybillNum(noCarWayBill.getBillNum());
            responseRespR = noCarInterface.waybillNumFindInvoice(waybillNumFindInvoiceRequest);
        }

        if (responseRespR.getCode() == 1) {
            log.info("取票失败啦：AAAAAA:{}",noCarWayBill.getBillNum());
            return new RespR(false, responseRespR.getMsg());
        } else {
            int tempStatus = responseRespR.getData().getWaybillStatus().intValue();
            //更改票状态
            noCarWayBill.setBillwayStatus(tempStatus);
            noCarWayBill.setUpdateTime(DateUtil.getCurrentDateStr());
            noCarWaybillMapper.updateByBillNum(noCarWayBill);
        }
        byte isKf = 1;
        if (countCalculateInfo(noCarWayBill, isKf, responseRespR)) {
            return new RespR(responseRespR.getData());
        }
        log.info("99999999{}", noCarWayBill.getBillNum());
        return new RespR("success");
    }
    @Autowired
    WayBillFileService wayBillFileService;
    @Override
    public RespR migrateData(MigrateVo migrateVo) {
        //按时间每次查询一千条数据 2024-03
        String startTime = migrateVo.getStartMounth()+"-01 00:00:00";
        String endTime = migrateVo.getEndmounth()+"-01 00:00:00";
        NoCarWayBill noCarWayBill = new NoCarWayBill();
        noCarWayBill.setStartBegin(startTime);
        noCarWayBill.setStartEnd(endTime);
         int i  = 0;
        while(i>-1){
            List<NoCarWayBill> noCarWayBills = noCarWaybillMapper.selectMigrateDatas(noCarWayBill);
            if(noCarWayBills.size() == 0){
                i=-2;
            }
            i++;
            noCarWayBills.forEach(noCarWayBill1 -> {
                wayBillFileService.migrateData1(noCarWayBill1);
            });
            log.info("第{}次删除时间{}，{}",i,startTime,endTime);
        }

        //对这一千条数据进行先入运单表，再入发票表，再删除运单和发票
        return new RespR("success");
    }

    @Override
    public void updateByBillNumEnd(NoCarWayBill noCarWayBill) {
        noCarWaybillMapper.updateByBillNumEnd(noCarWayBill);
    }


}
