/*
 * 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.depotTruckWeighDouble.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.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.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.entity.DepotTruckWeighDouble;
import vip.xiaonuo.biz.modular.depotTruckWeighDouble.mapper.DepotTruckWeighDoubleMapper;
import vip.xiaonuo.dev.modular.file.service.DevFileService;
import vip.xiaonuo.dev.modular.file.util.MultipartFileUtils;

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

/**
 * 双次过磅记录表Service接口实现类
 *
 * @author xiang
 * @date 2023/10/08 17:05
 **/
@Service
public class DepotTruckWeighDoubleService extends ServiceImpl<DepotTruckWeighDoubleMapper, DepotTruckWeighDouble> {

    @Resource
    DepotGrainService depotGrainService;
    @Resource
    private DepotTruckBookService depotTruckBookService;
    @Resource
    private DevFileService devFileService;

    public Page<DepotTruckWeighDouble> page(DepotTruckWeighDoublePageParam param) {
        QueryWrapper<DepotTruckWeighDouble> wrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotTruckWeighDouble::getDepotId, depotIdLst);
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotTruckWeighDouble::getLicensePlate, param.getSearchKey())
                        .or().like(DepotTruckWeighDouble::getDriverName, param.getSearchKey()));
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getDepotId()), DepotTruckWeighDouble::getDepotId, param.getDepotId());
        wrapper.lambda().like(Strings.isNotBlank(param.getTruckBookId()), DepotTruckWeighDouble::getTruckBookId, param.getTruckBookId());
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getDepotBizType()), DepotTruckWeighDouble::getDepotBizType, param.getDepotBizType());
        wrapper.lambda().eq(Strings.isNotBlank(param.getGrainGroup()), DepotTruckWeighDouble::getGrainGroup, param.getGrainGroup());
        wrapper.lambda().eq(Strings.isNotBlank(param.getBillGroup()), DepotTruckWeighDouble::getBillGroup, param.getBillGroup());
        wrapper.lambda().like(ObjectUtil.isNotEmpty(param.getLicensePlate()), DepotTruckWeighDouble::getLicensePlate, param.getLicensePlate());
        wrapper.lambda().like(ObjectUtil.isNotEmpty(param.getDriverName()), DepotTruckWeighDouble::getDriverName, param.getDriverName());
        wrapper.lambda().like(ObjectUtil.isNotEmpty(param.getDriverMobile()), DepotTruckWeighDouble::getDriverMobile, param.getDriverMobile());
        wrapper.lambda().eq(ObjectUtil.isNotEmpty(param.getPlateColor()), DepotTruckWeighDouble::getPlateColor, param.getPlateColor());
        if (ObjectUtil.isNotEmpty(param.getCarNumber())) {
            wrapper.lambda().like(DepotTruckWeighDouble::getCarNumber, param.getCarNumber());
        }
        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(DepotTruckWeighDouble::getId);
        }

        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    public List<DepotTruckWeighDouble> lst(DepotTruckWeighDoubleListParam param) {
        LambdaQueryWrapper<DepotTruckWeighDouble> wrapper = new LambdaQueryWrapper<>(BeanUtil.toBean(param, DepotTruckWeighDouble.class));
        wrapper.in(CollUtil.isNotEmpty(param.getTruckBookIdLst()), DepotTruckWeighDouble::getTruckBookId, param.getTruckBookIdLst());
        return list(wrapper.orderByDesc(DepotTruckWeighDouble::getId));
    }

    public List<DepotTruckWeighDouble> lst(StatisticsParam param) {
        LambdaQueryWrapper<DepotTruckWeighDouble> wrapper = new LambdaQueryWrapper(BeanUtil.copyProperties(param, DepotTruckWeighDouble.class));
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotTruckWeighDouble::getDepotId, depotIdLst);
        wrapper.ge(Strings.isNotBlank(param.getCreateTimeStart()), DepotTruckWeighDouble::getGrossTime, param.getCreateTimeStart());
        wrapper.le(Strings.isNotBlank(param.getCreateTimeEnd()), DepotTruckWeighDouble::getGrossTime, param.getCreateTimeEnd());
        return this.list(wrapper);
    }

    public DepotTruckWeighDouble getOne(DepotTruckWeighDoubleListParam param) {
        List<DepotTruckWeighDouble> list = lst(param);
        return list.isEmpty() ? null : list.get(0);
    }

    public DepotTruckWeighDouble getOneByBookId(String bookId) {
        return getOne(new DepotTruckWeighDoubleListParam(bookId));
    }

    public void add(DepotTruckWeighDoubleAddParam param) {
        DepotTruckWeighDouble depotTruckWeighDouble = this.getOne(new DepotTruckWeighDoubleListParam(param.getTruckBookId()));
        if (depotTruckWeighDouble != null) {
            BeanUtil.copyProperties(param, depotTruckWeighDouble);
            putInnerMinioPic(depotTruckWeighDouble);
            this.updateById(depotTruckWeighDouble);
            return;
        }
        BeanUtil.copyProperties(depotTruckBookService.getOneByBookId(param.getTruckBookId()), param);
        depotTruckWeighDouble = BeanUtil.toBean(param, DepotTruckWeighDouble.class);
        putInnerMinioPic(depotTruckWeighDouble);
        this.save(depotTruckWeighDouble);
    }

    public void addByPlug(DepotTruckWeighDoubleAddParam param) {
        param.setBillGroup("人工补单");
        this.add(param);
    }

    public void editByBookId(DepotTruckWeighDoubleAddParam param) {
        DepotTruckWeighDouble depotTruckWeighDouble = this.getOne(new DepotTruckWeighDoubleListParam(param.getTruckBookId()));
        BeanUtil.copyProperties(param, depotTruckWeighDouble);
        this.updateById(depotTruckWeighDouble);
    }

    public void delByBookId(String bookId) {
        DepotTruckWeighDouble depotTruckWeighDouble = this.getOne(new DepotTruckWeighDoubleListParam(bookId));
        removeById(depotTruckWeighDouble.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(DepotTruckWeighDoubleEditParam depotTruckWeighDoubleEditParam) {
        DepotTruckWeighDouble depotTruckWeighDouble = this.queryEntity(depotTruckWeighDoubleEditParam.getId());
        BeanUtil.copyProperties(depotTruckWeighDoubleEditParam, depotTruckWeighDouble);
        this.updateById(depotTruckWeighDouble);
    }

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

    public DepotTruckWeighDouble detail(String id, String bookId) {
        DepotTruckWeighDouble one = null;
        if (id != null)
            one = queryEntity(id);
        else if (bookId != null)
            one = getOne(new DepotTruckWeighDoubleListParam(bookId));
        if (one != null)
            one.setDepotGrainName(depotGrainService.getNameByDepotId(one.getDepotId()));
        return one;
    }

    public DepotTruckWeighDouble queryEntity(String id) {
        DepotTruckWeighDouble depotTruckWeighDouble = this.getById(id);
        if (ObjectUtil.isEmpty(depotTruckWeighDouble)) {
            throw new CommonException("双次过磅记录表不存在，id值为：{}", id);
        }
        return depotTruckWeighDouble;
    }

    public void putInnerMinioPic(DepotTruckWeighDouble d) {
        String type = "body";
        String itemCd = d.getDepotId();
        if (Strings.isNotEmpty(d.getGrossPlateName()) && d.getGrossPlateName().contains("base64"))
            d.setGrossPlateName(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossPlateName()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossLicenseName()) && d.getGrossLicenseName().contains("base64"))
            d.setGrossLicenseName(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossLicenseName()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossCaptureHead()) && d.getGrossCaptureHead().contains("base64"))
            d.setGrossCaptureHead(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossCaptureHead()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossCaptureTail()) && d.getGrossCaptureTail().contains("base64"))
            d.setGrossCaptureTail(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossCaptureTail()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossCaptureWare()) && d.getGrossCaptureWare().contains("base64"))
            d.setGrossCaptureWare(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossCaptureWare()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossCaptureBody()) && d.getGrossCaptureBody().contains("base64"))
            d.setGrossCaptureBody(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossCaptureBody()), itemCd, type));
        if (Strings.isNotEmpty(d.getGrossCapturePoundRoom()) && d.getGrossCapturePoundRoom().contains("base64"))
            d.setGrossCapturePoundRoom(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getGrossCapturePoundRoom()), itemCd, type));
        if (Strings.isNotEmpty(d.getTarePlateName()) && d.getTarePlateName().contains("base64"))
            d.setTarePlateName(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTarePlateName()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareLicenseName()) && d.getTareLicenseName().contains("base64"))
            d.setTareLicenseName(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareLicenseName()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareCaptureHead()) && d.getTareCaptureHead().contains("base64"))
            d.setTareCaptureHead(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareCaptureHead()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareCaptureTail()) && d.getTareCaptureTail().contains("base64"))
            d.setTareCaptureTail(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareCaptureTail()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareCaptureWare()) && d.getTareCaptureWare().contains("base64"))
            d.setTareCaptureWare(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareCaptureWare()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareCaptureBody()) && d.getTareCaptureBody().contains("base64"))
            d.setTareCaptureBody(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareCaptureBody()), itemCd, type));
        if (Strings.isNotEmpty(d.getTareCapturePoundRoom()) && d.getTareCapturePoundRoom().contains("base64"))
            d.setTareCapturePoundRoom(devFileService.uploadInnerMonioReturnUrl(MultipartFileUtils.base64ToMultipart(d.getTareCapturePoundRoom()), itemCd, type));
    }

}
