package com.jkcredit.invoice.controller.business;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.com.taiji.sdk.model.comm.protocol.tts.invoice.server.B2BInvoiceListModel;
import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.CardTradeModel;
import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.TradeApplyQueryResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.annotation.LoginRequired;
import com.jkcredit.invoice.annotation.annotationdes.AuthenticationInterceptor;
import com.jkcredit.invoice.mapper.binvoce.SelfCarApplMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
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.CustomerCarRec;
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.user.User;
import com.jkcredit.invoice.model.entity.waybill.SelfCarTrade;
import com.jkcredit.invoice.model.vo.CardAndTradeVo;
import com.jkcredit.invoice.service.calculateinfor.SelfCarCalculateInfoService;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerservice.CheckHasAuthRole;
import com.jkcredit.invoice.service.lowerservice.SelfCarCustService;
import com.jkcredit.invoice.service.lowerservice.vo.*;
import com.jkcredit.invoice.service.selfcar.SelfCarApplyService;
import com.jkcredit.invoice.service.selfcar.SelfCarBussService;
import com.jkcredit.invoice.service.selfcar.SelfCarInvoiceService;
import com.jkcredit.invoice.service.selfcar.SelfCarTradeService;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import com.jkcredit.invoice.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jkcredit.invoice.common.CommonConst.NULL;

@Api(tags = "自有车操作")
@RestController
@RequestMapping(value = {"/selfCar"})
@Slf4j
/**
 * @Description 自有车操作
 * @Author mashengyi
 * @Date 2022/2/8 18:18
 * @Param
 * @Return
 * @Exception
 *
 */
public class SelfCarController {
    @Autowired
    SelfCarCustService selfCarCustService;
    @Autowired
    SelfCarBussService selfCarBussService;
    @Autowired
    SelfCarCustService selfCarCustServicel;
    @Autowired
    SelfCarTradeService selfCarTradeService;
    @Autowired
    SelfCarInvoiceService selfCarInvoiceService;
    @Autowired
    SelfCarCalculateInfoService selfCarCalculateInfoService;
    @Autowired
    SellCarTradeMapper sellCarTradeMapper;
    @Autowired
    CustomerService customerService;
    @Autowired
    SelfCarApplyService selfCarApplyService;
    @Autowired
    CustomerRecMapper customerRecMapper;
    @Autowired
    CustomerCarRecMapper customerCarRecMapper;
    @Autowired
    private CheckHasAuthRole checkHasAuthRole;

