package cn.iocoder.yudao.module.flow.service.outboundgoods;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.basic.api.dealerinfo.DealerInfoApi;
import cn.iocoder.yudao.module.basic.api.dealerinfo.dto.DealerInfoRespDTO;
import cn.iocoder.yudao.module.flow.controller.admin.outboundgoods.vo.OutboundGoodsCreateReqVO;
import cn.iocoder.yudao.module.flow.controller.admin.outboundgoods.vo.OutboundGoodsUpdateReqVO;
import cn.iocoder.yudao.module.flow.convert.outboundgoods.OutboundGoodsConvert;
import cn.iocoder.yudao.module.flow.dal.dataobject.outboundgoods.OutboundGoodsDO;
import cn.iocoder.yudao.module.flow.dal.mysql.outboundgoods.OutboundGoodsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.flow.enums.ErrorCodeConstants.OUTBOUND_GOODS_NOT_EXISTS;

/**
 * 出库单商品 Service 实现类
 *
 * @author 芋道源码
 */
@Service
public class OutboundGoodsServiceImpl implements OutboundGoodsService {

    @Resource
    private OutboundGoodsMapper outboundGoodsMapper;

    @Resource
    private DealerInfoApi dealerGoodsApi;


    @Override
    public Long createOutboundGoods(OutboundGoodsCreateReqVO createReqVO) {
        //检验经销商id是否存在，如果不存在则抛出异常。
        CommonResult<DealerInfoRespDTO> result = dealerGoodsApi.getDealerGoodsInfoByDealerGoodsId(createReqVO.getHarvestBatchId());
        DealerInfoRespDTO dto = result.getData();
        if (result.isError() || dto == null){
            throw exception(cn.iocoder.yudao.module.basic.enums.ErrorCodeConstants.VENDOR_INFO_NOT_EXISTS.getCode());
        }
        // 插入数据
        OutboundGoodsDO outboundGoods = OutboundGoodsConvert.INSTANCE.convert(createReqVO);

        outboundGoodsMapper.insert(outboundGoods);
        // 返回
        return outboundGoods.getId();
    }


    @Override
    public void updateOutboundGoods(OutboundGoodsUpdateReqVO updateReqVO) {
        // 校验存在
        validateOutboundGoodsExists(updateReqVO.getId());
        // 更新
        OutboundGoodsDO updateObj = OutboundGoodsConvert.INSTANCE.convert(updateReqVO);
        outboundGoodsMapper.updateById(updateObj);
    }

    @Override
    public void deleteOutboundGoods(Long id) {
        // 校验存在
        validateOutboundGoodsExists(id);
        // 删除
        outboundGoodsMapper.deleteById(id);
    }

    private void validateOutboundGoodsExists(Long id) {
        if (outboundGoodsMapper.selectById(id) == null) {
            throw exception(OUTBOUND_GOODS_NOT_EXISTS);
        }
    }
}
