/*
 * 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.depotTruckPlateList.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.entity.DepotGrain;
import vip.xiaonuo.biz.modular.depotGrain.param.DepotGrainPageParam;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotTruckPlateList.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotTruckPlateList.entity.DepotTruckPlateList;
import vip.xiaonuo.biz.modular.depotTruckPlateList.mapper.DepotTruckPlateListMapper;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 车牌名单Service接口实现类
 *
 * @author xiang
 * @date 2024/03/24 14:59
 **/
@Service
public class DepotTruckPlateListService extends ServiceImpl<DepotTruckPlateListMapper, DepotTruckPlateList> {

    @Resource
    DepotGrainService depotGrainService;

    public Page<DepotTruckPlateList> page(DepotTruckPlateListPageParam param) {
        QueryWrapper<DepotTruckPlateList> wrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotTruckPlateList::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotTruckPlateList::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getListType())) {
            wrapper.lambda().eq(DepotTruckPlateList::getListType, param.getListType());
        }
        if (ObjectUtil.isNotEmpty(param.getPlateValue())) {
            wrapper.lambda().like(DepotTruckPlateList::getPlateValue, param.getPlateValue());
        }
        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().orderByAsc(DepotTruckPlateList::getId);
        }

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

    /**
     * 匹配粮库名称
     *
     * @author xiang
     * @date 2023-01-01
     */
    private void putDepotName(List<DepotTruckPlateList> sources) {
        if (CollUtil.isEmpty(sources)) return;
        List<DepotGrain> lst = this.depotGrainService.lst(new DepotGrainPageParam(null, sources.stream().map(DepotTruckPlateList::getDepotId).distinct().collect(Collectors.toList())));
        for (DepotTruckPlateList s : sources) {
            for (DepotGrain one : lst) {
                if (!Objects.equals(s.getDepotId(), one.getDepotId()))
                    continue;
                s.setDepotGrainName(one.getDepotGrainName());
                break;
            }
        }
    }

    public List<DepotTruckPlateList> lst(String depotId, String plateValue) {
        return list(new LambdaQueryWrapper<>(new DepotTruckPlateList(depotId, plateValue)));
    }

    public void add(DepotTruckPlateListAddParam depotTruckPlateListAddParam) {
        DepotTruckPlateList depotTruckPlateList = BeanUtil.toBean(depotTruckPlateListAddParam, DepotTruckPlateList.class);
        this.save(depotTruckPlateList);
    }

    public void edit(DepotTruckPlateListEditParam depotTruckPlateListEditParam) {
        DepotTruckPlateList depotTruckPlateList = this.queryEntity(depotTruckPlateListEditParam.getId());
        BeanUtil.copyProperties(depotTruckPlateListEditParam, depotTruckPlateList);
        this.updateById(depotTruckPlateList);
    }

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

    public DepotTruckPlateList detail(DepotTruckPlateListIdParam depotTruckPlateListIdParam) {
        return this.queryEntity(depotTruckPlateListIdParam.getId());
    }

    public DepotTruckPlateList queryEntity(String id) {
        DepotTruckPlateList depotTruckPlateList = this.getById(id);
        if (ObjectUtil.isEmpty(depotTruckPlateList)) {
            throw new CommonException("车牌名单不存在，id值为：{}", id);
        }
        return depotTruckPlateList;
    }

    public void depotTruckPlateListPush(DepotTruckPlateListPushParam param) {
        if (Strings.isBlank(param.getDepotId())) return;
        remove(new LambdaQueryWrapper<>(new DepotTruckPlateList(param.getDepotId())));
        List<DepotTruckPlateList> plateLists = new LinkedList<>();
        if (param.getWhitePlates() != null)
            param.getWhitePlates().forEach(one -> {
                plateLists.add(new DepotTruckPlateList(param.getDepotId(), "白", one));
            });
        if (param.getBlackPlates() != null)
            param.getBlackPlates().forEach(one -> {
                plateLists.add(new DepotTruckPlateList(param.getDepotId(), "黑", one));
            });
        if (!plateLists.isEmpty())
            saveBatch(plateLists);
    }

}
