package com.fzm.mall.server.admin.goods_center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.goods_center.entity.dto.PointsExchangeDTO;
import com.fzm.mall.server.admin.goods_center.entity.vo.PointsExchangeVO;
import com.fzm.mall.server.admin.goods_center.model.PointsExchange;
import com.fzm.mall.server.admin.goods_center.mapper.PointsExchangeMapper;
import com.fzm.mall.server.admin.goods_center.service.IPointsExchangeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.util.UUIDUtil;
import lombok.RequiredArgsConstructor;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wangp
 * @date 2021/3/4 16:06
 * @description 积分兑换 服务实现类
 * @since JDK 1.8
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PointsExchangeServiceImpl extends ServiceImpl<PointsExchangeMapper, PointsExchange> implements IPointsExchangeService {

    private final DozerBeanMapper beanMapper;

    @Override
    public void add(PointsExchangeDTO pointsExchangeDTO, String goodsId) {
        if (pointsExchangeDTO.getStock() < 0 || pointsExchangeDTO.getPNum() < 0) {
            throw new MyException(MallResponseError.VALUE_LT_0_ERROR);
        }

        PointsExchange exchange = beanMapper.map(pointsExchangeDTO, PointsExchange.class);
        exchange.setPeId(UUIDUtil.getUUID());
        exchange.setGoodsId(goodsId);
        if (!save(exchange)) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }
    }

    @Override
    public void edit(PointsExchangeDTO pointsExchangeDTO, String goodsId) {
        if (pointsExchangeDTO.getStock() < 0 || pointsExchangeDTO.getPNum() < 0) {
            throw new MyException(MallResponseError.VALUE_LT_0_ERROR);
        }

        UpdateWrapper<PointsExchange> uw = new UpdateWrapper<>();
        uw.lambda().eq(PointsExchange::getGoodsId, goodsId);

        PointsExchange exchange = beanMapper.map(pointsExchangeDTO, PointsExchange.class);

        if (!update(exchange, uw)) {
            throw new MyException(MallResponseError.UPDATE_ERROR);
        }
    }

    @Override
    public PointsExchangeVO getByGoodsId(String goodsId) {
        QueryWrapper<PointsExchange> qw = new QueryWrapper<>();
        qw.lambda().eq(PointsExchange::getGoodsId, goodsId);
        PointsExchange pointsExchange = getOne(qw);
        return beanMapper.map(pointsExchange, PointsExchangeVO.class);
    }
}
