package com.pj.project.tb_business;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
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.bean.BeanUtil;
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.OtherBusinessBO;
import com.pj.api.bo.OtherBusinessEditBO;
import com.pj.api.open.ResultJson;
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.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.TbNoticesMapper;
import com.pj.project.tb_notices.TbNoticesService;
import com.pj.project.tb_pass_record.TbPassRecord;
import com.pj.project.tb_pass_record.TbPassRecordService;
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.project4sp.role.SpRoleUtil;
import com.pj.project4sp.role4permission.SpRolePermissionService;
import com.pj.utils.so.SoMap;
import org.aspectj.weaver.loadtime.Aj;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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
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;


    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 && TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(db.getBusinessType())) {
                throw new BusinessException("该车存在其他业务");
            }
            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()).setBusinessType(TbBusiness.BusinessType.HOLD_CAR.getCode());
            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));
        }
        yueCar.setBusinessType(TbBusiness.BusinessType.HOLD_CAR.getCode());
        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.findByBusinessId(business.getId());
            if (TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(business.getBusinessType())) {
                cars = Collections.singletonList(tbBusinessCarService.getById(business.getBusinessCarId()));
            }
            String carNoStr = cars.stream().map(TbBusinessCar::getCarNo).collect(Collectors.joining("、"));
            storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已确认" + DateUtil.now() + "。");
            List<TbBusinessItem> items = tbBusinessItemService.findByBusinessId(id);
            Integer bigBusinessType = business.getBusinessType();
            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 carId, String state) {
        Map<String, Object> result = new HashMap<>();
        TbBusinessCar car = tbBusinessCarService.getById(carId);
        String businessId = car.getBusinessId();
        Integer businessType = car.getBusinessType();
        result.put("type", businessType);
        result.put("showPay", true);
        List<TbBusinessCar> cars = new ArrayList<>();
        List<TbBusinessItem> items = new ArrayList<>();
        cars.add(car);
        //其他业务
        String itemTypeId = "";
        if (TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(businessType)) {
            List<TbBusiness> businesses = this.findOtherBusinessByCarId(carId);
            businesses = businesses.stream()
                    .filter(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<String> businessIdList = businesses.stream().map(TbBusiness::getId).collect(Collectors.toList());
            if (!businessIdList.isEmpty()) {
                itemTypeId = businesses.get(0).getItemTypeId();
                items = tbBusinessItemService.findByBusinessIdList(businessIdList);
                businessId = String.join(",", businessIdList);
            }
        } else if (TbBusiness.BusinessType.HOLD_CAR.getCode().equals(businessType)) {
            cars = tbBusinessCarService.findByBusinessId(businessId);
            TbBusiness tbBusiness = this.getById(businessId);
            if (tbBusiness.getPayStatus() != TbBusiness.PayStatus.HAS_PAY_CONFIRM.getCode()) {
                items = tbBusinessItemService.findByBusinessId(businessId);
            }
        }
        result.put("businessId", businessId);
        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) && TbBusiness.BusinessType.HOLD_CAR.getCode().equals(businessType)) {
                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());
            TbCar tbCar = tbCarService.findByCardNo(tbBusinessCar.getCarNo());
            if (tbCar != null && !TbCar.CarTypeEnum.BUSINESS_CAR.getType().equals(tbCar.getCarType())) {
                carMap.put("price", 0);
            }
            carsList.add(carMap);
        }
        result.put("carList", carsList);
        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()));
            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);
        }
        result.put("itemsPrice", itemsPrice);
        result.put("itemList", itemList);
        if (TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(businessType) && StrUtil.isNotEmpty(itemTypeId)) {
            TbBusinessSort tbBusinessSort = tbBusinessSortService.findByItemTypeId(itemTypeId);
            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);
                }
            }
        }

        return result;
    }

    public List<TbBusiness> findOtherBusinessByCarId(String businessCarId) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("business_car_id", businessCarId);
        return list(ew);
    }

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


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

    public OtherBusinessEditBO getOtherBusinessById(String id) {
        TbBusiness tbBusiness = this.getById(id);
        List<TbBusinessItem> tbBusinessItems = tbBusinessItemService.findByBusinessId(id);
        TbBusinessCar car = tbBusinessCarService.getById(tbBusiness.getBusinessCarId());
        OtherBusinessEditBO otherBusinessBO = new OtherBusinessEditBO();
        otherBusinessBO.setId(tbBusiness.getId()).setOperator(tbBusiness.getOperator()).setOperateTime(tbBusiness.getOperateTime());
        otherBusinessBO.setCustomerId(tbBusiness.getCustomerId());
        otherBusinessBO.setCarNo(car.getCarNo()).setCarWeight(tbBusiness.getNetWeight())
                .setCarSize(tbBusiness.getCardSize()).setCarType(tbBusiness.getGoodsName())
                .setItemTypeId(tbBusiness.getItemTypeId());
        otherBusinessBO.setItems(tbBusinessItems);
        return otherBusinessBO;
    }

    public void deleteOtherBusiness(String id) {
        TbBusiness db = super.getById(id);
        TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(db.getBusinessCarId());
        if (tbBusinessCar == null || tbBusinessCar.getRealInTime() == null) {
            List<TbBusiness> businesses = this.findOtherBusinessByCarId(db.getBusinessCarId());
            if (businesses.size() == 1) {
                tbBusinessCarService.removeById(db.getBusinessCarId());
            }
        }
        this.removeById(id);
        tbBusinessItemService.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, String inChannel, Date realInTime, String outChannel, Date realOutTime, String remark) {
        TbBusiness db = this.getById(id);
        if (db == null) {
            throw new BusinessException("业务不存在");
        }
        db.setPayStatus(3).setPayMoney(db.getItemPrice());
        this.updateById(db);
        TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(db.getBusinessCarId());
        if (realInTime != null && realOutTime != null) {
            BigDecimal price = calculationPartMoney(realInTime, realOutTime);
            tbBusinessCar.setMoney(price).setPay(1);
        }
        tbBusinessCar.setInChannel(inChannel)
                .setOutChannel(outChannel)
                .setRealOutTime(realOutTime)
                .setRealInTime(realInTime);
        tbBusinessCarService.updateById(tbBusinessCar);
        List<TbBusinessItem> items = tbBusinessItemService.findByBusinessId(id);
        items.forEach(tbBusinessItem -> tbBusinessItem.setPayStatus(1).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 bindCar(String id, String businessCarId) {
        TbBusiness db = this.getById(id);
        if (!TbBusiness.BusinessType.CAR_DISINCLE.getCode().equals(db.getBusinessType())) {
            throw new BusinessException("业务类型不正确");
        }
        TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(businessCarId);
        if (tbBusinessCar == null) {
            throw new BusinessException("车辆记录不存在");
        }
        List<TbBusiness> list = this.findOtherBusinessByCarId(businessCarId);
        int count = (int) list.stream().filter(tbBusiness -> !tbBusiness.getId().equals(id) && tbBusiness.getItemTypeId().equals(db.getItemTypeId())).count();
        if (count>0){
            throw new BusinessException("同一车辆请勿绑定多个相同业务");
        }
        String carNo = tbBusinessCar.getCarNo();
        String carNoStr = StrUtil.sub(carNo, 0, 1);
        //中国车
        if (CAR_LIST.contains(carNoStr)) {
            db.setChinaCarNo(carNo);
        } else {
            db.setCardNo(carNo);
        }
        db.setBusinessCarId(businessCarId);
        this.updateById(db);
    }
}
