package cn.iocoder.yudao.module.pms.service.iotsapstock;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotsapstock.vo.IotSapStockPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotsapstock.vo.IotSapStockSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotsapstock.IotSapStockDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotsapstock.IotSapStockMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_SAP_STOCK_NOT_EXISTS;

/**
 * PMS SAP 库存(通用库存/项目部库存) Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class IotSapStockServiceImpl implements IotSapStockService {

    @Resource
    private IotSapStockMapper iotSapStockMapper;

    @Override
    public Long createIotSapStock(IotSapStockSaveReqVO createReqVO) {
        // 插入
        IotSapStockDO iotSapStock = BeanUtils.toBean(createReqVO, IotSapStockDO.class);
        iotSapStockMapper.insert(iotSapStock);
        // 返回
        return iotSapStock.getId();
    }

    @Override
    public void updateIotSapStock(IotSapStockSaveReqVO updateReqVO) {
        // 校验存在
        validateIotSapStockExists(updateReqVO.getId());
        // 更新
        IotSapStockDO updateObj = BeanUtils.toBean(updateReqVO, IotSapStockDO.class);
        iotSapStockMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotSapStock(Long id) {
        // 校验存在
        validateIotSapStockExists(id);
        // 删除
        iotSapStockMapper.deleteById(id);
    }

    private void validateIotSapStockExists(Long id) {
        if (iotSapStockMapper.selectById(id) == null) {
            throw exception(IOT_SAP_STOCK_NOT_EXISTS);
        }
    }

    @Override
    public IotSapStockDO getIotSapStock(Long id) {
        return iotSapStockMapper.selectById(id);
    }

    @Override
    public PageResult<IotSapStockDO> getIotSapStockPage(IotSapStockPageReqVO pageReqVO) {
        return iotSapStockMapper.selectPage(pageReqVO);
    }

    @Override
    public List<IotSapStockDO> getIotSapStockList(IotSapStockPageReqVO pageReqVO) {
        return iotSapStockMapper.selectList(pageReqVO);
    }

    @Override
    public Long batchSetSafetyStock(List<IotSapStockSaveReqVO> sapStocks) {
        List<IotSapStockDO> sapStockDOs = new ArrayList<>();
        sapStocks.forEach(stock -> {
            IotSapStockDO tempBom = BeanUtils.toBean(stock, IotSapStockDO.class);
            sapStockDOs.add(tempBom);
        });
        iotSapStockMapper.updateBatch(sapStockDOs);
        return 1l;
    }

}