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

import cn.com.taiji.sdk.model.comm.protocol.tts.card.server.*;
import cn.com.taiji.sdk.model.comm.protocol.tts.invoice.server.*;
import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.*;
import com.jkcredit.invoice.common.CommonConstants;
import com.jkcredit.invoice.mapper.binvoce.SelfCarApplMapper;
import com.jkcredit.invoice.mapper.binvoce.SelfCarInvoiceMapper;
import com.jkcredit.invoice.mapper.calculateinfor.SelfCarCalculateInforMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
import com.jkcredit.invoice.mapper.customer.CustomerChangeInfoMapper;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.mapper.waybill.SellCarTradeMapper;
import com.jkcredit.invoice.model.entity.calculate.SelfCarCalculateInfor;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.customer.CustomerEtcChangeInfo;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.entity.invoice.SelfCarAppl;
import com.jkcredit.invoice.model.entity.invoice.SelfCarInvoice;
import com.jkcredit.invoice.model.entity.waybill.SelfCarTrade;
import com.jkcredit.invoice.model.vo.CardChangeQueryVo;
import com.jkcredit.invoice.model.vo.CardChangeVo;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerservice.SelfCarCustService;
import com.jkcredit.invoice.service.lowerservice.vo.*;
import com.jkcredit.invoice.service.upservice.SelfCarInterface;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 自有车调下游服务实现类
 * @author mumuxigua
 */
