package com.njzscloud.dispose.wh.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.dispose.wh.mapper.InventoryMapper;
import com.njzscloud.dispose.wh.pojo.entity.InventoryEntity;
import com.njzscloud.dispose.wh.pojo.param.AddInventoryParam;
import com.njzscloud.dispose.wh.pojo.param.SearchInventoryParam;
import com.njzscloud.dispose.wh.pojo.result.SearchInventoryResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 库存信息
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InventoryService extends ServiceImpl<InventoryMapper, InventoryEntity> {

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(AddInventoryParam addInventoryParam) {
        if (this.exists(Wrappers.<InventoryEntity>lambdaQuery().eq(InventoryEntity::getWarehouseId, addInventoryParam.getWarehouseId())
            .eq(InventoryEntity::getGoodsId, addInventoryParam.getGoodsId())
            .eq(InventoryEntity::getDeleted, Boolean.FALSE))) {
            throw Exceptions.clierr("该产品已存在仓库，无需新增");
        }
        InventoryEntity entity = BeanUtil.copyProperties(addInventoryParam, InventoryEntity.class);
        this.save(entity);
    }

    /**
     * 修改
     */
    public void modify(InventoryEntity inventoryEntity) {
        this.updateById(inventoryEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public SearchInventoryResult detail(Long id) {
        return baseMapper.detail(id);
    }

    /**
     * 分页查询
     */
    public PageResult<SearchInventoryResult> paging(PageParam pageParam, SearchInventoryParam param) {
        Long warehouseId = param.getWarehouseId();
        Long goodsId = param.getGoodsId();
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.query()
            .eq("wi.deleted", 0)
            .eq(warehouseId != null, "wi.warehouse_id", warehouseId)
            .like(StrUtil.isNotBlank(param.getWarehouseName()), "ww.warehouse_name", param.getWarehouseName())
            .eq(goodsId != null, "wi.goods_id", goodsId)
            .like(StrUtil.isNotBlank(param.getGoodsName()), "gg.goods_name", param.getGoodsName())
            .like(StrUtil.isNotBlank(param.getLocation()), "wi.location", param.getLocation())
        ));
    }
}