    /**
     * 解绑etc卡
     *
     * @param etcNum 参数集
     * @return 用户集合
     */
    @PostMapping("/selfCarUnBind")
    @ApiOperation(value = "解绑etc卡", notes = "解绑etc卡")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_ADMIN)
    public RespR selfCarUnBind(@NotNull(message = "etc卡号不能为空") @Length(max = 20, message = "etc卡号长度不符") String etcNum) {
        try {
            RespR respR = selfCarBussService.selfCarUnBind(etcNum);
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车交易信息
     *
     * @param page 参数集
     * @return 交易信息
     */
    @PostMapping("/findTrades")
    @ApiOperation(value = "分页查询自有车交易信息", notes = "分页查询自有车交易信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findTrades(Page page, SelfCarTrade selfCarTrade, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, selfCarTrade.getCustomId());
            setTimeDue(selfCarTrade);
            RespR respR = new RespR(selfCarTradeService.findByPageAndTrade(page, selfCarTrade));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车交易信息
     *
     * @param page 参数集
     * @return 交易信息
     */
    @PostMapping("/findTradesUpper")
    @ApiOperation(value = "分页查询自有车交易信息", notes = "分页查询自有车交易信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findTradesUpper(Page page, SelfCarTrade selfCarTrade, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, selfCarTrade.getCustomId());
            setTimeDue(selfCarTrade);
            if (StringUtils.isEmpty(selfCarTrade.getCompanyName())) {
                return new RespR(false, "需要输入公司名称");
            }
            if (StringUtils.isEmpty(selfCarTrade.getExTimeBegin())) {
                return new RespR(false, "请输入交易开始时间");
            }
            if (StringUtils.isEmpty(selfCarTrade.getExTimeEnd())) {
                return new RespR(false, "请输入交易结束时间");
            }
            //先更新查询信息
            TradeRequestVo tradeRequestVo = new TradeRequestVo();
            tradeRequestVo.setCustomerName(selfCarTrade.getCustomId());
            tradeRequestVo.setCompanyName(selfCarTrade.getCompanyName());
            tradeRequestVo.setStartTime(selfCarTrade.getExTimeBegin());
            tradeRequestVo.setEndTime(selfCarTrade.getExTimeEnd());
            tradeRequestVo.setTradeStatus(selfCarTrade.getStatus());
            //0 接口
            tradeRequestVo.setInterType(1);
            if (StringUtils.isEmpty(selfCarTrade.getCardId())) {
                List<CustomerCarRec> customerCarRecs = selfCarBussService.getEtcsByCompany(selfCarTrade.getCompanyName());
                if (customerCarRecs != null && customerCarRecs.size() > 0) {
                    for (CustomerCarRec customerCarRec : customerCarRecs) {
                        tradeRequestVo.setEtcId(customerCarRec.getEtcNum());
                        if (tradeRequestVo.getTradeStatus() == null) {
                            tradeRequestVo.setTradeStatus(1);
                            selfCarCustService.getTradeList(tradeRequestVo);
                            tradeRequestVo.setTradeStatus(2);
                            selfCarCustService.getTradeList(tradeRequestVo);
                            tradeRequestVo.setTradeStatus(3);
                            selfCarCustService.getTradeList(tradeRequestVo);
                        } else {
                            selfCarCustService.getTradeList(tradeRequestVo);
                        }
                    }
                }
            } else {
                tradeRequestVo.setEtcId(selfCarTrade.getCardId());
                if (tradeRequestVo.getTradeStatus() == null) {
                    tradeRequestVo.setTradeStatus(1);
                    selfCarCustService.getTradeList(tradeRequestVo);
                    tradeRequestVo.setTradeStatus(2);
                    selfCarCustService.getTradeList(tradeRequestVo);
                    tradeRequestVo.setTradeStatus(3);
                    selfCarCustService.getTradeList(tradeRequestVo);
                } else {
                    selfCarCustService.getTradeList(tradeRequestVo);
                }
            }
            RespR respR = new RespR(selfCarTradeService.findByPageAndTrade(page, selfCarTrade));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车交易信息
     *
     * @param selfCarTradesStr
     * @return 交易信息
     */
    @PostMapping("/updateTrades")
    @ApiOperation(value = "更新交易id状态", notes = "更新交易id状态")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR updateTrades(@NotNull(message = "更新交易id状态，不能为空") String selfCarTradesStr, @NotNull(message = "更新交易id状态，不能为空") String companyName, User user) {
        try {
            checkHasAuthRole.checkCompanyRole(user, companyName);
            List<SelfCarTrade> selfCarTrades = JSON.parseArray(selfCarTradesStr, SelfCarTrade.class);
            if (selfCarTrades == null || selfCarTrades.size() == 0) {
                selfCarTrades = sellCarTradeMapper.selectByStatus("2", companyName);

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

    public void setTimeDue(SelfCarTrade selfCarTrade) {
        if (!StringUtils.isEmpty(selfCarTrade.getCardId()) && !StringUtils.isEmpty(selfCarTrade.getTradeId())) {
            String[] cardIdArr = selfCarTrade.getCardId().split(",");
            String[] tradeIdArr = null;
            if (selfCarTrade.getTradeId() != null) {
                tradeIdArr = selfCarTrade.getTradeId().split(",");
            }
            List<CardAndTradeVo> cardAndTradeVos = new ArrayList<>();
            for (int i = 0; i < cardIdArr.length; i++) {
                CardAndTradeVo cardAndTradeVo = new CardAndTradeVo();
                cardAndTradeVo.setCardId(cardIdArr[i]);
                if (tradeIdArr != null && tradeIdArr.length >= i + 1) {
                    cardAndTradeVo.setTradeId(tradeIdArr[i]);
                } else {
                    cardAndTradeVo.setTradeId("");
                }
                cardAndTradeVos.add(cardAndTradeVo);
            }
            selfCarTrade.setCardAndTradeVos(cardAndTradeVos);
        } else if (!StringUtils.isEmpty(selfCarTrade.getCardId())) {
            selfCarTrade.setCardIds(Arrays.asList(selfCarTrade.getCardId().split(",")));
        } else if (!StringUtils.isEmpty(selfCarTrade.getTradeId())) {
            selfCarTrade.setTradeIds(Arrays.asList(selfCarTrade.getTradeId().split(",")));
        }
        if (!StringUtils.isEmpty(selfCarTrade.getAclTimeBegin()) && !NULL.equals(selfCarTrade.getAclTimeBegin())) {
            String[] res = selfCarTrade.getAclTimeBegin().split(",");
            selfCarTrade.setAclTimeBegin(res[0]);
            selfCarTrade.setAclTimeEnd(res[1].replace("00:00:00", "23:59:59"));
        } else {
            selfCarTrade.setAclTimeBegin(null);
        }
        if (!StringUtils.isEmpty(selfCarTrade.getExTimeBegin()) && !NULL.equals(selfCarTrade.getExTimeBegin())) {
            String[] res = selfCarTrade.getExTimeBegin().split(",");
            selfCarTrade.setExTimeBegin(res[0]);
            selfCarTrade.setExTimeEnd(res[1].replace("00:00:00", "23:59:59"));
        } else {
            selfCarTrade.setExTimeBegin(null);
        }
    }

    /**
     * 分页查询所有发票信息
     *
     * @param page 参数集
     * @return 交易信息
     */
    @PostMapping("/findSelfCarInvoices")
    @ApiOperation(value = "分页查询自有车发票信息", notes = "分页查询自有车发票信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findSelfCarInvoices(Page page, SelfCarInvoice selfCarInvoice, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, selfCarInvoice.getCustomerName());
            if (!StringUtils.isEmpty(selfCarInvoice.getCardId()) && !StringUtils.isEmpty(selfCarInvoice.getTradeId())) {
                String[] cardIdArr = selfCarInvoice.getCardId().split(",");
                String[] tradeIdArr = null;
                if (selfCarInvoice.getTradeId() != null) {
                    tradeIdArr = selfCarInvoice.getTradeId().split(",");
                }
                List<CardAndTradeVo> cardAndTradeVos = new ArrayList<>();
                for (int i = 0; i < cardIdArr.length; i++) {
                    CardAndTradeVo cardAndTradeVo = new CardAndTradeVo();
                    cardAndTradeVo.setCardId(cardIdArr[i]);
                    if (tradeIdArr != null && tradeIdArr.length >= i + 1) {
                        cardAndTradeVo.setTradeId(tradeIdArr[i]);
                    } else {
                        cardAndTradeVo.setTradeId("");
                    }
                    cardAndTradeVos.add(cardAndTradeVo);
                }
                selfCarInvoice.setCardAndTradeVos(cardAndTradeVos);
            } else if (!StringUtils.isEmpty(selfCarInvoice.getCardId())) {
                selfCarInvoice.setCardIds(Arrays.asList(selfCarInvoice.getCardId().split(",")));
            } else if (!StringUtils.isEmpty(selfCarInvoice.getTradeId())) {
                selfCarInvoice.setTradeIds(Arrays.asList(selfCarInvoice.getTradeId().split(",")));
            }
            if (!StringUtils.isEmpty(selfCarInvoice.getInvoiceMakeTime()) && !NULL.equals(selfCarInvoice.getInvoiceMakeTime())) {
                String[] res = selfCarInvoice.getInvoiceMakeTime().split(",");
                selfCarInvoice.setInvoiceMakeStart(res[0]);
                selfCarInvoice.setInvoiceMakeEnd(res[1].replace("00:00:00", "23:59:59"));
            }
            RespR respR = new RespR(selfCarInvoiceService.findByPageAndInvoice(page, selfCarInvoice));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车计费信息
     *
     * @param page 参数集
     * @return 用户集合
     */
    @PostMapping("/findSelfcarCalculateInfo")
    @ApiOperation(value = "分页查询自有车计费信息", notes = "分页查询自有车计费信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findSelfcarCalculateInfo(Page page, SelfCarCalculateInfor carCalculateInfor, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, carCalculateInfor.getCustomId());
            if (!StringUtils.isEmpty(carCalculateInfor.getCalTime()) && !NULL.equals(carCalculateInfor.getCalTime())) {
                String[] res = carCalculateInfor.getCalTime().split(",");
                carCalculateInfor.setCalTimeStart(res[0]);
                carCalculateInfor.setCalTimeEnd(res[1]);
            }
            if (!StringUtils.isEmpty(carCalculateInfor.getActCalTime()) && !NULL.equals(carCalculateInfor.getCalTime())) {
                String[] res = carCalculateInfor.getActCalTime().split(",");
                carCalculateInfor.setActCalTimeStart(res[0]);
                carCalculateInfor.setActCalTimeEnd(res[1]);
            }
            RespR respR = new RespR(selfCarCalculateInfoService.findByPageAndCalculateInfor(page, carCalculateInfor));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车申请信息
     *
     * @param page 参数集
     * @return 用户集合
     */
    @PostMapping("/findSelfcarAppls")
    @ApiOperation(value = "分页查询自有车申请信息", notes = "分页查询自有车申请信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findSelfcarAppls(Page page, SelfCarAppl selfCarAppl, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, selfCarAppl.getCustomId());
            RespR respR = new RespR(selfCarApplyService.findByPageAndInvoice(page, selfCarAppl));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * 分页查询自有车计费信息
     *
     * @param carCalculateInfor
     * @return 用户集合
     */
    @PostMapping("/findSelfcarCalculateInfoSta")
    @ApiOperation(value = "自有车计费统计信息", notes = "自有车计费统计信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findSelfcarCalculateInfoSta(SelfCarCalculateInfor carCalculateInfor, User user) {
        try {
            checkHasAuthRole.checkCustomerRole(user, carCalculateInfor.getCustomId());
            if (!StringUtils.isEmpty(carCalculateInfor.getCalTime()) && !NULL.equals(carCalculateInfor.getCalTime())) {
                String[] res = carCalculateInfor.getCalTime().split(",");
                carCalculateInfor.setCalTimeStart(res[0]);
                carCalculateInfor.setCalTimeEnd(res[1]);
            }
            RespR respR = new RespR(selfCarCalculateInfoService.findSelfcarCalculateInfoSta(carCalculateInfor));
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }

    /**
     * @param tradeRequestCarNumVo
     * @return
     */
    @PostMapping("/getTradeList")
    @ApiOperation(value = "获取需要开票的交易Id列表", notes = "获取需要开票的交易Id列表")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR getTradeList(@RequestBody TradeRequestCarNumVo tradeRequestCarNumVo, User user) {

        if (!checkHasAuthRole.checkMessage(tradeRequestCarNumVo.getCarNum(), tradeRequestCarNumVo.getCompanyName(), tradeRequestCarNumVo.getCustomerName(),
                tradeRequestCarNumVo.getStartTime(), tradeRequestCarNumVo.getEndTime())) {
            return new RespR(false, "获取需要开票的交易Id列表失败，请查看数据是否维护准确");
        }

        checkHasAuthRole.checkCompanyRole(user, tradeRequestCarNumVo.getCompanyName());
        //通过车牌号查询所有的Etc卡号
        List<CustomerCarRec> customerCarRecs = selfCarBussService.getEtcsByCarNum(tradeRequestCarNumVo.getCarNum());
        if (customerCarRecs == null || customerCarRecs.size() <= 0) {
            return new RespR(false, "请输入有绑定ETC卡号的车牌");
        }
        //合并展示
        List<CardTradeModel> cardTradeModels = new ArrayList<>();
        customerCarRecs.forEach(customerCarRec -> {
            TradeRequestVo tradeRequestVo = new TradeRequestVo();
            tradeRequestVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
            tradeRequestVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tradeRequestVo.setStartTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getStartTime()))));
            tradeRequestVo.setEndTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getEndTime()))));
            tradeRequestVo.setTradeStatus(1);
            tradeRequestVo.setEtcId(customerCarRec.getEtcNum());
            RespR<List<CardTradeModel>> respRbefore = selfCarCustServicel.getTradeList(tradeRequestVo);
            if (respRbefore.getCode() == 0) {
                cardTradeModels.addAll(respRbefore.getData());
            }
        });
        return new RespR(cardTradeModels);
    }

    /**
     * @param tradeRequestCarNumVo
     * @return
     */
    @PostMapping("/applTradeList")
    @ApiOperation(value = "根据车牌号进行开票操作", notes = "根据车牌号进行开票操作")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR applTradeList(@RequestBody TradeRequestCarNumVo tradeRequestCarNumVo, User user) {

        if (!checkHasAuthRole.checkMessage(tradeRequestCarNumVo.getCarIdStr(), tradeRequestCarNumVo.getCompanyName(),
                tradeRequestCarNumVo.getCustomerName())) {
            return new RespR(false, "根据车牌号进行开票操作失败，请查看数据是否维护准确");
        }

        checkHasAuthRole.checkCompanyRole(user, tradeRequestCarNumVo.getCompanyName());
        String[] cardAndTrades = tradeRequestCarNumVo.getCarIdStr().split(",");
        Map<String, InvoiceApplVo> map = new HashMap<>(10);
        for (int i = 0; i < cardAndTrades.length; i++) {
            if (!StringUtils.isEmpty(cardAndTrades[i])) {
                String[] cardAndTrade = cardAndTrades[i].split("#");
                InvoiceApplVo invoiceApplVo = map.get(cardAndTrade[0]);
                if (invoiceApplVo == null) {
                    invoiceApplVo = new InvoiceApplVo();
                    invoiceApplVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
                    invoiceApplVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
                    invoiceApplVo.setCardId(cardAndTrade[0]);
                    invoiceApplVo.setTradeIds(new ArrayList<String>());
                    invoiceApplVo.getTradeIds().add(cardAndTrade[1]);
                    map.put(cardAndTrade[0], invoiceApplVo);
                } else {
                    invoiceApplVo.getTradeIds().add(cardAndTrade[1]);
                }
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, InvoiceApplVo> elm : map.entrySet()) {
            InvoiceApplVo invoiceApplVo = elm.getValue();
            RespR respR = selfCarCustServicel.applInvoice(invoiceApplVo);
            if (respR.getCode() == 1) {
                stringBuffer.append(invoiceApplVo.getCardId() + "开票申请失败原因:" + respR.getMsg() + "#");
            }
        }
        if (StringUtils.isEmpty(stringBuffer.toString())) {
            return new RespR(true);
        } else {
            return new RespR(false, stringBuffer.toString());
        }

    }

    /**
     * 查询已经开票信息
     *
     * @param
     * @return
     */
    @PostMapping("/findSelfcarInvoiceByTime")
    @ApiOperation(value = "通过时间，车牌号查询开票信息", notes = "通过时间，车牌号查询开票信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_SELFCAR)
    public RespR findSelfcarInvoiceByTime(@RequestBody SelfcarInvoiceByTimeVo selfcarInvoiceByTimeVo, User user) {
        try {

            if (!checkHasAuthRole.checkMessage(selfcarInvoiceByTimeVo.getCustomerName(), selfcarInvoiceByTimeVo.getCompanyName(),selfcarInvoiceByTimeVo.getStartTime(), selfcarInvoiceByTimeVo.getEndTime())) {
                return new RespR(false, "开票操作失败，请输入开始时间与结束时间");
            }


            checkHasAuthRole.checkCompanyRole(user, selfcarInvoiceByTimeVo.getCompanyName());
            if (!customerService.checkMoneyEnough(selfcarInvoiceByTimeVo.getCustomerName())) {
                return new RespR(false, "余额不足");
            }
            //通过车牌号查询所有的Etc卡号
            List<CustomerCarRec> customerCarRecs = null;
            if (selfcarInvoiceByTimeVo.getCarNum() != null && selfcarInvoiceByTimeVo.getCarNum() != "") {
                customerCarRecs = selfCarBussService.getEtcsByCarNum(selfcarInvoiceByTimeVo.getCarNum());
            } else {
                customerCarRecs = customerCarRecMapper.selectAllEtcByCompany(selfcarInvoiceByTimeVo.getCompanyName());
            }

            if (customerCarRecs == null || customerCarRecs.size() <= 0) {
                return new RespR(false, "无ETC卡号的车牌");
            }
            CustomerRec customerRec = new CustomerRec();
            customerRec.setCustomerName(selfcarInvoiceByTimeVo.getCustomerName());
            customerRec.setCompanyName(selfcarInvoiceByTimeVo.getCompanyName());
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
            if (customerRec1 == null || customerRec1.getRecStatus().intValue() != 1) {
                return new RespR(false, "客户未备案");
            }
            List<B2BInvoiceListModel> allSelfInvocies = new ArrayList<>();
            StringBuilder resp = new StringBuilder("");
            customerCarRecs.forEach(customerCarRec -> {
                SelfCarDueQueryVo selfCarDueQueryVo = new SelfCarDueQueryVo();
                selfCarDueQueryVo.setCustomername(selfcarInvoiceByTimeVo.getCustomerName());
                selfCarDueQueryVo.setCompanyName(selfcarInvoiceByTimeVo.getCompanyName());
                selfCarDueQueryVo.setStartTime(selfcarInvoiceByTimeVo.getStartTime());
                selfCarDueQueryVo.setEndTime(selfcarInvoiceByTimeVo.getEndTime());
                selfCarDueQueryVo.setCardId(customerCarRec.getEtcNum());
                RespR<List<B2BInvoiceListModel>> respR = selfCarCustServicel.getSelfCarInvoicesByTime(selfCarDueQueryVo, customerRec1);
                if (respR.getCode() == 0) {
                    allSelfInvocies.addAll(respR.getData());
                }else{
                    if(!"未查得".equals(respR.getMsg())){
                        resp.append(customerCarRec.getEtcNum()).append(":").append(respR.getMsg()).append("#");
                    }
                }
            });
            if(!StringUtil.isEmpty(resp.toString())){
                return new RespR(false,resp.toString());
            }
            return new RespR(allSelfInvocies);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }


    /**
     * 批量查询自有车交易信息
     *
     * @param file 参数集
     * @return
     */
    @PostMapping("/batchImportSelfcarTrades")
    @ApiOperation(value = "批量查询自有车交易信息", notes = "批量查询自有车交易信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_ADMIN)
    public RespR batchImportSelfcarTrades(@RequestParam("file") MultipartFile file) {
        try {

            if (null == file) {
                return new RespR(false, "批量查询自有车交易信息失败，请查看数据是否维护准确");
            }


            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            List<SelfCarTrade> list = ExcelImportUtil.importExcel(file.getInputStream(), SelfCarTrade.class, params);
            RespR respR = selfCarTradeService.batchImportSelfcarTrades(list);
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }


    /**
     * 批量查询自有车发票信息
     *
     * @param file 参数集
     * @return
     */
    @PostMapping("/batchImportSelfcarInvoices")
    @ApiOperation(value = "批量查询自有车发票信息", notes = "批量查询自有车发票信息")
    @LoginRequired(role = AuthenticationInterceptor.AUTH_ADMIN)
    public RespR batchImportSelfcarInvoices(@RequestParam("file") MultipartFile file) {
        try {

            if (null == file) {
                return new RespR(false, "批量查询自有车发票信息失败，请查看数据是否维护准确");
            }

            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            List<SelfCarInvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), SelfCarInvoice.class, params);
            RespR respR = selfCarInvoiceService.findImportSelfcarInvoices(list);
            return respR;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }
    /**
     * 回复applyId
     */
    @GetMapping("/recoverApplyId")
    public RespR recoverApplyId() {
        try {
            List<SelfCarTrade> selfCarTrades = sellCarTradeMapper.sellectAllNullApplid();
            log.info("开始修复条数{}",selfCarTrades.size());
            selfCarTrades.forEach(selfCarTrade->{
                TradeApplyQueryInvVo tradeApplyQueryInvVo = new TradeApplyQueryInvVo();
                tradeApplyQueryInvVo.setCompanyNum(selfCarTrade.getCompanyNum());
                tradeApplyQueryInvVo.setTradeId(selfCarTrade.getTradeId());
                tradeApplyQueryInvVo.setCardId(selfCarTrade.getCardId());
                RespR<TradeApplyQueryResponse> respR =  selfCarCustService.getApplyQueryByTradeId(tradeApplyQueryInvVo);
                if(respR.getCode() == 0){
                    String applyId = respR.getData().getApplyId();
                    if(!StringUtils.isEmpty(applyId)){
                        SelfCarAppl selfCarAppl = selfCarApplMapper.selectByApplId(applyId);
                        if(selfCarAppl != null){
                            selfCarTrade.setApplId(selfCarAppl.getApplId());
                            selfCarTrade.setAclTime(DateUtil.tTimeToDate(selfCarAppl.getApplTime()));
                            log.info("开始修复{}",selfCarTrade);
                            sellCarTradeMapper.updateByTradeId(selfCarTrade);
                        }else {
                            selfCarTrade.setApplId(applyId);
                            selfCarTrade.setAclTime(DateUtil.tTimeToDate(selfCarAppl.getApplTime()));
                            log.info("开始修复{}",selfCarTrade);
                            sellCarTradeMapper.updateByTradeId(selfCarTrade);
                        }

                    }else{
                        log.info("修复失败{}",11111111);
                    }
                }else {
                    log.info("修复失败{}",respR.getMsg());
                }


            });
            log.info("修复完成");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new RespR(false, e.getMessage());
        }
    }
    @Autowired
    SelfCarApplMapper selfCarApplMapper;
}
