/*
 * 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.depotTruckWeighPlug.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
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 org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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.depotRepayOrder.service.DepotRepayOrderService;
import vip.xiaonuo.biz.modular.depotSampling.param.DepotSamplingAddParam;
import vip.xiaonuo.biz.modular.depotSampling.service.DepotSamplingService;
import vip.xiaonuo.biz.modular.depotTruckBook.entity.DepotTruckBook;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.param.DepotTruckWeighDoubleAddParam;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.service.DepotTruckWeighDoubleService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.entity.DepotTruckWeighPlug;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.mapper.DepotTruckWeighPlugMapper;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.param.DepotTruckWeighPlugAddParam;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.param.DepotTruckWeighPlugEditParam;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.param.DepotTruckWeighPlugIdParam;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.param.DepotTruckWeighPlugPageParam;
import vip.xiaonuo.common.util.DatesUtil;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 车辆称重补单表Service接口实现类
 *
 * @author xiang
 * @date 2023/11/27 08:54
 **/
@Service
public class DepotTruckWeighPlugService extends ServiceImpl<DepotTruckWeighPlugMapper, DepotTruckWeighPlug> {

    @Resource
    DepotGrainService depotGrainService;
    @Resource
    private DepotTruckBookService depotTruckBookService;
    @Resource
    private DepotTruckWeighDoubleService depotTruckWeighDoubleService;
    @Resource
    private DepotSamplingService samplingService;

    @Resource
    DepotRepayOrderService depotRepayOrderService;