@Service
@Slf4j
public class SelfCarCustServiceImpl implements SelfCarCustService {
    @Autowired
    SelfCarInterface selfCarInterface;
    @Autowired
    CustomerCarRecMapper customerCarRecMapper;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    CustomerRecMapper customerRecMapper;
    @Autowired
    SellCarTradeMapper sellCarTradeMapper;
    @Autowired
    SelfCarApplMapper selfCarApplMapper;
    @Autowired
    SelfCarInvoiceMapper selfCarInvoiceMapper;
    @Autowired
    SelfCarCalculateInforMapper calculateInforMapper;
    @Autowired
    CustomerService customerService;
    @Autowired
    CustomerChangeInfoMapper customerChangeInfoMapper;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor=Exception.class)
    public RespR<List<CardTradeModel>> getTradeList(TradeRequestVo tradeRequestVo) {
        log.info("获取交易开始SelfCarServiceLImpl.getTradeList{}", tradeRequestVo);
        Customer customer = customerMapper.selectByCustomerName(tradeRequestVo.getCustomerName());
        if (customer == null || customer.getAccstatus().intValue() == 1) {
            log.info("获取交易失败SelfCarServiceLImpl.getTradeList{},msg{}", tradeRequestVo, "客户已经停用");
            return new RespR(false, "客户已经停用");
        }
        if (StringUtils.isEmpty(tradeRequestVo.getStartTime()) || StringUtils.isEmpty(tradeRequestVo.getEndTime())) {
            log.info("获取交易失败SelfCarServiceLImpl.getTradeList{},msg{}", tradeRequestVo, "时间为空");
            return new RespR(false, "时间为空");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(tradeRequestVo.getCustomerName());
        customerRec.setCompanyName(tradeRequestVo.getCompanyName());
        customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        if (customerRec == null || customerRec.getRecStatus().intValue() != 1) {
            log.info("获取交易失败SelfCarServiceLImpl.getTradeList{},msg{}", tradeRequestVo, "客户未备案");
            return new RespR(false, "客户未备案");
        }
        CardTradeRequest cardTradeRequest = new CardTradeRequest();
        cardTradeRequest.setCardId(tradeRequestVo.getEtcId());
        cardTradeRequest.setCompanyNum(customerRec.getCompanyNum());
        cardTradeRequest.setStartExTime(DateUtil.dateFormate(tradeRequestVo.getStartTime()));
        cardTradeRequest.setEndExTime(DateUtil.dateFormate(tradeRequestVo.getEndTime()));
        cardTradeRequest.setTradeStatus(tradeRequestVo.getTradeStatus());
        RespR<CardTradeResponse> resp = selfCarInterface.cardTrade(cardTradeRequest);
        if (resp.getCode() == 1) {
            log.info("获取交易失败SelfCarServiceLImpl.getTradeList{},msg{}", tradeRequestVo, resp.getMsg());
            try{
                if(tradeRequestVo.getTradeStatus() == 1 && resp.getMsg().contains("该卡号不在该企业下绑定")){
                    int i = sellCarTradeMapper.deletebyEtcAndTime(tradeRequestVo);
                    log.info("本次删除条数{},etcId{},reultNum",i,tradeRequestVo.getEtcId(),0);
                }else if(tradeRequestVo.getTradeStatus() == 2 && resp.getMsg().contains("该卡号不在该企业下绑定")){
                    sellCarTradeMapper.updatebindStatus(2,tradeRequestVo.getEtcId(),customerRec.getCompanyNum());
                    log.info("{}更新成功bindstatus",tradeRequestVo.getEtcId());
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("{}更新失败原因：{}",tradeRequestVo.getEtcId(),e.getMessage());
            }

            return new RespR(false, resp.getMsg());
        } else {
            CardTradeResponse cardTradeResponse = resp.getData();
            List<CardTradeModel> result = cardTradeResponse.getResult();
            //对不存在的tradeId入表
            if (result != null && result.size() > 0) {
                try {
                    customerCarRecMapper.selectByEtcForLock(tradeRequestVo.getEtcId());
                    SelfCarTrade selfCarTrade;
                    for (CardTradeModel cardTradeModel : result) {
                        List<SelfCarTrade> selfCarTrades = sellCarTradeMapper.selectByTradeId(cardTradeModel.getTradeId());
                        if (selfCarTrades == null || selfCarTrades.size() <= 0) {
                            selfCarTrade = new SelfCarTrade();
                            selfCarTrade.setInterType(tradeRequestVo.getInterType());
                            selfCarTrade.setCustomId(customerRec.getCustomerName());
                            selfCarTrade.setCompanyName(customerRec.getCompanyName());
                            selfCarTrade.setCompanyReferencenum(customerRec.getCompanyReferencenum());
                            selfCarTrade.setCompanyNum(customerRec.getCompanyNum());
                            selfCarTrade.setCardId(cardTradeModel.getCardId());
                            selfCarTrade.setTradeId(cardTradeModel.getTradeId());
                            selfCarTrade.setExTime(DateUtil.tTimeToDate(cardTradeModel.getExTime()));
                            selfCarTrade.setFee(cardTradeModel.getFee());
                            selfCarTrade.setStatus(tradeRequestVo.getTradeStatus());
                            sellCarTradeMapper.insert(selfCarTrade);
                        } else {
                            selfCarTrade = selfCarTrades.get(0);
                            if (!selfCarTrade.getStatus().equals(tradeRequestVo.getTradeStatus())) {
                                selfCarTrade.setStatus(tradeRequestVo.getTradeStatus());
                                selfCarTrade.setInterType(tradeRequestVo.getInterType());
                                sellCarTradeMapper.updateByTradeId(selfCarTrade);
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error(e.getMessage());
                }

            } else {
                return new RespR(false, "未查得");
            }


            return new RespR(result);

        }
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor=Exception.class)
    public RespR<String> applInvoice(InvoiceApplVo invoiceApplVo) {
        log.info("申请开票开始SelfCarServiceLImpl.applInvoice{}", invoiceApplVo);
        if (!customerService.checkMoneyEnough(invoiceApplVo.getCustomerName())) {
            log.info("申请开票失败SelfCarServiceLImpl.applInvoice{},msg{}", invoiceApplVo, "余额不足");
            return new RespR(false, "余额不足");
        }
        Customer customer = customerMapper.selectByCustomerName(invoiceApplVo.getCustomerName());
        if (customer == null || customer.getAccstatus().intValue() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.applInvoice{},msg{}", invoiceApplVo, "客户已经停用");
            return new RespR(false, "客户已经停用");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(invoiceApplVo.getCustomerName());
        customerRec.setCompanyName(invoiceApplVo.getCompanyName());
        customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        if (customerRec == null || customerRec.getRecStatus().intValue() != 1) {
            log.info("申请开票失败SelfCarServiceLImpl.applInvoice{},msg{}", invoiceApplVo, "客户未备案");
            return new RespR(false, "客户未备案");
        }

        B2BInvoiceApplyRequest b2bInvoiceApplyRequest = new B2BInvoiceApplyRequest();
        b2bInvoiceApplyRequest.setCardId(invoiceApplVo.getCardId());
        b2bInvoiceApplyRequest.setCompanyNum(customerRec.getCompanyNum());
        List<B2BInvoiceApplyModel> applyModels = new ArrayList<>();
        List<String> tradeIds = invoiceApplVo.getTradeIds();
        if (tradeIds == null || tradeIds.size() <= 0) {
            return new RespR(false, "没有交易Id");
        }
        for (String tradeId : tradeIds) {
            B2BInvoiceApplyModel applyModel = new B2BInvoiceApplyModel();
            applyModel.setTradeId(tradeId);
            applyModels.add(applyModel);
        }
        b2bInvoiceApplyRequest.setTradeIdModel(applyModels);
        RespR<B2BInvoiceApplyResponse> respR = selfCarInterface.b2Binvoiceapply(b2bInvoiceApplyRequest);
        if (respR.getCode() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.applInvoice{},msg{}", invoiceApplVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {
            return getStringRespR(invoiceApplVo, customer, customerRec, b2bInvoiceApplyRequest, tradeIds, respR);
        }

    }

    private RespR<String> getStringRespR(InvoiceApplVo invoiceApplVo, Customer customer, CustomerRec customerRec, B2BInvoiceApplyRequest b2bInvoiceApplyRequest, List<String> tradeIds, RespR<B2BInvoiceApplyResponse> respR) {
        B2BInvoiceApplyResponse data = respR.getData();
        SelfCarAppl selfCarAppl = new SelfCarAppl();
        selfCarAppl.setApplId(data.getApplyId());
        selfCarAppl.setApplTime(data.getReceiveTime());
        selfCarAppl.setCompanyNum(b2bInvoiceApplyRequest.getCompanyNum());
        selfCarAppl.setCustomId(customer.getCustomerName());
        selfCarAppl.setCardId(invoiceApplVo.getCardId());
        selfCarAppl.setInvoiceAmount(data.getInvoiceAmount());
        selfCarAppl.setInvoiceCount(data.getInvoiceCount());
        selfCarAppl.setInvoiceTaxAmount(data.getInvoiceTaxAmount());
        selfCarAppl.setInterType(invoiceApplVo.getInterType());
        selfCarApplMapper.insert(selfCarAppl);
        double needFee = 0;
        //更新交易id申请开票时间，并将转态改为开票中
        for (String tradeId : tradeIds) {
            List<SelfCarTrade> selfCarTrades = sellCarTradeMapper.selectByTradeId(tradeId);
            if (selfCarTrades == null || selfCarTrades.size() == 0) {
                continue;
            }
            SelfCarTrade selfCarTrade = selfCarTrades.get(0);
            selfCarTrade.setStatus(2);
            selfCarTrade.setAclTime(DateUtil.getCurrentDateStr());
            selfCarTrade.setApplId(data.getApplyId());
            selfCarTrade.setInterType(invoiceApplVo.getInterType());
            sellCarTradeMapper.updateByTradeId(selfCarTrade);
            //计费
            SelfCarCalculateInfor carCalculateInfor = new SelfCarCalculateInfor();
            carCalculateInfor.setCustomId(customerRec.getCustomerName());
            carCalculateInfor.setCompanyNum(customerRec.getCompanyNum());
            //公司名称
            carCalculateInfor.setCompanyName(customerRec.getCompanyName());
            //主体名称
            carCalculateInfor.setCompanyLongName(customerRec.getCompanyBelongName());
            carCalculateInfor.setCalTime(StringUtils.substring(selfCarTrade.getExTime(), 0, 7));
            carCalculateInfor.setFee(customer.getFee());
            carCalculateInfor.setCompanyReferencenum(customerRec.getCompanyReferencenum());
            carCalculateInfor.setEtcNum(selfCarTrade.getCardId());
            if (calculateInforMapper.selectByEtcAndTime(carCalculateInfor) == null) {
                needFee = MathUtil.add(needFee, carCalculateInfor.getFee());
                carCalculateInfor.setActCalTime(DateUtil.getCurrentDateStr());
                calculateInforMapper.insert(carCalculateInfor);
            }
        }
        customer = customerMapper.selectByCustomerNameForLock(invoiceApplVo.getCustomerName());
        //客户统一扣费
        customer.setInvoiceTime(DateUtil.getCurrentDateStr());
        customer.setAccountBalance(MathUtil.sub(customer.getAccountBalance(), needFee));
        customerMapper.updateByPrimaryKeySelective(customer);
        return new RespR(respR.getData());
    }

    @Override
    public RespR<List<B2BInvoiceQueryByApplyModel>> getSelfCarInvoicesByApplyIds(ApplQueryInvVo applQueryInvVo) {
        log.info("申请开票开始SelfCarServiceLImpl.getSelfCarInvoicesByApplyIds{}", applQueryInvVo);
        B2BInvoiceQueryByApplyRequest applyRequest = new B2BInvoiceQueryByApplyRequest();
        applyRequest.setCardId(applQueryInvVo.getEtcNum());
        applyRequest.setCompanyNum(applQueryInvVo.getCompanyNum());
        applyRequest.setApplyId(applQueryInvVo.getApplId());
        RespR<B2BInvoiceQueryByApplyResponse> responseRespR = selfCarInterface.b2bContractQuery(applyRequest);
        //返回相应的发票
        if (responseRespR.getCode() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.getSelfCarInvoicesByApplyIds{},msg{}", applQueryInvVo, responseRespR.getMsg());
            return new RespR(false, responseRespR.getMsg());
        } else {
            return new RespR(responseRespR.getData().getResult(), responseRespR.getData().getResult().toString());
        }

    }

    @Override
    public void getSelfCarInvoicesByApplyIdsDb(ApplQueryInvVo applQueryInvVo) {
        log.info("申请开票开始SelfCarServiceLImpl.getSelfCarInvoicesByApplyIdsDb{}", applQueryInvVo);
        B2BInvoiceQueryByApplyRequest applyRequest = new B2BInvoiceQueryByApplyRequest();
        applyRequest.setCardId(applQueryInvVo.getEtcNum());
        applyRequest.setCompanyNum(applQueryInvVo.getCompanyNum());
        applyRequest.setApplyId(applQueryInvVo.getApplId());
        RespR<B2BInvoiceQueryByApplyResponse> responseRespR = selfCarInterface.b2bContractQuery(applyRequest);
        //返回相应的发票
        if (responseRespR.getCode() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.getSelfCarInvoicesByApplyIdsDb{},msg{}", applQueryInvVo, responseRespR.getMsg());
        } else {
            B2BInvoiceQueryByApplyResponse respData = responseRespR.getData();
            List<B2BInvoiceQueryByApplyModel> dataResult = respData.getResult();
            if (dataResult != null && dataResult.size() > 0) {
                for (B2BInvoiceQueryByApplyModel listModel : dataResult) {
                    SelfCarInvoice selfCarInvoice = new SelfCarInvoice();
                    BeanUtils.copyProperties(listModel, selfCarInvoice);
                    if(StringUtil.isEmpty(selfCarInvoice.getInvoiceMakeTime())){
                        log.info("跳过发票{},跳过原因:{}",listModel.getTradeId(),listModel.getMsg());
                        continue;
                    }
                    selfCarInvoice.setInvoiceMakeTime(DateUtil.tTimeToDate(selfCarInvoice.getInvoiceMakeTime()));
                    selfCarInvoice.setExTime(DateUtil.tTimeToDate(selfCarInvoice.getExTime()));
                    selfCarInvoice.setCustomerName(applQueryInvVo.getCustomerName());
                    selfCarInvoice.setCompanyName(applQueryInvVo.getCompanyName());
                    selfCarInvoice.setBuyerTaxpayerCode(applQueryInvVo.getCompanyReferencenum());
                    selfCarInvoice.setBuyerName(applQueryInvVo.getCompanyName());
                    selfCarInvoice.setCompanyNum(applQueryInvVo.getCompanyNum());
                    selfCarInvoice.setEnStation(listModel.getEnStationName());
                    selfCarInvoice.setExStation(listModel.getExStationName());
                    List<SelfCarInvoice> selfCarInvoice1 = selfCarInvoiceMapper.selectByCodeAndNum(selfCarInvoice);
                    if (selfCarInvoice1 == null || selfCarInvoice1.size() <= 0) {
                        selfCarInvoiceMapper.insert(selfCarInvoice);
                    }
                }
            }
        }
    }

    @Override
    public RespR<List<B2BInvoiceListModel>> getSelfCarInvoicesByTime(SelfCarDueQueryVo selfCarDueQueryVo, CustomerRec customerRec) {
        log.info("申请开票开始SelfCarServiceLImpl.getSelfCarInvoicesByTime{}", selfCarDueQueryVo);
        B2BInvoiceQueryRequest request = new B2BInvoiceQueryRequest();
        request.setCompanyNum(customerRec.getCompanyNum());
        request.setCardId(selfCarDueQueryVo.getCardId());
        request.setStartInvoiceMakeTime(DateUtil.dateFormate(selfCarDueQueryVo.getStartTime()));
        request.setEndInvoiceMakeTime(DateUtil.dateFormate(selfCarDueQueryVo.getEndTime()));

        RespR<B2BInvoiceQueryResponse> responseRespR = selfCarInterface.b2Binvoicequery(request);
        if (responseRespR.getCode() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.getSelfCarInvoicesByTime{},msg{}", selfCarDueQueryVo, responseRespR.getMsg());
            return new RespR(false, responseRespR.getMsg());
        } else {
            B2BInvoiceQueryResponse respData = responseRespR.getData();
            List<B2BInvoiceListModel> dataResult = respData.getResult();
            if (dataResult != null && dataResult.size() > 0) {
                for (B2BInvoiceListModel listModel : dataResult) {
                    SelfCarInvoice selfCarInvoice = new SelfCarInvoice();
                    BeanUtils.copyProperties(listModel, selfCarInvoice);
                    selfCarInvoice.setInvoiceMakeTime(DateUtil.tTimeToDate(selfCarInvoice.getInvoiceMakeTime()));
                    selfCarInvoice.setExTime(DateUtil.tTimeToDate(selfCarInvoice.getExTime()));
                    selfCarInvoice.setCustomerName(selfCarDueQueryVo.getCustomername());
                    selfCarInvoice.setCompanyName(customerRec.getCompanyName());
                    selfCarInvoice.setBuyerTaxpayerCode(customerRec.getCompanyReferencenum());
                    selfCarInvoice.setBuyerName(customerRec.getCompanyName());
                    selfCarInvoice.setCompanyNum(customerRec.getCompanyNum());
                    selfCarInvoice.setEnStation(listModel.getEnStationName());
                    selfCarInvoice.setExStation(listModel.getExStationName());
                    List<SelfCarInvoice> selfCarInvoice1 = selfCarInvoiceMapper.selectByCodeAndNum(selfCarInvoice);
                    if (selfCarInvoice1 == null || selfCarInvoice1.size() <= 0) {
                        selfCarInvoiceMapper.insert(selfCarInvoice);
                    }
                }
            } else {
                return new RespR(false, "未查得");
            }
            return new RespR(dataResult, responseRespR.getData().getResult().toString());
        }
    }

    @Override
    public RespR<List<B2bInvoicePackageModel>> getInvoicePackge(InvoicePackageVo invoicePackageVo) {
        log.info("申请开票开始SelfCarServiceLImpl.getInvoicePackge{}", invoicePackageVo);
        Customer customer = customerMapper.selectByCustomerName(invoicePackageVo.getCustomerName());
        if (customer == null || customer.getAccstatus().intValue() == 1) {
            return new RespR(false, "客户已经停用");
        }
        if (!customerService.checkMoneyEnough(invoicePackageVo.getCustomerName())) {
            return new RespR(false, "余额不足");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(invoicePackageVo.getCustomerName());
        customerRec.setCompanyName(invoicePackageVo.getCompanyName());
        customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        if (customerRec == null || customerRec.getRecStatus().intValue() != 1) {
            return new RespR(false, "客户未备案");
        }

        B2bInvoicePackageRequest b2bInvoicePackageRequest = new B2bInvoicePackageRequest();
        b2bInvoicePackageRequest.setCompanyNum(customerRec.getCompanyNum());
        b2bInvoicePackageRequest.setMakeMonth(invoicePackageVo.getMonth());
        RespR<B2bInvoicePackageResponse> b2bInvoicePackageResponseRespR = selfCarInterface.b2bInvoicePackage(b2bInvoicePackageRequest);
        if (b2bInvoicePackageResponseRespR.getCode() == 1) {
            log.info("申请开票失败SelfCarServiceLImpl.getInvoicePackge{}，msg{}", invoicePackageVo, b2bInvoicePackageResponseRespR.getMsg());
            return new RespR(false, b2bInvoicePackageResponseRespR.getMsg());
        } else {

            if (b2bInvoicePackageResponseRespR.getData().getResult() == null || b2bInvoicePackageResponseRespR.getData().getResult().size() <= 0) {
                return new RespR(false, "未查得");
            }
            return new RespR(b2bInvoicePackageResponseRespR.getData().getResult());
        }
    }

    @Override
    public RespR getEtcInfo(EtcQueryVo etcQueryVo) {
        log.info("获取etc信息：SelfCarServiceLImpl.getEtcInfo{}", etcQueryVo);
        Customer customer = customerMapper.selectByCustomerName(etcQueryVo.getCustomerName());
        if (customer == null || customer.getAccstatus().intValue() == 1) {
            return new RespR(false, "客户已经停用");
        }
        CustomerRec customerRec = new CustomerRec();
        customerRec.setCustomerName(etcQueryVo.getCustomerName());
        customerRec.setCompanyName(etcQueryVo.getCompanyName());
        customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        if (customerRec == null || customerRec.getRecStatus().intValue() != 1) {
            return new RespR(false, "客户未备案");
        }
        CardBindQueryListToBRequest list = new CardBindQueryListToBRequest();
        //企业编号，必输
        list.setCompanyNum(customerRec.getCompanyNum());
        //卡户 ,非必输
        list.setCardId(etcQueryVo.getCardId());
        //车牌号,非必输
        list.setPlateNum(etcQueryVo.getPlateNum());
        //车牌颜色.非必输
        list.setPalteColor(etcQueryVo.getPlateColor());
        RespR<CardBindQueryListToBResponse> respR = selfCarInterface.cardBindQueryListToB(list);
        if (respR.getCode() == 1) {
            log.info("获取etc信息失败：SelfCarServiceLImpl.getEtcInfo{},msg{}", etcQueryVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        }
        return new RespR(respR.getData().getResult());
    }

    @Override
    public RespR queryEtcInfo(EtcBindVo etcBindVo) {
        log.info("获取etc信息：SelfCarServiceLImpl.queryEtcInfo{}", etcBindVo);
        StringBuffer res = new StringBuffer();
        if (etcBindVo == null || etcBindVo.getCards() == null || etcBindVo.getCards().size() <= 0) {
            return new RespR(false, "无备案Etc");
        }
        Customer customer = customerMapper.selectByCustomerName(etcBindVo.getCustomerName());
        if (customer == null || customer.getAccstatus() != 0) {
            res.append("#客户：" + etcBindVo.getCustomerName() + "不存在或状态异常");
            return new RespR(false, res.toString());
        }
        CustomerRec customerRecP = new CustomerRec();
        customerRecP.setCustomerName(etcBindVo.getCustomerName());
        customerRecP.setCompanyName(etcBindVo.getCompanyName());
        CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecP);
        if (customerRec == null || customerRec.getRecStatus() != 1) {
            res.append("#客户：" + etcBindVo.getCustomerName() + "企业:" + etcBindVo.getCompanyName() + "请先备案");
            return new RespR(false, res.toString());
        }
        CardQueryCardToBRequest request = new CardQueryCardToBRequest();
        request.setCompanyNum(customerRec.getCompanyNum());
        List<CardQueryCardToBModel> models = new ArrayList<>();
        etcBindVo.getCards().forEach(carVo -> {
            CardQueryCardToBModel cardModel = new CardQueryCardToBModel();
            cardModel.setPlateNum(carVo.getNum());
            cardModel.setPlateColor(carVo.getColor());
            models.add(cardModel);
        });
        request.setVehicleList(models);
        RespR<CardQueryCardToBResponse> respR = selfCarInterface.cardQueryCardToB(request);
        if (respR.getCode() == 1) {
            log.info("获取etc信息失败：SelfCarServiceLImpl.queryEtcInfo{},msg{}", etcBindVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        }
        if (respR.getData().getResult() == null || respR.getData().getResult().size() <= 0) {
            log.info("获取etc信息失败：SelfCarServiceLImpl.queryEtcInfo{},msg{}", etcBindVo, "没有etc卡");
            return new RespR(false, "未查得");
        }
        return new RespR(respR.getData().getResult());

    }

    @Override
    public RespR customerEtcRec(EtcBindVo etcBindVo) {
        log.info("etc注册：SelfCarServiceLImpl.customerEtcRec{}", etcBindVo);
        if (etcBindVo == null || etcBindVo.getCards() == null || etcBindVo.getCards().size() <= 0) {
            return new RespR(false, "无备案Etc");
        }
        StringBuffer res = new StringBuffer();
        Customer customer = customerMapper.selectByCustomerName(etcBindVo.getCustomerName());
        if (customer == null || customer.getAccstatus() != 0) {
            res.append("#客户：" + etcBindVo.getCustomerName() + "不存在或状态异常");
            return new RespR(false, res.toString());
        }
        CustomerRec customerRecP = new CustomerRec();
        customerRecP.setCustomerName(etcBindVo.getCustomerName());
        customerRecP.setCompanyName(etcBindVo.getCompanyName());
        CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecP);
        if (customerRec == null || customerRec.getRecStatus() != 1) {
            res.append("#客户：" + etcBindVo.getCustomerName() + "企业:" + etcBindVo.getCompanyName() + "请先备案");
            return new RespR(false, res.toString());
        }
        return recEtc(etcBindVo, customerRec);
    }

    public RespR recEtc(EtcBindVo etcBindVo, CustomerRec customerRec) {
        CardQueryCardToBRequest request = new CardQueryCardToBRequest();
        request.setCompanyNum(customerRec.getCompanyNum());
        List<CardBindingToBModel> models = new ArrayList<>();
        etcBindVo.getCards().forEach(carVo -> {
            CardBindingToBModel model = new CardBindingToBModel();
            model.setCardId(carVo.getEtcNum());
            models.add(model);
        });
        CardBindingToBRequest binding = new CardBindingToBRequest();
        binding.setMobile(etcBindVo.getMobile());
        binding.setCompanyNum(customerRec.getCompanyNum());
        binding.setCardIdList(models);
        RespR<CardBindingToBResponse> respR1 = selfCarInterface.cardBindingToB(binding);
        if (respR1.getCode() == 1) {
            log.info("etc注册失败：SelfCarServiceLImpl.customerEtcRec{},msg{}", etcBindVo, respR1.getMsg());
            return new RespR(false, respR1.getMsg());
        } else {
            return new RespR(respR1.getData());
        }
    }

    public void updateetcrec(CustomerCarRec customerCarRec) {
        //根据车牌号查询是新增还是更新
        log.info("检验成功入库参数{}", customerCarRec);
        CustomerCarRec customerCarRec1 = customerCarRecMapper.selectByEtc(customerCarRec.getEtcNum());
        if (customerCarRec1 == null) {
            log.info("检验成功入库新增参数{}", customerCarRec);
            customerCarRecMapper.insert(customerCarRec);
        } else {
            log.info("检验成功入库更新参数{}", customerCarRec);
            customerCarRecMapper.updateEtcByPrimaryKey(customerCarRec);
        }
    }

    @Override
    public RespR customerEtcRecValid(EtcValidVo etcValidVo) {
        log.info("etc注册校验：SelfCarServiceLImpl.customerEtcRecValid{}", etcValidVo);
        StringBuffer res = new StringBuffer();
        Customer customer = customerMapper.selectByCustomerName(etcValidVo.getCustomerName());
        if (customer == null || customer.getAccstatus() != 0) {
            res.append("#客户：" + etcValidVo.getCustomerName() + "不存在或状态异常");
            return new RespR(false, res.toString());
        }
        CustomerRec customerRecP = new CustomerRec();
        customerRecP.setCustomerName(etcValidVo.getCustomerName());
        customerRecP.setCompanyName(etcValidVo.getCompanyName());
        CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecP);
        if (customerRec == null || customerRec.getRecStatus() != 1) {
            res.append("#客户：" + etcValidVo.getCustomerName() + "企业:" + etcValidVo.getCompanyName() + "请先备案");
            return new RespR(false, res.toString());
        }
        CardValidCodeToBRequest request = new CardValidCodeToBRequest();
        request.setCompanyNum(customerRec.getCompanyNum());
        request.setMobile(etcValidVo.getMobile());
        request.setValidCode(etcValidVo.getValidCode());
        RespR<CardValidCodeToBResponse> respR = selfCarInterface.cardValidCodeToB(request);
        if (respR.getCode() == 1) {
            log.info("etc注册校验失败：SelfCarServiceLImpl.customerEtcRecValid{},msg", etcValidVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {
            /**
             * 绑定的etc卡入库
             */
            respR.getData().getResult().forEach(model -> {
                CustomerCarRec customerCarRec = new CustomerCarRec();
                customerCarRec.setBusinessType(CommonConstants.BUSSINESS_TYPE_SELFCAR);
                customerCarRec.setCompanyName(customerRec.getCompanyName());
                customerCarRec.setCustomerName(customerRec.getCustomerName());
                customerCarRec.setCompanyNum(customerRec.getCompanyNum());
                customerCarRec.setCarNum(model.getPlateNum());
                customerCarRec.setEtcNum(model.getCardId());
                customerCarRec.setCarColor(model.getPlateColor() + "");
                customerCarRec.setRecStatus(CommonConstants.REC_STATUS_SUC);
                customerCarRec.setSuccTime(DateUtil.getCurrentDateStr());
                customerCarRec.setCustPhone(etcValidVo.getMobile());
                customerCarRec.setInterType(etcValidVo.getInterType());
                updateetcrec(customerCarRec);
            });
            return new RespR(respR.getData().getResult().toString());
        }
    }

    @Override
    public RespR customerCarUnRec(List<CustomerCarRec> customerCarRecs) {
        log.info("etc解绑：SelfCarServiceLImpl.customerCarUnRec{}", customerCarRecs);
        if (customerCarRecs == null || customerCarRecs.size() <= 0) {
            return new RespR(false, "无解绑信息");
        }

        StringBuffer res = new StringBuffer();
        String resRespon = "";
        try {
            for (CustomerCarRec customerCarRec : customerCarRecs) {
                CustomerRec customerRecP = new CustomerRec();
                customerRecP.setCustomerName(customerCarRec.getCustomerName());
                customerRecP.setCompanyName(customerCarRec.getCompanyName());
                CustomerRec customerRec = customerRecMapper.selectByCustomerNameAndCompany(customerRecP);
                if ("0".equals(customerRec.getBussinessType())) {
                    customerCarRec.setRecStatus(2);
                    customerCarRecMapper.updateEtcByPrimaryKeySelective(customerCarRec);
                }
            }
            if (org.springframework.util.StringUtils.isEmpty(res.toString())) {
                return new RespR(resRespon);
            } else {
                return new RespR(false, res.toString());
            }

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

    }

    @Override
    public RespR customerCardChange(CardChangeVo cardChangeVo) {
        CardChangeTitleRequest cardChangeTitleRequest = new CardChangeTitleRequest();
        List<String> cards = cardChangeVo.getCardIdList();
        List<CardBindingToBModel> models = new ArrayList<>();
        for (String card : cards) {
            CardBindingToBModel model = new CardBindingToBModel();
            model.setCardId(card);
            models.add(model);
        }
        cardChangeTitleRequest.setCardIdList(models);
        cardChangeTitleRequest.setCompanyNum(cardChangeVo.getCompanyNum());
        cardChangeTitleRequest.setTargetCompanyNum(cardChangeVo.getTargetCompanyNum());

        RespR<CardChangeTitleResponse> respR = selfCarInterface.changeCardTile(cardChangeTitleRequest);
        if (respR.getCode() == 1) {
            log.info("etc换绑失败：SelfCarServiceLImpl.customerCardChange{},msg", cardChangeVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {

            try {
                String applyId = respR.getData().getApplyId();
                //1.删除etc绑卡信息
                cards.stream().forEach(card -> {
                    customerCarRecMapper.deleteByEtcCard(card);
                    customerChangeInfoMapper.insertChangeCard(applyId, card);
                });
                //2.换绑信息入库
                CustomerEtcChangeInfo custometEtcChangeInfo = new CustomerEtcChangeInfo();
                custometEtcChangeInfo.copyFromChangeDto(cardChangeVo);
                custometEtcChangeInfo.setApplyId(applyId);
                customerChangeInfoMapper.insertCardChangeInfo(custometEtcChangeInfo);
            } catch (Exception e) {
                log.info("customerCardChange:{0}", e.getMessage());
            }
            return new RespR(respR.getData());
        }
    }

    @Override
    public RespR customerCardChangeQuery(CardChangeQueryVo cardChangeQueryVo) {
        CardChangeQueryRequest cardChangeQueryRequest = new CardChangeQueryRequest();
        cardChangeQueryRequest.setApplyId(cardChangeQueryVo.getApplyId());
        cardChangeQueryRequest.setCardId(cardChangeQueryVo.getCardId());
        cardChangeQueryRequest.setCompanyNum(cardChangeQueryVo.getCompanyNum());
        RespR<CardChangeQueryResponse> respR = selfCarInterface.queryChangeCard(cardChangeQueryRequest);
        if (respR.getCode() == 1) {
            log.info("etc换绑失败：SelfCarServiceLImpl.customerCardChange{},msg", cardChangeQueryVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {
            return new RespR(respR.getData());
        }
    }

    @Override
    public RespR getApplyQueryByTradeId(TradeApplyQueryInvVo tradeApplyQueryInvVo) {

        TradeApplyQueryRequest tradeApplyQueryRequest = new TradeApplyQueryRequest();
        tradeApplyQueryRequest.setCompanyNum(tradeApplyQueryInvVo.getCompanyNum());
        tradeApplyQueryRequest.setCardId(tradeApplyQueryInvVo.getCardId());
        tradeApplyQueryRequest.setTradeId(tradeApplyQueryInvVo.getTradeId());
        RespR<TradeApplyQueryResponse> respR = selfCarInterface.queryApplyQueryByTradeId(tradeApplyQueryRequest);

        if (respR.getCode() == 1) {
            log.info("自有车 按交易查申请接口查询失败：SelfCarServiceLImpl.getApplyQueryByTradeId{},msg", tradeApplyQueryInvVo, respR.getMsg());
            return new RespR(false, respR.getMsg());
        } else {
            return new RespR(respR.getData());
        }

    }


    @Override
    public RespR getApplyQueryByTradeIds(List<TradeApplyQueryInvVo> tradeApplyQueryInvVos) {

        TradeApplyQueryInvVo data = new TradeApplyQueryInvVo();
        List<TradeApplyQueryResponse> result = new ArrayList<>();


        for (TradeApplyQueryInvVo tradeApplyQueryInvVo : tradeApplyQueryInvVos) {
            TradeApplyQueryRequest tradeApplyQueryRequest = new TradeApplyQueryRequest();
            tradeApplyQueryRequest.setCompanyNum(tradeApplyQueryInvVo.getCompanyNum());
            tradeApplyQueryRequest.setCardId(tradeApplyQueryInvVo.getCardId());
            tradeApplyQueryRequest.setTradeId(tradeApplyQueryInvVo.getTradeId());
            RespR<TradeApplyQueryResponse> respR = selfCarInterface.queryApplyQueryByTradeId(tradeApplyQueryRequest);
            if (respR.getCode() == 1) {
                log.info("自有车 按交易查申请接口查询失败：SelfCarServiceLImpl.getApplyQueryByTradeId{},msg", tradeApplyQueryInvVo, respR.getMsg());
                return new RespR(false, respR.getMsg());
            } else {
                TradeApplyQueryResponse tradeApplyQueryResponse = new TradeApplyQueryResponse();
                tradeApplyQueryResponse.setCardId(respR.getData().getCardId());
                tradeApplyQueryResponse.setApplyId(respR.getData().getApplyId());
                tradeApplyQueryResponse.setTradeCount(respR.getData().getTradeCount());
                tradeApplyQueryResponse.setInvoiceCount(respR.getData().getInvoiceCount());
                tradeApplyQueryResponse.setInvoiceAmount(respR.getData().getInvoiceAmount());
                tradeApplyQueryResponse.setTaxAmount(respR.getData().getTaxAmount());
                tradeApplyQueryResponse.setInvoicedCount(respR.getData().getInvoicedCount());
                tradeApplyQueryResponse.setInvoicedAmount(respR.getData().getInvoicedAmount());
                tradeApplyQueryResponse.setApplyStatus(respR.getData().getApplyStatus());
                result.add(tradeApplyQueryResponse);

            }
        }
        data.setResult(result);
        return new RespR(data);
    }
}
