package cn.iocoder.yudao.module.member.service.storegoods;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.member.controller.admin.storegoods.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoods.StoreGoodsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.member.dal.mysql.storegoods.StoreGoodsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 商品 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class StoreGoodsServiceImpl implements StoreGoodsService {

    @Resource
    private StoreGoodsMapper storeGoodsMapper;

    @Override
    public Integer createStoreGoods(StoreGoodsSaveReqVO createReqVO) {
        // 插入
        StoreGoodsDO storeGoods = BeanUtils.toBean(createReqVO, StoreGoodsDO.class);
        storeGoodsMapper.insert(storeGoods);
        // 返回
        return storeGoods.getGoodId();
    }

    @Override
    public void updateStoreGoods(StoreGoodsSaveReqVO updateReqVO) {
        // 校验存在
        validateStoreGoodsExists(updateReqVO.getGoodId());
        // 更新
        StoreGoodsDO updateObj = BeanUtils.toBean(updateReqVO, StoreGoodsDO.class);
        storeGoodsMapper.updateById(updateObj);
    }

    @Override
    public void deleteStoreGoods(Integer id) {
        // 校验存在
        validateStoreGoodsExists(id);
        // 删除
        storeGoodsMapper.deleteById(id);
    }

    private void validateStoreGoodsExists(Integer id) {
        if (storeGoodsMapper.selectById(id) == null) {
            throw exception(STORE_GOODS_NOT_EXISTS);
        }
    }

    @Override
    public StoreGoodsDO getStoreGoods(Integer id) {
        return storeGoodsMapper.selectById(id);
    }

    @Override
    public PageResult<StoreGoodsDO> getStoreGoodsPage(StoreGoodsPageReqVO pageReqVO) {
        return storeGoodsMapper.selectPage(pageReqVO);
    }

    @Override
    public List<StoreGoodsDO> getAll(List<Integer> goodsIds) {
        if (CollectionUtil.isEmpty(goodsIds)) {
            return storeGoodsMapper.selectList();
        }else {
            return storeGoodsMapper.selectList(new LambdaQueryWrapper<StoreGoodsDO>().in(StoreGoodsDO::getGoodId, goodsIds));
        }

    }
}