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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
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.depotSampling.entity.DepotSampling;
import vip.xiaonuo.biz.modular.depotSampling.mapper.DepotSamplingMapper;
import vip.xiaonuo.biz.modular.depotSampling.param.DepotSamplingAddParam;
import vip.xiaonuo.biz.modular.depotSampling.param.DepotSamplingEditParam;
import vip.xiaonuo.biz.modular.depotSampling.param.DepotSamplingIdParam;
import vip.xiaonuo.biz.modular.depotSampling.param.DepotSamplingPageParam;
import vip.xiaonuo.biz.modular.depotTruckBook.entity.DepotTruckBook;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.DatesUtil;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 质价确认Service接口
 *
 * @author xiang
 * @date 2023/09/13 16:37
 **/
@Service
public class DepotSamplingService extends ServiceImpl<DepotSamplingMapper, DepotSampling> {

    @Resource
    DepotGrainService depotGrainService;
    @Resource
    DepotTruckBookService truckBookService;

    @Resource
    SysUserService sysUserService;

    /**
     * 获取质价确认分页
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public Page<DepotSampling> page(DepotSamplingPageParam param) {
        QueryWrapper<DepotSampling> wrapper = new QueryWrapper<>();
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotSampling::getLicensePlate, param.getSearchKey())
                        .or().like(DepotSampling::getDriverName, param.getSearchKey()));
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotSampling::getDepotId, depotIdLst);
        wrapper.lambda().eq(Strings.isNotBlank(param.getDepotId()), DepotSampling::getDepotId, param.getDepotId());
        wrapper.lambda().like(Strings.isNotBlank(param.getTruckBookId()), DepotSampling::getTruckBookId, param.getTruckBookId());
        wrapper.lambda().eq(Strings.isNotBlank(param.getSaveState()), DepotSampling::getSaveState, param.getSaveState());
        wrapper.lambda().eq(Strings.isNotBlank(param.getSamplingType()), DepotSampling::getSamplingType, param.getSamplingType());
        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(DepotSampling::getId);
        }

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

    public DepotSampling getOneByBookId(String bookId) {
        return getOne(new LambdaQueryWrapper<>(new DepotSampling(bookId)));
    }

    /**
     * 获取待扦样预约号
     *
     * @author xiang
     * @date 2023/09/13 09:21
     */
    public List<String> waitSampling(List<String> depotIdLst) {
        LambdaQueryWrapper<DepotSampling> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotSampling::getDepotId, depotIdLst);
        wrapper.eq(DepotSampling::getSamplingType, "待扦样");
        List<DepotSampling> list = list(wrapper);
        return list.isEmpty() ? Collections.singletonList("1") : list.stream().map(DepotSampling::getTruckBookId).collect(Collectors.toList());
    }

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

    /**
     * 添加
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void add(DepotSamplingAddParam param) {
        DepotSampling depotSampling = getOneByBookId(param.getTruckBookId());
        if (depotSampling != null)
            throw new CommonException(String.format("扦样单已存在，不能重复添加。预约号:%s;车牌:%s;", param.getTruckBookId(), param.getLicensePlate()));
        depotSampling = BeanUtil.toBean(param, DepotSampling.class);
        this.save(depotSampling);
    }

    /**
     * 已入场自动添加
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void addAuto(DepotTruckBook book) {
        DepotSampling depotSampling = getOneByBookId(book.getTruckBookId());
        if (depotSampling != null) return;
        DepotSamplingAddParam param = new DepotSamplingAddParam();
        param.asByBook(book);
        param.setSamplingPrice(book.getSamplingPrice());
        depotSampling = BeanUtil.toBean(param, DepotSampling.class);
        this.save(depotSampling);
    }

    /**
     * 已至扦样区
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void addFlowIn(String truckBookId, String truckPicInOne, String truckPicInTwo, String truckInTime) {
        DepotSampling depotSampling = getOneByBookId(truckBookId);
        if (depotSampling == null) return;
        depotSampling.setTruckPicInOne(truckPicInOne);
        depotSampling.setTruckPicInTwo(truckPicInTwo);
        depotSampling.setTruckInTime(truckInTime);
        this.updateById(depotSampling);
    }

    /**
     * 离开扦样区
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void addFlowOut(String truckBookId, String truckPicOutOne, String truckPicOutTwo, String truckOutTime) {
        DepotSampling depotSampling = getOneByBookId(truckBookId);
        if (depotSampling == null) return;
        depotSampling.setTruckPicOutOne(truckPicOutOne);
        depotSampling.setTruckPicOutTwo(truckPicOutTwo);
        depotSampling.setTruckOutTime(truckOutTime);
        this.updateById(depotSampling);
    }

    /**
     * 扦样
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void addSampling(DepotSamplingAddParam param) {
        if ("扦样驳回".equals(param.getSamplingType())) {
            reject(param.getTruckBookId());
            return;
        }
        if (ArrayUtil.hasEmpty(param.getSamplingShuiFen(), param.getSamplingRongZhong(), param.getSamplingQueShao()
                , param.getSamplingMeiBian(), param.getSamplingZaZhi(), param.getSamplingPrice()))
            throw new CommonException(500, "扦样数据不完整!");
        if (param.getSamplingShuiFen().doubleValue() > 50 || param.getSamplingShuiFen().doubleValue() < 0)
            throw new CommonException(BizExceptionEnum.ERROR14004.getMessage());
        param.setSamplingType(BizStr.FLOW_QIAN_YANG_FINISH);
        DepotTruckBook book = truckBookService.getOneByBookId(param.getTruckBookId());
        //已入场、已至扦样区 并未确认
        DepotSampling sampling = getOneByBookId(param.getTruckBookId());
        if (sampling == null) {
            param.asByBook(book);
            this.save(BeanUtil.toBean(param, DepotSampling.class));
        } else {
            if (!"待扦样".equals(sampling.getSamplingType())) {
                throw new CommonException(String.format("扦样单已完成或流转，不能进行扦样。预约号：%s；车牌：%s；扦样状态：%s；", book.getTruckBookId(), book.getLicensePlate(), sampling.getSamplingType()));
            }
            //已入场、已至扦样区 以外
            else if (!BizStr.BOOK_RIGHT.equals(book.getBookState())) {
                throw new CommonException(String.format("车辆预约状态异常，不能进行扦样。预约号：%s；车牌：%s；预约状态：%s；", book.getTruckBookId(), book.getLicensePlate(), book.getBookState()));
            }
            this.updateById(new DepotSampling(sampling.getId(), param.getSamplingShuiFen(), param.getSamplingRongZhong(), param.getSamplingQueShao()
                    , param.getSamplingMeiBian(), param.getSamplingZaZhi(), param.getSamplingPrice(), param.getSamplingType()));
        }
        //扦样价格
        book.setSamplingPrice(param.getSamplingPrice());
        truckBookService.upTruckBookFlow(book, depotGrainService.getOnSampling(book.getDepotId()) ? BizStr.FLOW_QIAN_YANG_FINISH : BizStr.FLOW_QIAN_YANG_OUT, DatesUtil.forDateTime());
    }

    /**
     * 添加人工补单
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void addByPlug(DepotSamplingAddParam param) {
        DepotTruckBook book = truckBookService.getOneByBookId(param.getTruckBookId());
        param.asByBook(book);
        DepotSampling depotSampling = BeanUtil.toBean(param, DepotSampling.class);
        depotSampling.setSaveState(BizStr.STATE_PROCESS_E);
        depotSampling.setSamplingType(BizStr.FLOW_QIAN_YANG_FINISH);
        this.save(depotSampling);
    }

    /**
     * 离开扦样区
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    @Transactional(rollbackFor = Exception.class)
    public DepotSampling editByBookId(DepotSamplingAddParam param) {
        DepotSampling sampling = getOneByBookId(param.getTruckBookId());
        if (sampling == null) {
            sampling = new DepotSampling();
            param.asByBook(truckBookService.getOneByBookId(param.getTruckBookId()));
        }
        BeanUtil.copyProperties(param, sampling);
        this.saveOrUpdate(sampling);
        return sampling;
    }

    /**
     * 编辑质价确认
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void edit(DepotSamplingEditParam param) {
        DepotSampling depotSampling = this.queryEntity(param.getId());
        BeanUtil.copyProperties(param, depotSampling);
        this.updateById(depotSampling);
    }

    /**
     * 删除质价确认
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotSamplingIdParam> depotSamplingIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotSamplingIdParamList, DepotSamplingIdParam::getId));
    }

    /**
     * 获取质价确认详情
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public DepotSampling detail(DepotSampling param) {
        DepotSampling one = null;
        if (Strings.isNotEmpty(param.getId()))
            one = this.queryEntity(param.getId());
        else if (Strings.isNotEmpty(param.getTruckBookId()))
            one = this.getOneByBookId(param.getTruckBookId());
        if (one != null) {
            one.setDepotGrainName(depotGrainService.getNameByDepotId(one.getDepotId()));
            //人员账号
            SysUser sysUser = sysUserService.getOneById(one.getCreateUser());
            if (sysUser != null) {
                one.setCreateUserName(sysUser.getName());
                one.setCreateUserAccount(sysUser.getAccount());
            }
        }
        return one == null ? new DepotSampling() : one;
    }

    /**
     * 获取质价确认详情
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public DepotSampling detail(DepotSamplingIdParam depotSamplingIdParam) {
        return this.detail(new DepotSampling(depotSamplingIdParam.getId(), null));
    }

    /**
     * 质价驳回
     *
     * @author xiang
     * @date 2023/09/13 16:37
     */
    public void reject(String bookId) {
        LambdaUpdateWrapper<DepotSampling> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DepotSampling::getTruckBookId, bookId);
        wrapper.set(DepotSampling::getSamplingType, BizStr.FLOW_QIAN_YANG_REJECT);
        this.update(wrapper);
        //进程 扦样驳回
        truckBookService.upTruckBookFlow(bookId, BizStr.FLOW_QIAN_YANG_REJECT, DatesUtil.forDateTime());
    }

    /**
     * 获取质价确认详情
     *
     * @author xiang
     * @date 2023/09/13 16:37
     **/
    public DepotSampling queryEntity(String id) {
        DepotSampling depotSampling = this.getById(id);
        if (ObjectUtil.isEmpty(depotSampling)) {
            throw new CommonException("质价确认不存在，id值为：{}", id);
        }
        return depotSampling;
    }

}
