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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.vo.SalesTopTenVO;
import com.fzm.mall.server.admin.goods_center.model.Count;
import com.fzm.mall.server.admin.goods_center.mapper.CountMapper;
import com.fzm.mall.server.admin.goods_center.model.Spu;
import com.fzm.mall.server.admin.goods_center.service.ICountService;
import com.fzm.mall.server.admin.goods_center.service.ISpuService;
import com.fzm.mall.server.admin.order.model.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商品统计信息表 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-04-02
 */
@Service
@Transactional
public class CountServiceImpl extends ServiceImpl<CountMapper, Count> implements ICountService {

    @Autowired
    private ISpuService spuService;

    @Override
    public void init(String goodsId) {
        Count count = new Count();
        count.setGoodsId(goodsId);
        if (!save(count)) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }
    }

    /**
     * 商品订单退款-销量还原
     */
    @Override
    public void restoreSales(List<OrderDetail> orderDetailList) {
        orderDetailList.forEach(orderDetail -> {
            Count count = getOne(new QueryWrapper<Count>().eq("goods_id", orderDetail.getGoodsId()));
            Integer sales = count.getSales() - orderDetail.getNumber();
            count.setSales(sales > 0 ? sales : 0);

            UpdateWrapper<Count> updateWrapper = new UpdateWrapper<Count>().eq("goods_id", orderDetail.getGoodsId())
                    .eq("update_time", count.getUpdateTime());
            boolean update = update(count, updateWrapper);
            if (!update) {
                throw new MyException(MallResponseError.UPDATE_FAIL);
            }
        });
    }

    @Override
    public List<SalesTopTenVO> salesTopTen(String merchantId) {
        List<SalesTopTenVO> salesTopTenVOS = baseMapper.salesTopTen(merchantId);
        int i = 1;
        for (SalesTopTenVO vo : salesTopTenVOS) {
            Spu spu = spuService.getByGoodsId(vo.getGoodsId());
            vo.setSort(i++);
            vo.setGoodsId(null);
            vo.setGoodsName(spu.getName());
        }
        return salesTopTenVOS;
    }

    @Override
    public void removeByGoodsId(String goodsId) {
        LambdaQueryWrapper<Count> qw = new LambdaQueryWrapper<>();
        qw.eq(Count::getGoodsId, goodsId);
        remove(qw);
    }
}
