package com.pj.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
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.pj.api.bo.InOutRecordBO;
import com.pj.api.bo.OtherBusinessBO;
import com.pj.api.wx.bo.MsgDataBO;
import com.pj.api.wx.service.WxService;
import com.pj.constants.UserTypeEnum;
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_type_item.RelationTypeItem;
import com.pj.project.relation_type_item.RelationTypeItemService;
import com.pj.project.tb_account.TbAccount;
import com.pj.project.tb_account.TbAccountService;
import com.pj.project.tb_business.CarDisincle;
import com.pj.project.tb_business.TbBusiness;
import com.pj.project.tb_business.TbBusinessService;
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_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_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_discount.TbDiscount;
import com.pj.project.tb_discount.TbDiscountService;
import com.pj.project.tb_disinfect.TbDisinfect;
import com.pj.project.tb_disinfect.TbDisinfectService;
import com.pj.project.tb_district.TbDistrict;
import com.pj.project.tb_district.TbDistrictService;
import com.pj.project.tb_item.TbItem;
import com.pj.project.tb_item_type.TbItemType;
import com.pj.project.tb_item_type.TbItemTypeService;
import com.pj.project.tb_pass_record.TbPassRecord;
import com.pj.project.tb_pass_record.TbPassRecordService;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.project4sp.admin.SpAdminService;
import com.pj.project4sp.global.BusinessException;
import com.pj.utils.cache.RedisUtil;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class ApiService {

    @Resource
    TbCostomerService tbCostomerService;
    @Resource
    @Lazy
    TbBusinessService tbBusinessService;
    @Resource
    TbPassRecordService tbPassRecordService;
    @Resource
    @Lazy
    TbBusinessCarService tbBusinessCarService;
    @Resource
    private TbDeclareService tbDeclareService;
    @Resource
    @Lazy
    private TbDisinfectService tbDisinfectService;
    @Resource
    private TbAccountService accountService;
    @Resource
    private TbDiscountService tbDiscountService;
    @Resource
    private TbBusinessItemService tbBusinessItemService;
    @Resource
    private SpAdminService spAdminService;
    @Resource
    private WxService wxService;
    @Resource
    private WxConfig wxConfig;
    @Resource
    private MyConfig myConfig;
    @Resource
    private TbCarService tbCarService;
    @Resource
    private RelationTypeItemService relationTypeItemService;

    @Resource
    private TbItemTypeService tbItemTypeService;

    @Resource
    private TbBusinessSortService tbBusinessSortService;

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


    public List<InOutRecordBO> getInOutRecord(SoMap so) {
        List<TbPassRecord> passRecords = tbPassRecordService.getList(so);
        List<InOutRecordBO> recordList = new ArrayList<>();
        for (TbPassRecord passRecord : passRecords) {
            InOutRecordBO record = new InOutRecordBO();
            BeanUtil.copyProperties(passRecord, record);
            TbCostomer costomer = tbCostomerService.getById(passRecord.getCustomerId());
            record.setCustomerContact(costomer.getPhone()).setDutyPeople(costomer.getDutyPeople());
            recordList.add(record);
        }
        return recordList;
    }

    public List<TbCostomer> getCustomerList(SoMap so) {
        List<TbCostomer> list = tbCostomerService.getList(so);
        return list;
    }

    public void confirmCustomer(Long customerId, String judgeContent) {
        TbCostomer costomer = tbCostomerService.getById(customerId);
        if (costomer != null && costomer.getJudgeStatus() == 1) {
            tbCostomerService.judge(customerId + "", 2, judgeContent);
        }
    }

    public Set<TbBusinessCar> searchPartCar(String carNo) {
        if (StrUtil.isEmpty(carNo) || StrUtil.length(carNo) < 3) {
            return new HashSet<>();
        }
        List<TbBusinessCar> list = tbBusinessCarService.searchPartCar(carNo);
        list = list.stream().filter(tbBusinessCar -> {
            String businessId = tbBusinessCar.getBusinessId();
            if (StrUtil.isEmpty(businessId)) {
                return false;
            }
            TbBusiness tbBusiness = tbBusinessService.getById(businessId);
            return tbBusiness.getAdminConfirmInput() == 1;
        }).collect(Collectors.toList());

        List<TbBusinessCar> otherBusinessCarList = tbBusinessCarService.searchOtherBusinessCar(carNo);
        otherBusinessCarList = otherBusinessCarList.stream().filter(tbBusinessCar -> {
            String businessCarId = tbBusinessCar.getId();
            List<TbBusiness> businesses = tbBusinessService.findOtherBusinessByCarId(businessCarId);
            return businesses.stream().anyMatch(tbBusiness -> tbBusiness.getPayMoney().doubleValue() < tbBusiness.getTotalMoney().doubleValue()
                    && (((TbItemType.PayStep.BEFORE_CONFIRM.getCode().equals(tbBusiness.getPayStep()) && tbBusiness.getAdminConfirmInput() >= 0)
                    || (TbItemType.PayStep.AFTER_CONFIRM.getCode().equals(tbBusiness.getPayStep()) && tbBusiness.getAdminConfirmInput() == 1))
            ));
        }).collect(Collectors.toList());


        List<TbBusinessCar> cars = tbBusinessCarService.findTheNoBusinessCar(carNo);
        //过滤掉不用缴费的车
        list.addAll(cars);
        list.addAll(otherBusinessCarList);
        return new HashSet<>(list);
    }

    public void confirm(List<String> ids) {
        tbBusinessService.confirm(ids);
    }

    public Map<String, Object> getBusinessMoney(String carId, String state) {
        return tbBusinessService.getBusinessMoney(carId, state);
    }

    public Map<String, Object> getPartCarByChannel(String channel) {
        Map<String, Object> result = new HashMap<>();
        String carNo = RedisUtil.get(channel);
        if (StrUtil.isEmpty(carNo)) {
            return result;
        }
        TbBusinessCar tbBusinessCar = tbBusinessCarService.findTheLastRecord(carNo);
        if (tbBusinessCar == null) {
            return result;
        }
        Date now = new Date();
        Date startTime = tbBusinessCar.getRealInTime();
        if (tbBusinessCar.getPayTime() != null) {
            startTime = tbBusinessCar.getPayTime();
        }
        BigDecimal price = tbBusinessService.calculationPartMoney(startTime, now);
        Map<String, Object> car = new HashMap<>();
        car.put("id", tbBusinessCar.getId());
        car.put("carNo", tbBusinessCar.getCarNo());
        car.put("price", price);
        result.put("total", price);
        result.put("cars", Collections.singleton(car));
        return result;
    }

    public void addDeclare(TbDeclare tbDeclare) {
        if (StpUserUtil.isLogin() && !StrUtil.equals(UserTypeEnum.PLATFORM_ADMIN.getCustomerId(), StpUserUtil.getCustomerId())) {
            String currentCustomerId = StpUserUtil.getCustomerId();
            tbDeclare.setCustomerId(currentCustomerId);
        }
        TbCostomer tbCostomer = tbCostomerService.getById(tbDeclare.getCustomerId());
        tbDeclare.setCustomerName(tbCostomer.getName());
        String chinaCarNo = tbDeclare.getChinaCarNo();
        if (StrUtil.isNotEmpty(chinaCarNo)) {
            chinaCarNo = chinaCarNo.toUpperCase();
            tbDeclare.setChinaCarNo(chinaCarNo);
        }
        String carNo = tbDeclare.getCarNo();
        if (StrUtil.isNotEmpty(carNo)) {
            carNo = carNo.toUpperCase();
            tbDeclare.setCarNo(carNo);
        }

        String nowStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        tbDeclare.setCreateTime(new Date()).setDeclareNo(nowStr + RandomUtil.randomNumbers(6));
        tbDeclareService.save(tbDeclare);
    }

    public void addDisinfect(TbDisinfect tbDisinfect) {
        if (StpUserUtil.isLogin() && !StrUtil.equals(UserTypeEnum.PLATFORM_ADMIN.getCustomerId(), StpUserUtil.getCustomerId())) {
            String currentCustomerId = StpUserUtil.getCustomerId();
            tbDisinfect.setCustomerId(currentCustomerId);
        }
        TbCostomer tbCostomer = tbCostomerService.getById(tbDisinfect.getCustomerId());
        tbDisinfect.setCustomerName(tbCostomer.getName()).setApplyUnit(tbCostomer.getName());
        String nowStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        tbDisinfect.setCode(nowStr + RandomUtil.randomNumbers(6)).setApplyTime(DateUtil.now());
        tbDisinfectService.save(tbDisinfect);
    }

    public List<TbDeclare> getDeclareList(SoMap so) {
        return tbDeclareService.getList(so);
    }

    public TbAccount getAccountInfo(String customerId) {
        return accountService.getByCustomerId(customerId);
    }

    public List<TbDiscount> getDiscountInfo(SoMap so) {
        return tbDiscountService.getList(so);
    }

    public TbBusinessItem getBusinessItem(String id) {
        TbBusinessItem item = tbBusinessItemService.getById(id);
        TbBusiness business = tbBusinessService.getById(item.getBusinessId());
        item.setCardNo(business.getCardNo()).setChinaCarNo(business.getChinaCarNo()).setGoodsName(business.getGoodsName());
        return item;
    }

    public AjaxJson pickBusinessItem(String openid, long id) {
        TbBusinessItem tbBusinessItem = tbBusinessItemService.getById(id);
        if (tbBusinessItem == null) {
            return AjaxJson.getError("业务项目或已被删除");
        }
        SpAdmin spAdmin = spAdminService.findByOpenid(openid);
        if (spAdmin == null) {
            return AjaxJson.getError("用户已被删除或解绑");
        }
        if (tbBusinessItem.getPick() == 1) {
            return AjaxJson.getError("您慢了一步，其他用户已接单");
        }
        String customerId = spAdmin.getCustomerId();
        TbCostomer tbCostomer = tbCostomerService.getById(customerId);
        tbBusinessItem.setPick(1).setPickTime(new Date()).setPickCustomerId(tbCostomer.getId()).setPickCustomerName(tbCostomer.getName());
        tbBusinessItemService.updateById(tbBusinessItem);
        //todo 通知录入人员 已接单
        List<SpAdmin> spAdminList = spAdminService.findByCustomerId(UserTypeEnum.PLATFORM_ADMIN.getCustomerId());
        TbBusiness tbBusiness = tbBusinessService.getById(tbBusinessItem.getBusinessId());
        MsgDataBO msgDataBO = new MsgDataBO("订单号：" + tbBusinessItem.getNo(), tbCostomer.getName(), DateUtil.now(), tbBusiness.getGoodsName() + "(" + tbBusinessItem.getItemTypeName() + tbBusinessItem.getItemName() + ")");
        spAdminList.stream().filter(admin -> StrUtil.isNotEmpty(admin.getOpenid())).forEach(admin -> {
            String detailUrl = myConfig.getWebDomain() + "/pages/business-order/business-item?id=" + tbBusiness.getId() + "&itemId=" + tbBusinessItem.getId() + "&openid=" + openid;
            log.info("admin confirm business:[{}]", detailUrl);
            wxService.sendTemplateMsg(wxConfig.getBusinessPickTemplate(), admin.getOpenid(), msgDataBO, detailUrl);
        });
        return AjaxJson.getSuccess();
    }

    public void confirmBusinessItem(long id) {
        tbBusinessItemService.confirmBusinessItem(id);
    }

    public List<TbBusinessItem> getPartnerBusinessItem(SoMap startPage) {
        List<TbBusinessItem> list = tbBusinessItemService.getList(startPage);
        list.parallelStream().forEach(tbBusinessItem -> {
            TbBusiness tbBusiness = tbBusinessService.getById(tbBusinessItem.getBusinessId());
            if (TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(tbBusiness.getBusinessType())) {
                TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(tbBusiness.getBusinessCarId());
                tbBusinessItem.setCardNo(tbBusinessCar.getCarNo());
            } else {
                List<TbBusinessCar> cars = tbBusinessCarService.findByBusinessId(tbBusiness.getId());
                String carStr = cars.stream().map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
                tbBusinessItem.setCardNo(carStr);
            }
        });
        return list;
    }

    public void addCarDisinfect(OtherBusinessBO otherBusinessBO) {
        List<TbItem> tbItems = otherBusinessBO.getItems();
        if (tbItems.isEmpty()) {
            throw new BusinessException("请选择明细");
        }
        String carNo = otherBusinessBO.getCarNo().trim().toUpperCase();
        checkOtherBusiness(otherBusinessBO, tbItems, carNo);
        TbBusinessCar db = tbBusinessCarService.findNotOutCar(carNo);
        String customerId = otherBusinessBO.getCustomerId();
        TbItemType tbItemType = tbItemTypeService.getById(otherBusinessBO.getItemTypeId());
        TbCar tbCar = tbCarService.findByCardNo(carNo);
        if (db == null) {
            db = tbBusinessCarService.findNotInCar(carNo);
            if (db == null) {
                db = new TbBusinessCar();
            }
        } else {
            db.setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode());
            tbBusinessCarService.updateById(db);
        }
        db.setPay(0).setCarNo(carNo).setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                .setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                .setIsLock(0).setCarCompany(tbCar != null ? tbCar.getCustomerName() : "临时");
        db.setCarSize(otherBusinessBO.getCarSize()).setTimeUpdate(new Date()).setCustomerId(customerId)
                .setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
        tbBusinessCarService.saveOrUpdate(db);
        TbBusiness tbBusiness = new TbBusiness();
        tbBusiness.setCreateBy(StpUserUtil.getAdmin().getName());
        tbBusiness.setBusinessCarId(db.getId()).setPayStep(tbItemType.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) {
            TbBusinessItem item = new TbBusinessItem();
            int num = tbItem.getNum();
            RelationTypeItem relationTypeItem = relationTypeItemService.findByTypeIdAndItemId(otherBusinessBO.getItemTypeId(), tbItem.getId());
            BigDecimal itemTotalPrice = tbItem.getPrice().multiply(new BigDecimal(num));
            item.setNo(no + "0" + index).setPayTypeName(tbItem.getPayTypeName()).setPayType(tbItem.getPayType())
                    .setBusinessType(tbItem.getBusinessType()).setTaxRate(NumberUtil.div(tbItem.getTaxRate().doubleValue(), 100D, 2));
            item.setItemCode(tbItem.getItemCode()).setNum(num + "").setItemId(tbItem.getId()).setItemCode(tbItem.getItemCode())
                    .setItemName(tbItem.getItemName()).setItemPrice(tbItem.getPrice()).setRemark(tbItem.getRemark())
                    .setItemTypeId(otherBusinessBO.getItemTypeId()).setItemTypeName(relationTypeItem.getTypeName())
                    .setUnit(tbItem.getUnit()).setTotal(itemTotalPrice).setCreateTime(new Date());
            price = price.add(itemTotalPrice);
            itemList.add(item);
            index++;
        }
        tbBusiness.setCardSize(otherBusinessBO.getCarSize()).setNetWeight(otherBusinessBO.getCarWeight())
                .setOperator(otherBusinessBO.getOperator()).setOperateTime(otherBusinessBO.getOperateTime())
                .setNo(no).setGoodsName(otherBusinessBO.getCarType()).setItemTypeId(otherBusinessBO.getItemTypeId())
                .setCreateTime(new Date()).setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                .setItemTypeName(tbItemType.getName())
                .setItemPrice(price).setTotalMoney(price);
        String prefix = carNo.substring(0, 1);
        if (CAR_LIST.contains(prefix)) {
            tbBusiness.setChinaCarNo(carNo);
        } else {
            tbBusiness.setCardNo(carNo);
        }
        tbBusinessService.save(tbBusiness);
        itemList.forEach(tbBusinessItem -> tbBusinessItem.setBusinessId(tbBusiness.getId()));
        tbBusinessItemService.saveBatch(itemList);
    }

    @Deprecated
    public void editCarDisinfect(CarDisincle carDisincle, String itemJson, String type) {
        String carId = carDisincle.getBusinessCarId();
        TbBusinessCar businessCar = tbBusinessCarService.getById(carId);
        if (businessCar == null) {
            throw new BusinessException("数据不存在");
        }
        List<TbItem> tbItems = JSONUtil.toList(itemJson, TbItem.class);

    }

    public void editOtherBusiness(OtherBusinessBO otherBusinessBO) {
        List<TbItem> tbItems = otherBusinessBO.getItems();
        if (tbItems.isEmpty()) {
            throw new BusinessException("请选择明细");
        }
        TbItemType tbItemType = tbItemTypeService.getById(otherBusinessBO.getItemTypeId());
        String businessId = otherBusinessBO.getId();
        tbBusinessItemService.removeByBusinessId(businessId);
        String carNo = otherBusinessBO.getCarNo();
        String customerId = otherBusinessBO.getCustomerId();
        TbCostomer tbCostomer = tbCostomerService.getById(customerId);
        TbBusiness tbBusiness = tbBusinessService.getById(businessId);
        checkOtherBusiness(otherBusinessBO, tbItems, carNo);
        tbBusiness.setOperateTime(otherBusinessBO.getOperateTime())
                .setOperator(otherBusinessBO.getOperator())
                .setPayStep(tbItemType.getPayStep()).setItemTypeName(tbItemType.getName())
                .setCardSize(otherBusinessBO.getCarSize()).setItemTypeId(tbItemType.getId())
                .setCustomerId(customerId).setNetWeight(otherBusinessBO.getCarWeight())
                .setGoodsName(otherBusinessBO.getCarType())
                .setCustomerName(tbCostomer.getName());
        String prefix = carNo.substring(0, 1);
        if (CAR_LIST.contains(prefix)) {
            tbBusiness.setChinaCarNo(carNo);
        } else {
            tbBusiness.setCardNo(carNo);
        }
        String no = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4);
        TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(tbBusiness.getBusinessCarId());
        TbBusinessCar otherCar = tbBusinessCarService.searchOtherBusinessCarNotOut(carNo);
        if (otherCar != null) {
            List<TbBusiness> checkList = tbBusinessService.findOtherBusinessByCarId(tbBusiness.getBusinessCarId());
            if (checkList.size() == 1) {
                tbBusinessCarService.removeById(tbBusiness.getBusinessCarId());
            }
            tbBusiness.setBusinessCarId(otherCar.getId());
        } else {
            tbBusinessCar.setCarSize(otherBusinessBO.getCarSize()).setBusinessType(TbBusiness.BusinessType.CAR_DISINCLE.getCode())
                    .setCustomerId(otherBusinessBO.getCustomerId()).setCarNo(carNo)
                    .setTimeUpdate(new Date());
            tbBusinessCarService.updateById(tbBusinessCar);
        }

        int index = 1;
        BigDecimal price = new BigDecimal("0");
        List<TbBusinessItem> itemList = new ArrayList<>();
        for (TbItem tbItem : tbItems) {
            TbBusinessItem item = new TbBusinessItem();
            int num = tbItem.getNum();
            RelationTypeItem relationTypeItem = relationTypeItemService.findByTypeIdAndItemId(otherBusinessBO.getItemTypeId(), tbItem.getId());
            BigDecimal itemTotalPrice = tbItem.getPrice().multiply(new BigDecimal(num));
            item.setNo(no + "0" + index).setPayTypeName(tbItem.getPayTypeName())
                    .setPayType(tbItem.getPayType())
                    .setBusinessType(tbItem.getBusinessType())
                    .setTaxRate(NumberUtil.div(tbItem.getTaxRate().doubleValue(), 100D, 2))
                    .setItemCode(tbItem.getItemCode()).setNum(num + "")
                    .setItemId(tbItem.getId()).setItemCode(tbItem.getItemCode())
                    .setItemName(tbItem.getItemName()).setItemPrice(tbItem.getPrice())
                    .setRemark(tbItem.getRemark())
                    .setItemTypeId(otherBusinessBO.getItemTypeId())
                    .setItemTypeName(relationTypeItem.getTypeName()).setBusinessId(otherBusinessBO.getId())
                    .setUnit(tbItem.getUnit()).setTotal(itemTotalPrice).setCreateTime(new Date());
            price = price.add(itemTotalPrice);
            itemList.add(item);
            index++;
        }
        tbBusiness.setItemPrice(price);
        tbBusinessItemService.saveBatch(itemList);
        tbBusinessService.updateById(tbBusiness);


    }

    private void checkOtherBusiness(OtherBusinessBO otherBusinessBO, List<TbItem> tbItems, String carNo) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String itemTypeId = otherBusinessBO.getItemTypeId();
        TbBusinessSort sort = tbBusinessSortService.findByItemTypeId(itemTypeId);
        List<TbBusinessSort> sorts = tbBusinessSortService.findByGroupId(sort.getGroupId());
        LocalDateTime operateTime = LocalDateTime.parse(otherBusinessBO.getOperateTime(), formatter);
        int i = 0;
        for (TbBusinessSort tbBusinessSort : sorts) {
            if (i == 0 && StrUtil.equals(tbBusinessSort.getTypeId(), otherBusinessBO.getItemTypeId()) && 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 = tbBusinessService.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(), otherBusinessBO.getItemTypeId())) {
                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 = tbBusinessService.checkCarBusinessType(typeId, carNo, endTime.format(formatter), 0);
                    if (count > 0) {
                        throw new BusinessException("车辆:[" + carNo + "]" + beforeItem.getTypeName() + "后" + tbBusinessSort.getIntervalTime() + "分钟才可以执行" + tbBusinessSort.getTypeName());
                    }
                }
            }
            String typeId = otherBusinessBO.getItemTypeId();
            Integer singleIntervalTime = tbBusinessSort.getSingleIntervalTime();
            String timeStart = operateTime.minusHours(singleIntervalTime).format(formatter);
            String businessId = otherBusinessBO.getId();
            String timeEnd = operateTime.plusHours(singleIntervalTime).format(formatter);
            int count = tbBusinessService.checkCarBusinessType(typeId, carNo, timeStart, timeEnd, businessId);
            if (count > 0) {
                throw new BusinessException("车辆:[" + carNo + "]" + singleIntervalTime + "小时内已有相同作业");
            }
            i++;
        }
    }

}
