/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.depotRepayOrder.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.modular.login.service.AuthService;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.core.exception.BizExceptionEnum;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotGrainInfo.service.DepotGrainInfoFileService;
import vip.xiaonuo.biz.modular.depotGrainInfo.service.DepotGrainInfoService;
import vip.xiaonuo.biz.modular.depotGrainInfoPrice.entity.DepotGrainInfoPrice;
import vip.xiaonuo.biz.modular.depotGrainInfoPrice.service.DepotGrainInfoPriceService;
import vip.xiaonuo.biz.modular.depotRepayOrder.entity.DepotRepayOrderDetailVo;
import vip.xiaonuo.biz.modular.depotRepayOrder.param.*;
import vip.xiaonuo.biz.modular.depotTruckBook.entity.DepotTruckBook;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.entity.DepotTruckWeighDouble;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.param.DepotTruckWeighDoubleListParam;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.service.DepotTruckWeighDoubleService;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.service.DepotTruckWeighPlugService;
import vip.xiaonuo.biz.modular.depotWork.service.DepotWorkService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotRepayOrder.entity.DepotRepayOrder;
import vip.xiaonuo.biz.modular.depotRepayOrder.mapper.DepotRepayOrderMapper;
import vip.xiaonuo.common.util.BigDecimalUtil;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 出库还款Service接口实现类
 *
 * @author xiang
 * @date 2023/09/18 16:45
 **/
@Service
public class DepotRepayOrderService extends ServiceImpl<DepotRepayOrderMapper, DepotRepayOrder> {

    @Resource
    DepotGrainService depotGrainService;
    @Resource
    DepotGrainInfoService depotGrainInfoService;
    @Resource
    DepotGrainInfoPriceService depotGrainInfoPriceService;
    @Resource
    DepotGrainInfoFileService depotGrainInfoFileService;
    @Resource
    DepotTruckBookService bookService;
    @Resource
    DepotWorkService depotWorkService;
    @Resource
    DepotTruckWeighDoubleService truckWeighDoubleService;
    @Resource
    DevFileApi devFileApi;
    @Resource
    AuthService authService;
    @Resource
    DepotTruckWeighPlugService truckWeighPlugService;

