package com.fjhx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.enums.WarehouseTypeEnum;
import com.fjhx.entity.Warehouse;
import com.fjhx.mapper.WarehouseMapper;
import com.fjhx.service.WarehouseService;
import com.fjhx.utils.Assert;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 仓库 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-08-10
 */
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {

    @Override
    public void addOrEdit(Warehouse warehouse) {

        // 验证仓库名称是否为空
        String name = warehouse.getName();
        Assert.notEmpty(name, "仓库名称不能为空");

        Long id = warehouse.getId();

        // 验证仓库名称是否重复
        Long count = count(Wrappers.<Warehouse>lambdaQuery()
                .eq(Warehouse::getName, name)
                .eq(BaseEntity::getTenantId, AuthUtil.getTenantId())
                .ne(ObjectUtil.isNotEmpty(id), BaseEntity::getId, id)
        );
        Assert.eqZero(count, "仓库名称重复");

        // 如果是添加，且未选仓库类型，默认赋值普通仓库
        Integer type = warehouse.getType();
        if (ObjectUtil.isAllEmpty(id, type)) {
            warehouse.setType(WarehouseTypeEnum.ORDINARY.getType());
        }

        saveOrUpdate(warehouse);

    }

}