    public Page<DepotTruckWeighPlug> page(DepotTruckWeighPlugPageParam param) {
        QueryWrapper<DepotTruckWeighPlug> wrapper = new QueryWrapper<>();
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotTruckWeighPlug::getLicensePlate, param.getSearchKey())
                        .or().like(DepotTruckWeighPlug::getDriverName, param.getSearchKey()));
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotTruckWeighPlug::getDepotId, param.getDepotId());
        } else {
            List<String> depotIdLst = depotGrainService.lstOrgGrep();
            wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotTruckWeighPlug::getDepotId, depotIdLst);
        }
        if (ObjectUtil.isNotEmpty(param.getTruckBookId())) {
            wrapper.lambda().like(DepotTruckWeighPlug::getTruckBookId, param.getTruckBookId());
        }
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getDepotBizType()), DepotTruckWeighPlug::getDepotBizType, param.getDepotBizType());
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getGrainGroup()), DepotTruckWeighPlug::getGrainGroup, param.getGrainGroup());
        if (ObjectUtil.isNotEmpty(param.getGrainType())) {
            wrapper.lambda().eq(DepotTruckWeighPlug::getGrainType, param.getGrainType());
        }
        if (ObjectUtil.isNotEmpty(param.getLicensePlate())) {
            wrapper.lambda().like(DepotTruckWeighPlug::getLicensePlate, param.getLicensePlate());
        }
        if (ObjectUtil.isNotEmpty(param.getDriverName())) {
            wrapper.lambda().like(DepotTruckWeighPlug::getDriverName, param.getDriverName());
        }
        if (ObjectUtil.isNotEmpty(param.getDriverMobile())) {
            wrapper.lambda().like(DepotTruckWeighPlug::getDriverMobile, param.getDriverMobile());
        }
        if (ObjectUtil.isNotEmpty(param.getPlateColor())) {
            wrapper.lambda().like(DepotTruckWeighPlug::getPlateColor, param.getPlateColor());
        }
        if (ObjectUtil.isNotEmpty(param.getStartTareTime()) && ObjectUtil.isNotEmpty(param.getEndTareTime())) {
            wrapper.lambda().between(DepotTruckWeighPlug::getTareTime, param.getStartTareTime(), param.getEndTareTime());
        }
        if (ObjectUtil.isNotEmpty(param.getBankOpApprovalState()))
            wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getBankOpApprovalState()), DepotTruckWeighPlug::getBankOpApprovalState, param.getBankOpApprovalState());
        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(DepotTruckWeighPlug::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    /**
     * 获取待处理
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public List<DepotTruckWeighPlug> waitProcess(List<String> depotIdLst) {
        return lst(depotIdLst, null, new DepotTruckWeighPlug(null, BizStr.STATE_APPROVAL_N));
    }

    /**
     * 获取列表
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public List<DepotTruckWeighPlug> lst(List<String> depotIdLst, List<String> bookIdLst, DepotTruckWeighPlug param) {
        LambdaQueryWrapper<DepotTruckWeighPlug> wrapper = new LambdaQueryWrapper<>(param);
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotTruckWeighPlug::getDepotId, depotIdLst);
        wrapper.in(CollUtil.isNotEmpty(bookIdLst), DepotTruckWeighPlug::getTruckBookId, bookIdLst);
        return list(wrapper.orderByDesc(DepotTruckWeighPlug::getId));
    }

    public void add(DepotTruckWeighPlugAddParam param) {
        DepotTruckBook book = depotTruckBookService.getOneByBookId(param.getTruckBookId());
        //净重校验
        //depotRepayOrderService.checkOutNetWeight(book, param.getNetWeight().movePointLeft(3));
        //水份校验
        if (BizStr.KU_RU.equals(param.getDepotBizType()) && Strings.isNotBlank(param.getSamplingShuiFen())
                && (Double.parseDouble(param.getSamplingShuiFen()) > 50 || Double.parseDouble(param.getSamplingShuiFen()) < 0)) {
            throw new CommonException(BizExceptionEnum.ERROR14004.getMessage());
        }
        param.asBook(book);
        this.save(BeanUtil.toBean(param, DepotTruckWeighPlug.class));
    }

    public void edit(DepotTruckWeighPlugEditParam depotTruckWeighPlugEditParam) {
        DepotTruckWeighPlug depotTruckWeighPlug = this.queryEntity(depotTruckWeighPlugEditParam.getId());
        BeanUtil.copyProperties(depotTruckWeighPlugEditParam, depotTruckWeighPlug);
        this.updateById(depotTruckWeighPlug);
    }

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

    public DepotTruckWeighPlug detail(DepotTruckWeighPlugIdParam depotTruckWeighPlugIdParam) {
        DepotTruckWeighPlug one = this.queryEntity(depotTruckWeighPlugIdParam.getId());
        one.setDepotGrainName(depotGrainService.getNameByDepotId(one.getDepotId()));
        return one;
    }

    public DepotTruckWeighPlug queryEntity(String id) {
        DepotTruckWeighPlug depotTruckWeighPlug = this.getById(id);
        if (ObjectUtil.isEmpty(depotTruckWeighPlug)) {
            throw new CommonException("车辆称重补单表不存在，id值为：{}", id);
        }
        return depotTruckWeighPlug;
    }

    /**
     * 人工补单自动驳回
     *
     * @author xiang
     * @date 2023/10/08 17:05
     */
    @Transactional(rollbackFor = Exception.class)
    public void bankOpApproval(List<String> bookIds) {
        if (CollUtil.isEmpty(bookIds)) return;
        LambdaUpdateWrapper<DepotTruckWeighPlug> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(DepotTruckWeighPlug::getTruckBookId, bookIds);
        wrapper.eq(DepotTruckWeighPlug::getBankOpApprovalState, BizStr.STATE_APPROVAL_PASS_N);
        wrapper.set(DepotTruckWeighPlug::getBankOpApprovalState, BizStr.STATE_APPROVAL_PASS_G);
        wrapper.set(DepotTruckWeighPlug::getBankOpApprovalTime, new Date());
        update(wrapper);
    }

    /**
     * 人工补单审批
     *
     * @author xiang
     * @date 2023/10/08 17:05
     */
    @Transactional(rollbackFor = Exception.class)
    public void bankOpApproval(DepotTruckWeighPlugEditParam param) {
        if (Strings.isBlank(param.getBankOpApprovalState()))
            param.setBankOpApprovalState(BizStr.STATE_APPROVAL_PASS_Y);
        DepotTruckWeighPlug upOne = getById(param.getId());
        upOne.setBankOpApprovalState(param.getBankOpApprovalState());
        upOne.setBankOpApprovalTime(new Date());
        updateById(upOne);
        if (BizStr.STATE_APPROVAL_PASS_G.equals(upOne.getBankOpApprovalState()))
            return;
        DepotTruckBook book = depotTruckBookService.getOneByBookId(upOne.getTruckBookId());
        //净重校验
        depotRepayOrderService.checkOutNetWeight(book, upOne.getNetWeight().movePointLeft(3));
        //添加到双次过磅
        depotTruckWeighDoubleService.addByPlug(BeanUtil.copyProperties(upOne, DepotTruckWeighDoubleAddParam.class));
        //添加到签样单
        DepotSamplingAddParam addParam = BeanUtil.copyProperties(upOne, DepotSamplingAddParam.class);
        addParam.setSamplingPrice(upOne.getUnitPrice());
        samplingService.addByPlug(addParam);
        book.setSamplingPrice(upOne.getUnitPrice());
        //车辆进程更新
        depotTruckBookService.upTruckBookFlow(book, BizStr.FLOW_CHU_CHANG, DatesUtil.forDateTime(upOne.getTareTime()));
    }
}