    public Page<DepotRepayOrder> page(DepotRepayOrderPageParam param) {
        QueryWrapper<DepotRepayOrder> wrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotRepayOrder::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotRepayOrder::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getContractCode())) {
            wrapper.lambda().like(DepotRepayOrder::getContractCode, param.getContractCode());
        }
        wrapper.lambda().like(Strings.isNotBlank(param.getRepayOrderNo()), DepotRepayOrder::getRepayOrderNo, param.getRepayOrderNo());
        wrapper.lambda().eq(Strings.isNotBlank(param.getGrainGroup()), DepotRepayOrder::getGrainGroup, param.getGrainGroup());
        if (ObjectUtil.isNotEmpty(param.getLicensePlate())) {
            wrapper.lambda().like(DepotRepayOrder::getLicensePlate, param.getLicensePlate());
        }
        if (ObjectUtil.isNotEmpty(param.getKeeperName())) {
            wrapper.lambda().like(DepotRepayOrder::getKeeperName, param.getKeeperName());
        }
        if (ObjectUtil.isNotEmpty(param.getKeeperCitizenId())) {
            wrapper.lambda().like(DepotRepayOrder::getKeeperCitizenId, param.getKeeperCitizenId());
        }
        if (ObjectUtil.isNotEmpty(param.getKeeperMobile())) {
            wrapper.lambda().like(DepotRepayOrder::getKeeperMobile, param.getKeeperMobile());
        }
        wrapper.lambda().eq(Strings.isNotBlank(param.getBankOpApprovalState()), DepotRepayOrder::getBankOpApprovalState, param.getBankOpApprovalState());
        wrapper.lambda().eq(Strings.isNotBlank(param.getBookFlag()), DepotRepayOrder::getBookFlag, param.getBookFlag());
        wrapper.lambda().eq(Strings.isNotBlank(param.getRepayState()), DepotRepayOrder::getRepayState, param.getRepayState());
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            wrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            wrapper.lambda().orderByDesc(DepotRepayOrder::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        //人员信息
        putUserInfo(page.getRecords());
        return page;
    }

    private void putUserInfo(List<DepotRepayOrder> list) {
        if (list.isEmpty()) return;
        List<String> userIds = new LinkedList<>();
        list.forEach(one -> {
            if (Strings.isNotBlank(one.getBankOpApprovalUser()))
                userIds.add(one.getBankOpApprovalUser());
            if (Strings.isNotBlank(one.getCreateUser()))
                userIds.add(one.getCreateUser());
        });
        if (userIds.isEmpty()) return;
        List<SysUser> users = sysUserService.listByIds(userIds);
        for (DepotRepayOrder one : list) {
            //审批人
            if (Strings.isNotBlank(one.getBankOpApprovalUser()))
                for (SysUser user : users) {
                    if (!one.getBankOpApprovalUser().equals(user.getId())) continue;
                    one.setApprovalUserName(user.getName());
                    one.setApprovalUserAccount(user.getAccount());
                    break;
                }
            //创建人
            if (Strings.isNotBlank(one.getCreateUser()))
                for (SysUser user : users) {
                    if (!one.getCreateUser().equals(user.getId())) continue;
                    one.setCreateUserName(user.getName());
                    one.setCreateUserAccount(user.getAccount());
                    break;
                }
        }
    }

    public List<DepotRepayOrder> lst(DepotRepayOrderPageParam param) {
        QueryWrapper<DepotRepayOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Strings.isNotBlank(param.getDepotId()), DepotRepayOrder::getDepotId, param.getDepotId());
        wrapper.lambda().eq(Strings.isNotBlank(param.getRepayOrderNo()), DepotRepayOrder::getRepayOrderNo, param.getRepayOrderNo());
        wrapper.lambda().like(Strings.isNotBlank(param.getLicensePlate()), DepotRepayOrder::getLicensePlate, param.getLicensePlate());
        wrapper.lambda().eq(Strings.isNotBlank(param.getGrainGroup()), DepotRepayOrder::getGrainGroup, param.getGrainGroup());
        wrapper.lambda().eq(Strings.isNotBlank(param.getBankOpApprovalState()), DepotRepayOrder::getBankOpApprovalState, param.getBankOpApprovalState());
        wrapper.lambda().eq(Strings.isNotBlank(param.getBookFlag()), DepotRepayOrder::getBookFlag, param.getBookFlag());
        if (Strings.isNotEmpty(param.getRepayState()))
            wrapper.gt("instr('" + param.getRepayState() + "', repay_state)", 0);
        return list(wrapper);
    }

    public List<DepotRepayOrder> lst(DepotRepayOrder param) {
        return list(new LambdaQueryWrapper<>(param).orderByDesc(DepotRepayOrder::getId));
    }

    /**
     * 获取待处理
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public List<DepotRepayOrder> waitProcess(List<String> depotIdLst) {
        LambdaQueryWrapper<DepotRepayOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotRepayOrder::getDepotId, depotIdLst);
        wrapper.eq(DepotRepayOrder::getBankOpApprovalState, BizStr.STATE_APPROVAL_N);
        wrapper.eq(DepotRepayOrder::getRepayState, BizStr.STATE_REPAY_N);
        return list(wrapper.orderByDesc(DepotRepayOrder::getId));
    }

    public DepotRepayOrder oneByOrderNo(String repayOrderNo) {
        return getOne(new LambdaQueryWrapper<>(new DepotRepayOrder(repayOrderNo)));
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(DepotRepayOrderAddParam param) {
        //车牌号校验
        checkTruckBook(Arrays.asList(param.getLicensePlate().split(",")));
        //还款额校验
        depotGrainInfoService.loanSumCheck(param.getDepotId(), param.getRepayPrincipal());
        //粮食分类还贷重量和价格校验
        checkRepayGroup(param.getDepotId(), param.getGrainGroup(), param.getRepayTonThis(), param.getRepayPrice());
        DepotRepayOrder order = BeanUtil.toBean(param, DepotRepayOrder.class);
        order.setRepayTonSum(BigDecimalUtil.addVal(order.getRepayTonThis(), order.getRepayBeforeTonSurplus()));
        order.setRepayTonSurplus(order.getRepayTonSum());
        //处理图片
        if (Strings.isNotBlank(order.getKeeperCitizenPic()) && order.getKeeperCitizenPic().length() == 19)
            order.setKeeperCitizenPic(devFileApi.storageFilePathReturnUrlById(order.getKeeperCitizenPic()));
        this.save(order);
    }

    public void edit(DepotRepayOrderEditParam param) {
        DepotRepayOrder order = this.queryEntity(param.getId());
        if (!BizStr.STATE_APPROVAL_N.equals(order.getBankOpApprovalState()))
            throw new CommonException("已确认的还款单无法修改!" + order.getRepayOrderNo());
        if (BigDecimalUtil.isNullOrEqZero(param.getRepayBeforeTonSurplus()))
            param.setRepayBeforeTonSurplus(order.getRepayBeforeTonSurplus());
        //还款额校验
        depotGrainInfoService.loanSumCheck(param.getDepotId(), param.getRepayPrincipal());
        //粮食分类还贷重量和价格校验
        checkRepayGroup(order.getDepotId(), order.getGrainGroup(), order.getRepayTonThis(), order.getRepayPrice());
        BeanUtil.copyProperties(param, order);
        //数量
        if (BigDecimalUtil.isNotNullOrEqZero(order.getRepayTonThis())) {
            order.setRepayTonSum(BigDecimalUtil.addVal(order.getRepayTonThis(), order.getRepayBeforeTonSurplus()));
            order.setRepayTonSurplus(order.getRepayTonSum());
        }
        //处理图片
        if (Strings.isNotBlank(order.getKeeperCitizenPic()) && order.getKeeperCitizenPic().length() == 19)
            order.setKeeperCitizenPic(devFileApi.storageFilePathReturnUrlById(order.getKeeperCitizenPic()));
        this.updateById(order);
    }

    public void editBookFlag(String id, String bookFlag) {
        DepotRepayOrder order = this.queryEntity(id);
        if (BizStr.STATE_REPAY_Y.equals(order.getRepayState()))
            throw new CommonException(BizExceptionEnum.ERROR12007.getMessage());
        updateById(new DepotRepayOrder(id, null, null, bookFlag));
    }

    /**
     * 添加候补车牌
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void plug(DepotRepayOrderPlugParam param) {
        if (Strings.isNotBlank(param.getLicensePlatePlug())) {
            List<String> licensePlates = Arrays.asList(param.getLicensePlatePlug().split(",")).stream().distinct().collect(Collectors.toList());
            checkTruckBook(licensePlates);
            param.setLicensePlatePlug(Joiner.on(",").join((licensePlates)));
        }
        LambdaUpdateWrapper<DepotRepayOrder> wrapper = new LambdaUpdateWrapper<>(new DepotRepayOrder(param.getId(), null, null));
        wrapper.set(DepotRepayOrder::getLicensePlatePlug, param.getLicensePlatePlug());
        update(wrapper);
    }

    /**
     * 审批候补车牌
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void approvalPlug(DepotRepayOrderPlugParam param) {
        DepotRepayOrder order = this.queryEntity(param.getId());
        List<String> licensePlates = new ArrayList<>(Arrays.asList(order.getLicensePlate().split(",")));
        List<String> licensePlatePlugs = Arrays.asList(param.getLicensePlatePlug().split(","));
        for (String plug : licensePlatePlugs) {
            licensePlates.add(plug + " 补");
        }
        LambdaUpdateWrapper<DepotRepayOrder> wrapper = new LambdaUpdateWrapper<>(new DepotRepayOrder(param.getId(), null, null));
        wrapper.set(DepotRepayOrder::getLicensePlate, Joiner.on(",").join(licensePlates.stream().distinct().collect(Collectors.toList())));
        wrapper.set(DepotRepayOrder::getLicensePlatePlug, null);
        update(wrapper);
    }


    /**
     * 关单
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    @Transactional(rollbackFor = Exception.class)
    public void offOrder(String id) {
        DepotRepayOrder order = this.queryEntity(id);
        //车辆预约校验
        //checkOffOrder(order.getDepotId(), order.getRepayOrderNo());
        updateById(new DepotRepayOrder(id, BizStr.BOOK_OFF, BizStr.STATE_REPAY_Y));
        //车辆预约关单
        List<String> bookIds = bookService.offRepayOrder(order.getRepayOrderNo());
        //人工补单驳回
        truckWeighPlugService.bankOpApproval(bookIds);
    }

    /**
     * 添加新单时校验最近一次还款单并获取可结转单
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public DepotRepayOrder getBeforeAdd(String depotId, String grainGroup) {
        //上次还款单
        List<DepotRepayOrder> orders = lst(new DepotRepayOrder(depotId, grainGroup));
        if (orders.isEmpty())
            return new DepotRepayOrder();
        DepotRepayOrder order = orders.get(0);
        // 待审批/已确认/已上传凭证
        if (BizStr.STATE_APPROVAL_N.equals(order.getBankOpApprovalState())
                || BizStr.STATE_CONFIRM_Y.equals(order.getBankOpApprovalState())
                || BizStr.STATE_UPLOAD_Y.equals(order.getBankOpApprovalState()))
            throw new CommonException(String.format("%s;待处理单号:%s;待处理状态:%s", BizExceptionEnum.ERROR12006.getMessage(), order.getRepayOrderNo(), order.getBankOpApprovalState()));
        //已结账单号
        List<String> repayBeforeOrderNos = orders.stream().map(DepotRepayOrder::getRepayBeforeOrderNo).collect(Collectors.toList());
        //上传结转
        for (DepotRepayOrder one : orders) {
            //过滤未结束
            if (!BizStr.STATE_REPAY_Y.equals(one.getRepayState())) continue;
            //过滤已结转
            if (repayBeforeOrderNos.contains(one.getRepayOrderNo())) continue;
            //过滤没有剩余量的
            if (BigDecimalUtil.isNullOrEqZero(one.getRepayTonSurplus())) continue;
            return one;
        }
        return new DepotRepayOrder();
    }

    /**
     * 还款单更新出库
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public DepotRepayOrder editRepayTonReal(String repayOrderNo, BigDecimal netWeight) {
        DepotRepayOrder depotRepayOrder = this.oneByOrderNo(repayOrderNo);
        depotRepayOrder.setRepayTonOut(BigDecimalUtil.addVal(depotRepayOrder.getRepayTonOut(), netWeight));
        depotRepayOrder.setRepayTonSurplus(BigDecimalUtil.addVal(depotRepayOrder.getRepayTonSurplus(), netWeight.negate()));
        depotRepayOrder.setRepayState(BizStr.STATE_REPAY_Z);
        this.updateById(depotRepayOrder);
        return depotRepayOrder;
    }

    /**
     * 二级确认和审批
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    @Transactional(rollbackFor = Exception.class)
    public void bankOpApproval(DepotRepayOrderApprovalParam param) {
        //已确认-未通过
        if (BizStr.STATE_APPROVAL_G.equals(param.getBankOpApprovalState())) {
            DepotRepayOrder order = new DepotRepayOrder(param.getId(), BizStr.BOOK_OFF, BizStr.STATE_REPAY_Y);
            order.setBankOpApprovalState(BizStr.STATE_APPROVAL_G);
            order.setBankOpApprovalTime(new Date());
            order.setBankOpApprovalMsg(param.getBankOpApprovalMsg());
            order.setBankOpApprovalUser(authService.getLoginUser().getId());
            updateById(order);
        } else if ("已上传凭证".equals(param.getBankOpApprovalState())) {
            updateById(new DepotRepayOrder(param.getId(), param.getBankOpApprovalState(), null, null));
        } else if (BizStr.STATE_APPROVAL_Y.equals(param.getBankOpApprovalState())) {
            DepotRepayOrder order = this.queryEntity(param.getId());
            order.setBankOpApprovalState(param.getBankOpApprovalState());
            order.setBankOpApprovalTime(new Date());
            order.setBankOpApprovalMsg(param.getBankOpApprovalMsg() == null && order.getBankOpApprovalMsg() != null ? " " : param.getBankOpApprovalMsg());
            order.setBookFlag(BizStr.BOOK_ON);
            order.setBankOpApprovalUser(authService.getLoginUser().getId());
            updateById(order);
            //还款同步客户信息
            depotGrainInfoService.repaySync(order.getDepotId(), order.getRepayPrincipal(), order.getRepayInterest(), order.getRepayTonThis(), order.getGrainGroup());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotRepayOrderIdParam> depotRepayOrderIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotRepayOrderIdParamList, DepotRepayOrderIdParam::getId));
    }

    @Resource
    SysUserService sysUserService;

    public DepotRepayOrderDetailVo detail(DepotRepayOrderIdParam depotRepayOrderIdParam) {
        DepotRepayOrderDetailVo vo = BeanUtil.toBean(this.queryEntity(depotRepayOrderIdParam.getId()), DepotRepayOrderDetailVo.class);
        vo.setDepotGrainName(depotGrainService.getNameByDepotId(vo.getDepotId()));
        if (BizStr.STATE_APPROVAL_Y.equals(vo.getBankOpApprovalState()))
            vo.setDepotWorkList(depotWorkService.lst(vo.getRepayOrderNo(), null));
        if (!BizStr.STATE_APPROVAL_N.equals(vo.getBankOpApprovalState()))
            vo.setUploads(depotGrainInfoService.fileLst(vo.getId()));
        vo.setKeeperCitizenPic(depotGrainInfoFileService.getFullUrl(vo.getKeeperCitizenPic()));
        SysUser sysUser = sysUserService.getOneById(vo.getBankOpApprovalUser());
        if (sysUser != null) {
            vo.setApprovalUserName(sysUser.getName());
            vo.setApprovalUserAccount(sysUser.getAccount());
        }
        //已申请未结束的预约
        vo.setTruckBookList(bookService.lst(new DepotTruckBook(vo.getDepotId(), vo.getRepayOrderNo(), null, BizStr.BOOK_RIGHT)));
        return vo;
    }

    public DepotRepayOrder queryEntity(String id) {
        DepotRepayOrder depotRepayOrder = this.getById(id);
        if (ObjectUtil.isEmpty(depotRepayOrder)) {
            throw new CommonException("出库还款不存在，id值为：{}", id);
        }
        return depotRepayOrder;
    }

    /**
     * 出库还款净重校验
     *
     * @param netWeight 净重 吨
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void checkOutNetWeight(DepotTruckBook book, BigDecimal netWeight) {
        if (book == null || book.getRepayOrderNo() == null) return;
        //未结束预约号
        List<DepotTruckBook> bookLst = bookService.lst(new DepotTruckBook(book.getDepotId(), book.getRepayOrderNo(), BizStr.STATE_APPROVAL_Y, BizStr.BOOK_RIGHT));
        List<String> bookIdLst = bookLst.stream().filter(b -> !book.getTruckBookId().equals(b.getTruckBookId())).map(DepotTruckBook::getTruckBookId).collect(Collectors.toList());
        if (!bookIdLst.isEmpty()) {
            //人工补单待审批
            //List<DepotTruckWeighPlug> truckWeighPlugLst = truckWeighPlugService.lst(null, bookIdLst, new DepotTruckWeighPlug(null, BizStr.STATE_APPROVAL_N));
            //双次过磅
            List<DepotTruckWeighDouble> weighDoubleLst = truckWeighDoubleService.lst(new DepotTruckWeighDoubleListParam(bookIdLst));
            for (String bookId : bookIdLst) {
                /*for (DepotTruckWeighPlug plug : truckWeighPlugLst) {
                    if (!plug.getTruckBookId().equals(bookId)) continue;
                    netWeight = BigDecimalUtil.addVal(netWeight, plug.getNetWeight().movePointLeft(3));
                    bookId = null;
                }*/
                for (DepotTruckWeighDouble weighDouble : weighDoubleLst) {
                    if (!weighDouble.getTruckBookId().equals(bookId) || BigDecimalUtil.isNullOrEqZero(weighDouble.getNetWeight())) continue;
                    netWeight = BigDecimalUtil.addVal(netWeight, weighDouble.getNetWeight().movePointLeft(3));
                    bookId = null;
                }
            }
        }
        //还款单
        DepotRepayOrder order = this.oneByOrderNo(book.getRepayOrderNo());
        if (order.getRepayTonSurplus().compareTo(netWeight) < 0)
            throw new CommonException(String.format("%s 待出库数量(吨)：%s；；本次净重(吨)：%s；"
                    , BizExceptionEnum.ERROR14001.getMessage()
                    , order.getRepayTonSurplus()
                    , netWeight.stripTrailingZeros()));
    }

    /**
     * 车牌号校验
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void checkTruckBook(List<String> licensePlates) {
        for (String licensePlate : licensePlates) {
            if (!Validator.isPlateNumber(licensePlate))
                throw new CommonException(BizExceptionEnum.ERROR13006.getMessage() + licensePlate);
        }
    }

    /**
     * 关单校验
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void checkOffOrder(String depotId, String repayOrderNo) {
        List<DepotTruckBook> lst = bookService.lst(new DepotTruckBook(depotId, repayOrderNo, null, BizStr.BOOK_RIGHT));
        //未审批 已审批未入场 已入场未出场
        int num1 = 0, num2 = 0, num3 = 0;
        for (DepotTruckBook book : lst) {
            if (!BizStr.BOOK_RIGHT.equals(book.getBookState())) continue;
            if (BizStr.STATE_APPROVAL_N.equals(book.getDepotOpApprovalState())) {
                num1++;
            }
            if (BizStr.STATE_APPROVAL_Y.equals(book.getDepotOpApprovalState())
                    && book.getBizFlowName() == null) {
                num2++;
            }
            if (BizStr.STATE_APPROVAL_Y.equals(book.getDepotOpApprovalState())
                    && book.getBizFlowName() != null) {
                num3++;
            }
        }
        if (num1 + num2 + num3 > 0)
            throw new CommonException(BizExceptionEnum.ERROR13004.getCode()
                    , String.format("(%s) %s"
                    , repayOrderNo, BizExceptionEnum.ERROR13004.getMessage()));
    }

    /**
     * 粮食分类还贷重量和价格校验
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public void checkRepayGroup(String depotId, String grainGroup, BigDecimal repayWeight, BigDecimal repayPrice) {
        DepotGrainInfoPrice price = depotGrainInfoPriceService.oneByGrainGroup(depotId, grainGroup);
        if (price == null)
            throw new CommonException(String.format("检查粮食种类不存在;请联系管理员;粮库:%s;种类:%s", depotId, grainGroup));
        if (BigDecimalUtil.isNotNullOrEqZero(repayWeight)
                && repayWeight.compareTo(price.getLoanTonW().movePointRight(4)) > 0)
            throw new CommonException(BizExceptionEnum.ERROR14002.getMessage());
        if (BigDecimalUtil.isNotNullOrEqZero(repayPrice)
                && price.getLoanPrice().compareTo(repayPrice) > 0)
            throw new CommonException(BizExceptionEnum.ERROR14003.getMessage() + price.getLoanPrice());
    }

}
