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.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.dto.SkuPropertyDTO;
import com.fzm.mall.server.admin.goods_center.entity.vo.SkuPropertyVO;
import com.fzm.mall.server.admin.goods_center.mapper.SkuPropMapper;
import com.fzm.mall.server.admin.goods_center.model.SkuProp;
import com.fzm.mall.server.admin.goods_center.service.ISkuPropService;
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;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangp
 * @date 2021/3/4 16:06
 * @description 商品规格属性 服务实现类
 * @since JDK 1.8
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SkuPropServiceImpl extends ServiceImpl<SkuPropMapper, SkuProp> implements ISkuPropService {

    private final DozerBeanMapper beanMapper;

    @Override
    public void add(List<SkuPropertyDTO> pDTOs, String skuId) {
        List<SkuProp> skuProps = new ArrayList<>();

        for (SkuPropertyDTO pDTO : pDTOs) {
            SkuProp skuProp = beanMapper.map(pDTO, SkuProp.class);
            skuProp.setSkuId(skuId);
            skuProps.add(skuProp);
        }

        if (!saveBatch(skuProps)) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }
    }

    @Override
    public List<SkuPropertyVO> getBySkuId(String skuId) {
        QueryWrapper<SkuProp> qw = new QueryWrapper<>();
        qw.lambda().eq(SkuProp::getSkuId, skuId);
        List<SkuPropertyVO> propertyVOList = list(qw).stream()
                .map(v -> beanMapper.map(v, SkuPropertyVO.class))
                .collect(Collectors.toList());
        return propertyVOList;
    }

    @Override
    public void removeBySkuId(String skuId) {
        LambdaQueryWrapper<SkuProp> qw = new LambdaQueryWrapper<>();
        qw.eq(SkuProp::getSkuId, skuId);
        remove(qw);
    }
}
