package com.pj.project.tb_business;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.bo.OtherBusinessEditBO;
import com.pj.api.wx.bo.MsgDataBO;
import com.pj.api.wx.service.WxService;
import com.pj.constants.UserTypeEnum;
import com.pj.current.config.CarConfig;
import com.pj.current.config.MyConfig;
import com.pj.current.config.PartConfig;
import com.pj.current.config.WxConfig;
import com.pj.current.satoken.StpUserUtil;
import com.pj.project.relation_business_car.RelationBusinessCar;
import com.pj.project.relation_business_car.RelationBusinessCarService;
import com.pj.project.relation_goods_type.RelationGoodsTypeService;
import com.pj.project.relation_type_item.RelationTypeItem;
import com.pj.project.relation_type_item.RelationTypeItemService;
import com.pj.project.tb_business_car.TbBusinessCar;
import com.pj.project.tb_business_car.TbBusinessCarService;
import com.pj.project.tb_business_item.TbBusinessItem;
import com.pj.project.tb_business_item.TbBusinessItemService;
import com.pj.project.tb_business_people.TbBusinessPeople;
import com.pj.project.tb_business_people.TbBusinessPeopleService;
import com.pj.project.tb_business_sort.TbBusinessSort;
import com.pj.project.tb_business_sort.TbBusinessSortService;
import com.pj.project.tb_car.TbCar;
import com.pj.project.tb_car.TbCarService;
import com.pj.project.tb_car_no_color.TbCarNoColor;
import com.pj.project.tb_car_no_color.TbCarNoColorService;
import com.pj.project.tb_costomer.TbCostomer;
import com.pj.project.tb_costomer.TbCostomerService;
import com.pj.project.tb_declare.TbDeclare;
import com.pj.project.tb_declare.TbDeclareService;
import com.pj.project.tb_driver.TbDriver;
import com.pj.project.tb_driver.TbDriverService;
import com.pj.project.tb_goods.TbGoods;
import com.pj.project.tb_goods.TbGoodsService;
import com.pj.project.tb_item.TbItem;
import com.pj.project.tb_item.TbItemService;
import com.pj.project.tb_item_type.TbItemType;
import com.pj.project.tb_item_type.TbItemTypeService;
import com.pj.project.tb_notices.TbNoticesService;
import com.pj.project.tb_sort_group.TbSortGroup;
import com.pj.project.tb_sort_group.TbSortGroupService;
import com.pj.project.tb_unit.TbUnit;
import com.pj.project.tb_unit.TbUnitService;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.project4sp.admin.SpAdminService;
import com.pj.project4sp.global.BusinessException;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_business -- 入境登记
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness> implements IService<TbBusiness> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbBusinessMapper tbBusinessMapper;
    @Resource
    private TbCarService tbCarService;
    @Resource
    private TbDriverService tbDriverService;
    @Resource
    private TbCostomerService tbCostomerService;

    @Resource
    private TbItemService tbItemService;
    @Resource
    private TbItemTypeService tbItemTypeService;
    @Resource
    private TbBusinessItemService tbBusinessItemService;

    @Resource
    TbUnitService tbUnitService;
    @Resource
    TbBusinessPeopleService tbBusinessPeopleService;
    @Resource
    private PartConfig partConfig;
    @Resource
    private CarConfig carConfig;

    @Resource
    private TbNoticesService tbNoticesService;

    @Resource
    private TbCarNoColorService tbCarNoColorService;

    @Resource
    TbBusinessCarService tbBusinessCarService;
    @Resource
    @Lazy
    TbDeclareService tbDeclareService;
    @Resource
    WxConfig wxConfig;
    @Resource
    @Lazy
    WxService wxService;
    @Resource
    MyConfig myConfig;

    @Resource
    private SpAdminService spAdminService;

    @Resource
    private TbBusinessSortService tbBusinessSortService;
    @Resource
    private TbSortGroupService tbSortGroupService;
    @Resource
    private TbGoodsService tbGoodsService;
    @Resource
    private RelationTypeItemService relationTypeItemService;
    @Resource
    private RelationBusinessCarService relationBusinessCarService;


    private final List<String> CAR_LIST = StrUtil.splitTrim("浙,粤,京,津,冀,晋,蒙,辽,黑,沪,吉,苏,皖,赣,鲁,豫,鄂,湘,桂,琼,渝,川,贵,云,藏, 陕, 甘, 青, 宁", ",");


    /**
     * 增
     */
    public AjaxJson addOrUpdate(TbBusiness t) {
        t.setBusinessType(TbBusiness.BusinessType.HOLD_CAR.getCode());
        if (StrUtil.isEmpty(t.getDeclareNo())) {
            throw new BusinessException("请选择申报单");
        }
        if (StrUtil.isNotEmpty(t.getId()) && StrUtil.isNotEmpty(t.getDeclareNo())) {
            TbBusiness db = this.getById(t.getId());
            if (!StrUtil.equals(db.getDeclareNo(), t.getDeclareNo())) {
                TbDeclare tbDeclare = tbDeclareService.findByDeclareNo(db.getDeclareNo());
                if (tbDeclare != null) {
                    tbDeclare.setBusinessId("");
                    tbDeclareService.updateById(tbDeclare);
                }
            }
        }
        Double carSize = t.getCardSize();
        if (carSize != null && carSize > carConfig.getMaxLength()) {
            return AjaxJson.getError("车辆规格不能大于" + carConfig.getMaxLength());
        }
        Double netWeight = t.getNetWeight();
        if (netWeight != null && netWeight > carConfig.getMaxWeight()) {
            return AjaxJson.getError("车辆载重不能大于" + carConfig.getMaxWeight());
        }
        t.setCreateBy(StpUserUtil.getAdmin().getName());
        createCarUnit(t);
        String customerId = t.getCustomerId();
        TbCostomer tbCostomer = tbCostomerService.getById(customerId);
        t.setCustomerName(tbCostomer.getName()).setCustomerType(tbCostomer.getPayType());
        if (StrUtil.equals(customerId, UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            t.setConfirmInputBy(StpUserUtil.getAdmin().getName())
                    .setConfirmInput(1)
                    .setConfirmInputTime(new Date());
        }
        if (StrUtil.isEmpty(t.getId())) {
            t.setCreateTime(new Date());
            t.setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
            storeMsg(t.getCustomerId(), "新增一条业务数据:【" + t.getNo() + "】" + DateUtil.now() + "。");
        } else {
            storeMsg(t.getCustomerId(), "业务订单:【" + t.getNo() + "】数据发生更改，" + DateUtil.now() + "。");
        }
        saveOrUpdate(t);
        createBusinessPeople(t);
        tbBusinessItemService.removeByBusinessId(t.getId());
        BigDecimal price = new BigDecimal(0);
        List<TbBusinessItem> items = JSONUtil.toList(t.getItemJson(), TbBusinessItem.class);
        int index = 1;
        for (TbBusinessItem item : items) {
            Double num = NumberUtil.parseDouble(item.getNum());
            TbItem tbItem = tbItemService.getById(item.getItemId());
            String typeId = tbItem.getTypeId();
            price = price.add(NumberUtil.mul(num, tbItem.getPrice()));
            TbItemType tbItemType = tbItemTypeService.getById(typeId);
            item.setBusinessId(t.getId()).setItemCode(tbItem.getItemCode()).setBusinessType(tbItem.getBusinessType())
                    .setPayType(tbItem.getPayType()).setPayTypeName(tbItem.getPayTypeName())
                    .setItemName(tbItem.getItemName()).setItemPrice(tbItem.getPrice())
                    .setTaxRate(NumberUtil.div(tbItem.getTaxRate().doubleValue(), 100D, 2))
                    .setItemTypeId(typeId).setItemTypeName(tbItemType.getName()).setBusinessType(tbItemType.getBusinessType())
                    .setUnit(tbItem.getUnit()).setTotal(NumberUtil.mul(num, tbItem.getPrice())).setCreateTime(new Date())
                    .setNo(t.getNo() + "0" + index);
            tbBusinessItemService.save(item);

            index++;
        }
        List<TbBusinessCar> carList = JSONUtil.toList(t.getCarJson(), TbBusinessCar.class);
        String chinaCarNo = carList.stream().map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
        t.setChinaCarNo(StrUtil.isNotEmpty(chinaCarNo) ? chinaCarNo.toUpperCase() : "");
        carList.forEach(tbBusinessCar -> {
            tbBusinessCar.setIsLock(0);
            String carNo = tbBusinessCar.getCarNo().toUpperCase();
            TbBusinessCar db = tbBusinessCarService.findByBusinessIdAndCarNo(t.getId(), carNo);
            if (db != null) {
                tbBusinessCar.setId(db.getId()).setIsLock(db.getIsLock());
            }
            TbBusinessCar car = tbBusinessCarService.findInAndNoBusinessCar(carNo);
            if (car != null) {
                tbBusinessCar.setId(car.getId()).setRealInTime(car.getRealInTime()).setIsLock(car.getIsLock());
            }
            TbCar tbCar = tbCarService.findByCardNo(carNo);
            tbBusinessCar.setBusinessId(t.getId());
            tbBusinessCar.setCarNo(carNo).setCarCompany(tbCar != null ? tbCar.getCustomerName() : "临时");
            tbBusinessCar.setBusinessId(t.getId()).setCustomerId(t.getCustomerId());
            if (StrUtil.isEmpty(tbBusinessCar.getNo())) {
                tbBusinessCar.setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
            }

        });
        String yueCarNo = t.getCardNo().toUpperCase();
        TbBusinessCar yueCar = tbBusinessCarService.findInAndNoBusinessCar(yueCarNo);
        if (yueCar == null) {
            yueCar = tbBusinessCarService.findByBusinessIdAndCarNo(t.getId(), yueCarNo);
            if (yueCar == null) {
                yueCar = new TbBusinessCar();
                yueCar.setIsLock(0);
            }
        }
        yueCar.setBusinessId(t.getId()).setCarSize(t.getCardSize()).setCarNo(yueCarNo).setCustomerId(t.getCustomerId());
        if (StrUtil.isEmpty(yueCar.getNo())) {
            yueCar.setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
        }
        carList.add(yueCar);
        tbBusinessCarService.saveOrUpdateBatch(carList);
        t.setItemPrice(price)
                .setTotalMoney(price);
        this.saveOrUpdate(t);
        if (StrUtil.isNotEmpty(t.getDeclareNo())) {
            TbDeclare tbDeclare = tbDeclareService.findByDeclareNo(t.getDeclareNo());
            tbDeclare.setBusinessId(t.getId());
            tbDeclareService.updateById(tbDeclare);
        }
        return AjaxJson.getSuccess();
    }

    public void storeMsg(String businessCustomerId, String content) {
        String currentCustomerId = StpUserUtil.getCustomerId();
        if (StrUtil.equals(currentCustomerId, UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            BusinessMessageManager.set(businessCustomerId, content);
        } else {
            BusinessMessageManager.set(UserTypeEnum.PLATFORM_ADMIN.getCustomerId(), content);
        }
    }

    private void createBusinessPeople(TbBusiness t) {
        tbBusinessPeopleService.removeByBusinessId(t.getId());
        List<TbBusinessPeople> peopleList = JSONUtil.toList(t.getPeopleJson(), TbBusinessPeople.class);
        peopleList.forEach(tbBusinessPeople -> tbBusinessPeople.setBusinessId(t.getId()).setCreateTime(new Date()));
        tbBusinessPeopleService.saveBatch(peopleList);
    }

    private void createCarUnit(TbBusiness t) {
        TbUnit tbUnit = tbUnitService.findByUnit(t.getCardSize());
        if (tbUnit == null) {
            tbUnit = new TbUnit();
            tbUnit.setUnit(t.getCardSize() + "");
            tbUnitService.save(tbUnit);
        }
    }


    private TbDriver createDriver(TbBusiness business) {
        TbDriver tbDriver = tbDriverService.findByIdCardNo(business.getCardNo());
        if (tbDriver == null) {
            tbDriver = new TbDriver();
            tbDriver.setCreateTime(new Date()).setIdCard(business.getCardNo())
                    .setName(business.getDriverName()).setPhone(business.getDriverPhone());
            tbDriverService.save(tbDriver);
        }
        return tbDriver;

    }

    private TbCar createCar(TbBusiness business) {
        String cardNo = business.getCardNo();
        TbCar tbCar = tbCarService.findByCardNo(cardNo);
        if (tbCar == null) {
            tbCar = new TbCar();
        }
        tbCar.setCardNo(cardNo)
                .setCardSize(business.getCardSize())
                .setCountryName(business.getCountryName())
                .setLastGoodsName(business.getGoodsName())
                .setLastNetWeight(business.getNetWeight());
        tbCarService.saveOrUpdate(tbCar);
        return tbCar;
    }


    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbBusiness> getList(SoMap so) {
        return tbBusinessMapper.getList(so);
    }


    public void pay(String id, String payTicket) {
        TbBusiness tbBusiness = this.getById(id);
        SpAdmin admin = StpUserUtil.getAdmin();
        tbBusiness.setPayStatus(2).setPayBy(admin.getName())
                .setPayBy(StpUserUtil.getAdmin().getName())
                .setPayTicket(payTicket)
                .setPayTime(new Date());
        if (StrUtil.equals(admin.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            tbBusiness.setAdminConfirmPay(1).setPayStatus(3)
                    .setAdminConfirmPayBy(admin.getName()).setAdminConfirmPayTime(new Date());
        }
        this.updateById(tbBusiness);
        storeMsg(tbBusiness.getCustomerId(), "业务订单【" + tbBusiness.getNo() + "】已支付" + DateUtil.now() + "。");
        //发送消息
        String text = "您的费用已支付，业务单号[" + tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);
    }

    public void confirm(List<String> ids) {
        ids.forEach(id -> {
            TbBusiness business = this.getById(id);
            business.setConfirmInput(1).setAdminConfirmInput(1)
                    .setConfirmInputTime(new Date())
                    .setConfirmInputBy(StpUserUtil.getAdmin().getName());
            this.updateById(business);
            List<TbBusinessCar> cars = tbBusinessCarService.findOtherBusinessCar(business.getId());
            String carNoStr = cars.stream().map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
            storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已确认" + DateUtil.now() + "。");
            List<TbBusinessItem> items = tbBusinessItemService.findByBusinessId(id);
            String bigBusinessType = business.getGoodsId();
            items.forEach(item -> {
                String businessType = item.getBusinessType();
                if (!StrUtil.equals(businessType, TbCostomer.CustomerEnum.BUSINESS_TYPE.getType())) {
                    String customerId = business.getCustomerId();
                    TbCostomer tbCostomer = tbCostomerService.getById(customerId);
                    String customerType = tbCostomer.getType();
                    if (StrUtil.equals(businessType, customerType)) {
                        MsgDataBO msgDataBO = new MsgDataBO("订单号：" + item.getNo(), "系统自动确认",
                                DateUtil.now(),
                                business.getGoodsName() + "(" + item.getItemTypeName() + item.getItemName() + "-" + carNoStr + ")");
                        List<SpAdmin> spAdminList = spAdminService.findByCustomerId(customerId);
                        Date now = new Date();
                        item.setPickCustomerId(customerId).setPick(1)
                                .setPickCustomerName(tbCostomer.getName()).setPickTime(now)
                                .setConfirm(1).setConfirmTime(now);
                        tbBusinessItemService.updateById(item);
                        spAdminList.stream().map(SpAdmin::getOpenid).forEach(openId -> {
                            String detailUrl = myConfig.getWebDomain() + "/pages/business-item/item-detail?itemId=" + item.getId() + "&openid=" + openId;
                            wxService.sendTemplateMsg(wxConfig.getBusinessConfirmTemplate(), openId, msgDataBO, detailUrl);
                        });
                    } else {
                        String remark = "车牌：";
                        String carNo = business.getCardNo();
                        String chinaCarNo = business.getChinaCarNo();
                        if (StrUtil.isNotEmpty(carNo) && StrUtil.isNotEmpty(chinaCarNo)) {
                            remark += carNo + "、" + chinaCarNo;
                        }
                        if (StrUtil.isEmpty(carNo) && StrUtil.isNotEmpty(chinaCarNo)) {
                            remark += chinaCarNo;
                        }
                        if (StrUtil.isNotEmpty(carNo) && StrUtil.isEmpty(chinaCarNo)) {
                            remark += carNo;
                        }
                        MsgDataBO msgDataBO = new MsgDataBO("订单号：" + item.getNo(), item.getItemTypeName(),
                                item.getItemName(), business.getGoodsName(), DateUtil.now(), remark);
                        List<String> openidList = tbCostomerService.findByBusinessTypeOpenid(businessType, bigBusinessType);
                        openidList.forEach(openid -> {
                            String detailUrl = myConfig.getWebDomain() + "/pages/business-item/item-detail?itemId=" + item.getId() + "&openid=" + openid;
                            wxService.sendTemplateMsg(wxConfig.getBusinessNoticeTemplate(), openid, msgDataBO, detailUrl);
                        });
                    }
                }
            });
        });
    }

    public void adminConfirmPay(List<String> ids, String ticket) {
        ids.forEach(id -> {
            TbBusiness business = this.getById(id);
            business.setAdminConfirmPayTime(new Date()).setAdminConfirmPay(1).setAdminConfirmPayBy(StpUserUtil.getAdmin().getName())
                    .setPayStatus(3).setPayTicket(ticket);
            this.updateById(business);
            storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已确认支付" + DateUtil.now() + "。");
            //发送消息
            String text = "您的费用已支付，业务单号[" + business.getNo() + "]";
            tbNoticesService.sendNotice(business.getId(), business.getNo(), business.getCustomerId(), text);
        });
    }


    @Deprecated
    public void adminConfirmIn(String id, String inChannel) {
        TbBusiness tbBusiness = this.getById(id);
        tbBusiness.setRealInTime(new Date()).setInChannel(inChannel);
        this.updateById(tbBusiness);

        //更新境外车入场记录

        //更新中国车入场记录

        //发送消息
        String text = "您的车辆已入场，业务单号[" + tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);

    }

    public void adminOut(String id, Date outDayTime, String outChannel, String carType) {
        TbBusiness tbBusiness = this.getById(id);
        tbBusiness.setOutDayTime(outDayTime).setOutChannel(outChannel);
        calculationPartMoney(carType, tbBusiness);
        this.updateById(tbBusiness);

        //更新境外车出场记录

        //更新中国车出场记录

        //发送消息
        String text = "您的车辆已离场，业务单号[" + tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);

    }

    @Async
    @Deprecated
    public void calculationPartMoney(String itemType, TbBusiness tbBusiness) {
        Date iTime = tbBusiness.getRealInTime();
        Date oTime = tbBusiness.getOutDayTime();
        if (itemType.contains("中国")) {
            iTime = tbBusiness.getChinaCarInTime();
            oTime = tbBusiness.getChinaCarOutTime();
        }
        BigDecimal price = calculationPartMoney(iTime, oTime);
        if (itemType.contains("中国")) {
            int len = tbBusiness.getCardNo().split(" ").length;
            tbBusiness.setChinaPartMoney(price.multiply(new BigDecimal(len)));
        } else {
            tbBusiness.setPartMoney(price);
        }
        tbBusiness.setTotalMoney(tbBusiness.getItemPrice().add(tbBusiness.getChinaPartMoney()).add(tbBusiness.getPartMoney()));
    }

    public BigDecimal calculationPartMoney(Date iTime, Date oTime) {
        BigDecimal zero = new BigDecimal("0");
        if (iTime == null || oTime == null) {
            return zero;
        }
        LocalDateTime inDayTime = iTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime outDayTime = oTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        long minutes = ChronoUnit.MINUTES.between(inDayTime, outDayTime);
        if (minutes < 0) {
            return zero;
        }
        long days = ChronoUnit.DAYS.between(inDayTime.toLocalDate(), outDayTime.toLocalDate());
        BigDecimal p = partConfig.getBasePrice();//乘积因子
        BigDecimal extraPrice = partConfig.getExtraPrice();
        int unit = (int) Math.ceil(NumberUtil.div(minutes, 24 * 60));
        if (minutes < partConfig.getFreeMinutes()) {
            unit = 0;
        }
        return p.multiply(new BigDecimal(unit)).add(new BigDecimal(days).multiply(extraPrice));
    }


    public Map<String, Object> getBusinessMoney(String businessCarId, String state) {
        Map<String, Object> result = new HashMap<>();
        List<TbBusiness> businessList = this.findOtherBusinessByCarId(businessCarId);
        Set<TbBusinessCar> cars = new HashSet<>();
        //越南车是否需要支付
        int vietnamCarPay = businessList.stream().anyMatch(tbBusiness -> {
            TbGoods tbGoods = tbGoodsService.getById(tbBusiness.getGoodsId());
            return tbGoods.getVietnamCarPay() == 1;
        }) ? 1 : 0;
        //中国车是否需要支付
        int chinaCarPay = businessList.stream().anyMatch(tbBusiness -> {
            TbGoods tbGoods = tbGoodsService.getById(tbBusiness.getGoodsId());
            return tbGoods.getChinaCarPay() == 1;
        }) ? 1 : 0;
        //无业务的车辆,中国车和越南车都需要支付
        if (businessList.isEmpty()) {
            vietnamCarPay = 1;
            chinaCarPay = 1;
            cars.add(tbBusinessCarService.getById(businessCarId));
        }
        businessList = businessList.stream().filter(tbBusiness -> {
            TbGoods tbGoods=tbGoodsService.getById(tbBusiness.getGoodsId());
            Integer payStep = tbGoods.getPayStep();
            //确认订单后方可缴费
            return TbGoods.PayStep.AFTER_CONFIRM.getCode().equals(payStep) && tbBusiness.getAdminConfirmInput() == 1
                    //或者下单后可缴费
                    || TbGoods.PayStep.BEFORE_CONFIRM.getCode().equals(payStep)&& tbBusiness.getAdminConfirmInput() >=0;
        }).collect(Collectors.toList());
        businessList.forEach(tbBusiness -> {
            List<TbBusinessCar> businessCars = tbBusinessCarService.findOtherBusinessCar(tbBusiness.getId());
            cars.addAll(businessCars);
        });
        List<String> businessIdList = businessList.stream().map(TbBusiness::getId).collect(Collectors.toList());
        String businessIds = StrUtil.join(",", businessIdList);
//        result.put("type", businessType);
        result.put("showPay", true);
        result.put("businessId", businessIds);
        List<TbBusinessItem> items = tbBusinessItemService.findByBusinessIdList(businessIdList);
        Date now = new Date();
        List<Map<String, Object>> carsList = new ArrayList<>();
        for (TbBusinessCar tbBusinessCar : cars) {
            Date inTime = tbBusinessCar.getRealInTime();
            BigDecimal partMoney = new BigDecimal("0");
            String carNo = tbBusinessCar.getCarNo().substring(0, 1);
            if (inTime != null && tbBusinessCar.getRealOutTime() == null) {
                if (tbBusinessCar.getPay() == 1 && tbBusinessCar.getPayTime() != null) {
                    inTime = tbBusinessCar.getPayTime();
                }
                partMoney = this.calculationPartMoney(inTime, now);
            }
            if (StrUtil.isNotEmpty(tbBusinessCar.getColor())) {//蓝色车辆免费
                List<TbCarNoColor> freeList = tbCarNoColorService.getFreeColor();
                List<String> colorList = freeList.stream().map(f -> f.getCarNoColor().substring(0, 1)).collect(Collectors.toList());
                String color = tbBusinessCar.getColor().substring(0, 1);
                if (colorList.contains(color)) {
                    partMoney = new BigDecimal("0");
                }
            }

            //越南车牌,是否免费
            if (!CAR_LIST.contains(carNo) && vietnamCarPay == 0) {
                partMoney = new BigDecimal("0");
            }
            //中国车,是否免费
            if (CAR_LIST.contains(carNo) && chinaCarPay == 0) {
                partMoney = new BigDecimal("0");
            }
            Map<String, Object> carMap = new HashMap<>();
            carMap.put("price", partMoney);
            carMap.put("id", tbBusinessCar.getId());
            carMap.put("carNo", tbBusinessCar.getCarNo());
            carMap.put("pay", tbBusinessCar.getPay());
            if (TbBusinessCar.PayTypeEnum.FEE_TYPE.getType().equals(tbBusinessCar.getPayType())) {
                carMap.put("price", 0);
            }
            carsList.add(carMap);
        }
        result.put("carList",carsList.stream().sorted(Comparator.comparingDouble(obj->Double.valueOf(obj.get("price").toString()))).collect(Collectors.toList()));
        BigDecimal itemsPrice = new BigDecimal("0");
        List<Map<String, Object>> itemList = new ArrayList<>();
        for (TbBusinessItem item : items) {
            BigDecimal itemPrice = item.getItemPrice().multiply(new BigDecimal(item.getNum()));
            if (item.getPayStatus()==1){
                continue;
            }
            itemsPrice = itemsPrice.add(itemPrice);
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("id", item.getId());
            itemMap.put("name", item.getItemName() + "(" + item.getItemTypeName() + ")");
            itemMap.put("price", itemPrice);
            itemMap.put("pay", item.getPayStatus());
            itemList.add(itemMap);
            TbBusinessSort tbBusinessSort = tbBusinessSortService.findByItemTypeId(item.getItemTypeId());
            if (tbBusinessSort != null) {
                TbSortGroup sortGroup = tbSortGroupService.getById(tbBusinessSort.getGroupId());
                if (sortGroup.getCompletePay().equals(1) && sortGroup.getStatus().equals(1)) {
                    List<TbBusinessSort> sorts = tbBusinessSortService.findByGroupId(sortGroup.getId());
                    if (sorts.size() > items.size()) {
                        result.put("showPay", false);
                    }
                }
            }
        }
        result.put("itemsPrice", itemsPrice);
        result.put("itemList", itemList);
        return result;
    }

    public List<TbBusiness> findOtherBusinessByCarId(String businessCarId) {
        return tbBusinessMapper.findOtherBusinessByCarId(businessCarId);
    }

    public void uploadReport(TbBusiness tbBusiness) {
        this.updateById(tbBusiness);
        List<TbBusinessCar> cars = tbBusinessCarService.findOtherBusinessCar(tbBusiness.getId());
        tbBusinessCarService.updateBatchById(cars);
    }


    public List<CarDisincle> getCarDisincleList(SoMap soMap) {
        return tbBusinessMapper.getCarDisincleList(soMap);
    }

    public TbBusiness getOtherBusinessById(String id) {
        TbBusiness tbBusiness = this.getById(id);
        List<TbBusinessItem> tbBusinessItems = tbBusinessItemService.findByBusinessId(id);
        tbBusiness.setItems(tbBusinessItems);
        List<TbBusinessCar> cars = tbBusinessCarService.findOtherBusinessCar(id);
        tbBusiness.setCars(cars);
        return tbBusiness;
    }

    public void deleteOtherBusiness(String id) {
        TbBusiness db = super.getById(id);
        String declareNo = db.getDeclareNo();
        if (StrUtil.isNotEmpty(declareNo)) {
            tbDeclareService.rebackDeclareNo(declareNo);
        }
        this.removeById(id);
        //删除响应业务项
        tbBusinessItemService.removeByBusinessId(id);
        //检查是否删除车辆
        List<TbBusinessCar> tbBusinessCarList = tbBusinessCarService.findOtherBusinessCar(id);
        tbBusinessCarList.forEach(tbBusinessCar -> {
            //未入场
            if (tbBusinessCar.getRealInTime() == null) {
                List<RelationBusinessCar> relationBusinessCars = relationBusinessCarService.findByBusinessCarId(tbBusinessCar.getId());
                //无关联业务==>删除
                if (relationBusinessCars.size() == 1) {
                    tbBusinessCarService.removeById(tbBusinessCar.getId());
                }
            }
        });
        //删除关系
        relationBusinessCarService.removeByBusinessId(id);
    }

    public int checkCarBusinessType(String typeId, String carNo, String operateTime, int before) {
        return tbBusinessMapper.checkCarBusinessType(typeId, carNo, operateTime, before);
    }

    public int checkCarBusinessType(String typeId, String carNo, String timeStart, String timeEnd, String businessId) {
        return tbBusinessMapper.checkCarBusinessTypeByTime(typeId, carNo, timeStart, timeEnd, businessId);
    }

    public void manualConfirmPay(String id, List<TbBusinessCar> cars, String remark) {
        TbBusiness db = this.getById(id);
        if (db == null) {
            throw new BusinessException("业务不存在");
        }
        Date now = new Date();
        db.setPayStatus(3).setPayMoney(db.getItemPrice()).setPayTime(now);
        this.updateById(db);
        cars.forEach(tbBusinessCar -> {
            Date realInTime = tbBusinessCar.getRealInTime();
            Date realOutTime = tbBusinessCar.getRealOutTime();
            if (realInTime != null && realOutTime != null) {
                BigDecimal price = calculationPartMoney(realInTime, realOutTime);
                tbBusinessCar.setMoney(price);
            }
            tbBusinessCar.setPay(1).setPayTime(now);
            tbBusinessCarService.updateById(tbBusinessCar);
        });
        List<TbBusinessItem> items = tbBusinessItemService.findByBusinessId(id);
        items.forEach(tbBusinessItem -> tbBusinessItem
                .setPayStatus(1).setPayTime(now)
                .setRemark(StrUtil.isEmpty(remark) ? "手动确认" : remark)
        );
        tbBusinessItemService.updateBatchById(items);
    }

    public void unBindCar(String id, String businessCarId) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("id", id).eq("business_car_id", businessCarId);
        TbBusiness db = getOne(ew);
        if (db == null) {
            throw new BusinessException("业务单不存在");
        }
        tbBusinessMapper.unBindCar(id);
    }


    public void addOtherBusiness(OtherBusinessBO otherBusinessBO) {
        List<TbItem> tbItems = otherBusinessBO.getItems();
        if (tbItems.isEmpty()) {
            throw new BusinessException("请选择明细");
        }
        List<TbBusinessCar> cars = otherBusinessBO.getCars();
        if (cars.isEmpty()) {
            throw new BusinessException("作业车辆不能为空");
        }
        Date now = new Date();
        TbGoods tbGoods = tbGoodsService.getById(otherBusinessBO.getGoodsId());
        TbBusiness tbBusiness = new TbBusiness();
        String customerId = otherBusinessBO.getCustomerId();
        tbBusiness.setCreateBy(StpUserUtil.getAdmin().getName());
        tbBusiness.setPayStep(tbGoods.getPayStep());
        TbCostomer tbCostomer = tbCostomerService.getById(customerId);
        if (tbCostomer != null) {
            tbBusiness.setCustomerId(customerId).setCustomerName(tbCostomer.getName());
        }
        BigDecimal price = new BigDecimal("0");
        List<TbBusinessItem> itemList = new ArrayList<>();
        String no = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4);
        int index = 1;
        for (TbItem tbItem : tbItems) {
            TbItem db = tbItemService.getById(tbItem.getId());
            TbBusinessItem item = new TbBusinessItem();
            int num = tbItem.getNum();
            String typeId = tbItem.getTypeId();
            TbItemType tbItemType = tbItemTypeService.getById(typeId);
            BigDecimal itemTotalPrice = tbItem.getPrice().multiply(new BigDecimal(num));
            item.setNo(no + "0" + index).setPayTypeName(db.getPayTypeName()).setPayType(db.getPayType())
                    .setBusinessType(db.getBusinessType()).setTaxRate(NumberUtil.div(db.getTaxRate().doubleValue(), 100D, 2));
            item.setItemCode(db.getItemCode()).setNum(num + "").setItemId(db.getId())
                    .setItemName(db.getItemName()).setItemPrice(db.getPrice()).setRemark(tbItem.getRemark())
                    .setItemTypeId(typeId).setItemTypeName(tbItemType.getName())
                    .setUnit(db.getUnit()).setTotal(itemTotalPrice).setCreateTime(now);
            price = price.add(itemTotalPrice);
            itemList.add(item);
            index++;
        }
        String declareNo = otherBusinessBO.getDeclareNo();
        tbBusiness.setCardSize(otherBusinessBO.getCarSize()).setNetWeight(otherBusinessBO.getNetWeight())
                .setOperator(otherBusinessBO.getOperator()).setOperateTime(otherBusinessBO.getOperateTime())
                .setNo(no).setGoodsName(tbGoods.getName()).setGoodsId(otherBusinessBO.getGoodsId())
                .setPayStep(tbGoods.getPayStep()).setDeclareNo(declareNo).setCardNo(otherBusinessBO.getCardNo());
        tbBusiness.setCreateTime(now).setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                .setItemPrice(price).setTotalMoney(price).setOwner(otherBusinessBO.getOwner());
        tbBusiness.setChinaCarNo(otherBusinessBO.getChinaCarNo());
        this.save(tbBusiness);
        Integer chinaCarPay = tbGoods.getChinaCarPay();
        Integer vietnamCarPay = tbGoods.getVietnamCarPay();
        String carBuseinssNo = DateUtil.format(now, "yyyyMMddHHmm");
        for (TbBusinessCar car : cars) {
            String carNo = car.getCarNo().trim().toUpperCase();
            String carPrefix = StrUtil.sub(carNo, 0, 1);
            List<TbBusinessCar> notOutRecords = tbBusinessCarService.findNotOutCar(carNo);
            if (notOutRecords.size() > 1) {
                throw new BusinessException(carNo + "有多个未出场记录，请先处理");
            }
            //最新一条记录
            TbBusinessCar db = tbBusinessCarService.findTheLastRecord(carNo);
            //不存在，或者已离场记录--->新建记录；
            if (db == null || db.getRealInTime() != null && db.getRealOutTime() != null) {
                db = new TbBusinessCar();
                db.setCreateTime(now).setPay(0).setNo(carBuseinssNo + RandomUtil.randomNumbers(4));
            }
            for (TbBusinessItem item : itemList) {
                checkOtherBusiness(item.getItemTypeId(), otherBusinessBO.getOperateTime(), tbBusiness.getId(), carNo);
            }
            if ((CAR_LIST.contains(carPrefix) && chinaCarPay == 0) || (!CAR_LIST.contains(carPrefix) && vietnamCarPay == 0)) {
                db.setPayType(TbBusinessCar.PayTypeEnum.FEE_TYPE.getType());
            }
            TbCar tbCar = tbCarService.findByCardNo(carNo);
            if (tbCar != null) {
                db.setCarCompany(tbCar.getCustomerName());
                if (!TbCar.CarTypeEnum.BUSINESS_CAR.getType().equals(tbCar.getCarType())) {
                    db.setPayType(TbBusinessCar.PayTypeEnum.FEE_TYPE.getType());
                }
            }
            db.setCarNo(carNo).setIsLock(0);
            db.setCarSize(car.getCarSize())
                    .setTimeUpdate(now).setCarType(car.getCarType())
                    .setNetWeight(car.getNetWeight())
                    .setCustomerId(customerId)
                    .setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
            tbBusinessCarService.saveOrUpdate(db);
            RelationBusinessCar relationBusinessCar = new RelationBusinessCar();
            relationBusinessCar.setBusinessId(tbBusiness.getId()).setBusinessCarId(db.getId());
            relationBusinessCarService.save(relationBusinessCar);
        }
        if (StrUtil.isNotEmpty(declareNo)) {
            TbDeclare declare = tbDeclareService.findByDeclareNo(declareNo);
            declare.setBusinessId(tbBusiness.getId());
            tbDeclareService.updateById(declare);
        }
        itemList.forEach(tbBusinessItem -> tbBusinessItem.setBusinessId(tbBusiness.getId()));
        tbBusinessItemService.saveBatch(itemList);

    }


    public List<TbBusiness> getOtherBusiness(SoMap startPage) {
        return tbBusinessMapper.getOtherBusiness(startPage);
    }

    public void editOtherBusiness(OtherBusinessBO otherBusinessBO) {
        String id = otherBusinessBO.getId();
        TbBusiness dbBusiness = this.getById(id);
        if (dbBusiness == null) {
            throw new BusinessException("记录不存在");
        }
        List<TbItem> tbItems = otherBusinessBO.getItems();
        if (tbItems.isEmpty()) {
            throw new BusinessException("请选择收费明细");
        }
        List<TbBusinessCar> cars = otherBusinessBO.getCars();
        if (cars.isEmpty()) {
            throw new BusinessException("作业车辆不能为空");
        }
        tbBusinessItemService.removeByBusinessId(id);
        Date now = new Date();
        List<RelationBusinessCar> relationBusinessCars = relationBusinessCarService.findByBusinessId(id);
        List<String> businessCarIds = cars.stream().filter(tbBusinessCar -> StrUtil.isNotEmpty(tbBusinessCar.getId()))
                .map(TbBusinessCar::getId).collect(Collectors.toList());
        List<String> removeIds = relationBusinessCars.stream()
                .filter(relationBusinessCar -> !businessCarIds.contains(relationBusinessCar.getBusinessCarId()))
                .map(RelationBusinessCar::getId)
                .collect(Collectors.toList());
        if (!removeIds.isEmpty()) {
            relationBusinessCarService.removeByIds(removeIds);
        }
        TbGoods tbGoods = tbGoodsService.getById(otherBusinessBO.getGoodsId());
        Integer chinaCarPay = tbGoods.getChinaCarPay();
        Integer vietnamCarPay = tbGoods.getVietnamCarPay();
        String carBuseinssNo = DateUtil.format(now, "yyyyMMddHHmm");
        BigDecimal price = new BigDecimal("0");
        List<TbBusinessItem> itemList = new ArrayList<>();
        String no = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4);
        int index = 1;
        for (TbItem tbItem : tbItems) {
            TbItem db = tbItemService.getById(tbItem.getId());
            TbBusinessItem item = new TbBusinessItem();
            int num = tbItem.getNum();
            TbItemType tbItemType = tbItemTypeService.getById(tbItem.getTypeId());
            BigDecimal itemTotalPrice = tbItem.getPrice().multiply(new BigDecimal(num));
            item.setNo(no + "0" + index).setPayTypeName(db.getPayTypeName()).setPayType(db.getPayType())
                    .setBusinessType(db.getBusinessType()).setTaxRate(NumberUtil.div(db.getTaxRate().doubleValue(), 100D, 2));
            item.setItemCode(db.getItemCode()).setNum(num + "").setItemId(db.getId()).setBusinessId(dbBusiness.getId())
                    .setItemName(db.getItemName()).setItemPrice(db.getPrice()).setRemark(tbItem.getRemark())
                    .setItemTypeId(tbItem.getTypeId()).setItemTypeName(tbItemType.getName())
                    .setUnit(db.getUnit()).setTotal(itemTotalPrice).setCreateTime(now);
            price = price.add(itemTotalPrice);
            itemList.add(item);
            index++;
        }
        dbBusiness.setItemPrice(price).setTotalMoney(price);
        tbBusinessItemService.saveBatch(itemList);
        for (TbBusinessCar tbBusinessCar : cars) {
            String businessCarId = tbBusinessCar.getId();
            String carNo = tbBusinessCar.getCarNo();
            for (TbBusinessItem item : itemList) {
                checkOtherBusiness(item.getItemTypeId(), otherBusinessBO.getOperateTime(), dbBusiness.getId(), carNo);
            }
            String carPrefix = StrUtil.sub(carNo, 0, 1);
            if (StrUtil.isNotEmpty(businessCarId)) {
                //原来已存在的
                TbBusinessCar dbBusinessCar = tbBusinessCarService.getById(businessCarId);
                //如果修改了车牌号
                if (!StrUtil.equals(carNo, dbBusiness.getCardNo())) {
                    //把关联删除掉，然后添加新的关联
                    relationBusinessCarService.removeByBusinessIdAndCarId(dbBusiness.getId(),businessCarId);
                    TbBusinessCar otherCar = tbBusinessCarService.findTheLastRecord(carNo);
                    if (otherCar == null ||//不存在或者已离场===>新建
                            (otherCar.getRealInTime() != null && otherCar.getRealOutTime() != null)) {
                        otherCar = new TbBusinessCar();
                        otherCar.setCreateTime(now).setPay(0).setNo(carBuseinssNo + RandomUtil.randomNumbers(4))
                                .setCarNo(carNo).setCarType(tbBusinessCar.getCarType()).setCarSize(tbBusinessCar.getCarSize())
                                .setNetWeight(tbBusinessCar.getNetWeight()).setCustomerId(dbBusiness.getCustomerId())
                                .setTimeUpdate(now).setIsLock(0);
                        if ((CAR_LIST.contains(carPrefix) && chinaCarPay == 0) || (!CAR_LIST.contains(carPrefix) && vietnamCarPay == 0)) {
                            otherCar.setPayType(TbBusinessCar.PayTypeEnum.FEE_TYPE.getType());
                        }
                        tbBusinessCarService.save(otherCar);
                    } else {
                        List<TbBusiness> tbBusinessList = this.findOtherBusinessByCarId(businessCarId);
                        if (tbBusinessList.size() == 1&&dbBusinessCar.getRealInTime()==null) {
                            tbBusinessCarService.removeById(businessCarId);
                        }
                    }
                    RelationBusinessCar relationBusinessCar = new RelationBusinessCar();
                    relationBusinessCar.setBusinessId(dbBusiness.getId()).setBusinessCarId(otherCar.getId());
                    relationBusinessCarService.save(relationBusinessCar);
                } else {
                    dbBusinessCar.setNetWeight(tbBusinessCar.getNetWeight()).setCarType(tbBusinessCar.getCarType())
                            .setCarSize(tbBusinessCar.getCarSize());
                    tbBusinessCarService.updateById(dbBusinessCar);
                }
            } else {
                TbBusinessCar checkCar = tbBusinessCarService.findTheLastRecord(carNo);
                if (checkCar == null ||
                        (checkCar.getRealInTime() != null && checkCar.getRealOutTime() != null)) {
                    checkCar = new TbBusinessCar();
                    checkCar.setCreateTime(now).setPay(0).setNo(carBuseinssNo + RandomUtil.randomNumbers(4));
                }
                checkCar.setCarNo(carNo).setCarType(tbBusinessCar.getCarType()).setCarSize(tbBusinessCar.getCarSize())
                        .setNetWeight(tbBusinessCar.getNetWeight()).setCustomerId(dbBusiness.getCustomerId())
                        .setTimeUpdate(now).setIsLock(0);
                if ((CAR_LIST.contains(carPrefix) && chinaCarPay == 0) || (!CAR_LIST.contains(carPrefix) && vietnamCarPay == 0)) {
                    checkCar.setPayType(TbBusinessCar.PayTypeEnum.FEE_TYPE.getType());
                }
                tbBusinessCarService.saveOrUpdate(checkCar);
                RelationBusinessCar relationBusinessCar = new RelationBusinessCar();
                relationBusinessCar.setBusinessId(dbBusiness.getId()).setBusinessCarId(checkCar.getId());
                relationBusinessCarService.save(relationBusinessCar);
            }
        }
        if (!StrUtil.equals(dbBusiness.getGoodsId(), otherBusinessBO.getGoodsId())) {
            dbBusiness.setGoodsId(otherBusinessBO.getGoodsId())
                    .setGoodsName(tbGoods.getName()).setPayStep(tbGoods.getPayStep());
        }
        String declareNo = otherBusinessBO.getDeclareNo();
        if (!StrUtil.equals(declareNo, dbBusiness.getDeclareNo())) {
            tbDeclareService.rebackDeclareNo(dbBusiness.getDeclareNo());
           TbDeclare tbDeclare= tbDeclareService.findByDeclareNo(declareNo);
           tbDeclare.setBusinessId(dbBusiness.getId());
           tbDeclareService.updateById(tbDeclare);
        }
        dbBusiness.setCardSize(otherBusinessBO.getCarSize()).setNetWeight(otherBusinessBO.getNetWeight())
                .setOperator(otherBusinessBO.getOperator()).setOperateTime(otherBusinessBO.getOperateTime())
                .setNo(no).setGoodsId(otherBusinessBO.getGoodsId()).setOwner(otherBusinessBO.getOwner())
                .setDeclareNo(declareNo).setCardNo(otherBusinessBO.getCardNo());
        dbBusiness.setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                .setItemPrice(price).setTotalMoney(price);
        dbBusiness.setChinaCarNo(otherBusinessBO.getChinaCarNo());
        this.updateById(dbBusiness);
    }

    public void bindOtherBusinessCar(String businessId, List<String> businessCarIdList) {
        TbBusiness tbBusiness = this.getById(businessId);
        relationBusinessCarService.removeByBusinessId(businessId);
        List<TbBusinessCar> carList = tbBusinessCarService.listByIds(businessCarIdList);
        String chinaCarNo = carList.stream().filter(tbBusinessCar -> {
            String carNo = tbBusinessCar.getCarNo();
            String carStr = StrUtil.sub(carNo, 0, 1);
            return CAR_LIST.contains(carStr);
        }).map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
        String yueCarNo = carList.stream().filter(tbBusinessCar -> {
            String carNo = tbBusinessCar.getCarNo();
            String carStr = StrUtil.sub(carNo, 0, 1);
            return !CAR_LIST.contains(carStr);
        }).map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
        tbBusiness.setChinaCarNo(chinaCarNo);
        tbBusiness.setCardNo(yueCarNo);
        this.updateById(tbBusiness);
        businessCarIdList.forEach(businessCarId -> {
            RelationBusinessCar relationBusinessCar = new RelationBusinessCar();
            relationBusinessCar.setBusinessCarId(businessCarId).setBusinessId(businessId);
            relationBusinessCarService.save(relationBusinessCar);
        });
    }

    private void checkOtherBusiness(String itemTypeId, String operateTimeStr, String businessId, String carNo) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        TbBusinessSort sort = tbBusinessSortService.findByItemTypeId(itemTypeId);
        if (sort==null){
            return;
        }
        List<TbBusinessSort> sorts = tbBusinessSortService.findByGroupId(sort.getGroupId());
        LocalDateTime operateTime = LocalDateTime.parse(operateTimeStr, formatter);
        int i = 0;
        for (TbBusinessSort tbBusinessSort : sorts) {
            if (i == 0 && StrUtil.equals(tbBusinessSort.getTypeId(), itemTypeId) && sorts.size() > 1) {
                TbBusinessSort afterItem = sorts.get(i + 1);
                String typeId = afterItem.getTypeId();
                Integer interval = afterItem.getIntervalTime();
                LocalDateTime endTime = operateTime.plusMinutes(interval);
                if (afterItem.getIntervalTime() > 0) {
                    int count = this.checkCarBusinessType(typeId, carNo, endTime.format(formatter), 1);
                    if (count > 0) {
                        throw new BusinessException("车辆:[" + carNo + "]" + tbBusinessSort.getTypeName() + "后" + afterItem.getIntervalTime() + "分钟才可以执行" + afterItem.getTypeName());
                    }
                }
            }
            if (i > 0 && StrUtil.equals(tbBusinessSort.getTypeId(), itemTypeId)) {
                TbBusinessSort beforeItem = sorts.get(i - 1);
                String typeId = beforeItem.getTypeId();
                Integer interval = tbBusinessSort.getIntervalTime();
                LocalDateTime endTime = operateTime.minusMinutes(interval);
                if (tbBusinessSort.getIntervalTime() > 0) {
                    int count = this.checkCarBusinessType(typeId, carNo, endTime.format(formatter), 0);
                    if (count > 0) {
                        throw new BusinessException("车辆:[" + carNo + "]" + beforeItem.getTypeName() + "后" + tbBusinessSort.getIntervalTime() + "分钟才可以执行" + tbBusinessSort.getTypeName());
                    }
                }
            }
            Integer singleIntervalTime = tbBusinessSort.getSingleIntervalTime();
            String timeStart = operateTime.minusHours(singleIntervalTime).format(formatter);
            String timeEnd = operateTime.plusHours(singleIntervalTime).format(formatter);
            int count = this.checkCarBusinessType(itemTypeId, carNo, timeStart, timeEnd, businessId);
            if (count > 0) {
                throw new BusinessException("车辆:[" + carNo + "]" + singleIntervalTime + "小时内已有相同作业");
            }
            i++;
        }
    }


    public TbBusiness findByDeclareNo(String declareNo) {
        QueryWrapper<TbBusiness>ew=new QueryWrapper<>();
        ew.eq("declare_no",declareNo).orderByDesc("id");
        List<TbBusiness>list=this.list(ew);
        return  list.isEmpty()?null:list.get(0);
    }
}
