package com.wzj.soopin.goods.business;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzj.soopin.goods.convert.ProductConvert;
import com.wzj.soopin.goods.convert.SkuConvert;
import com.wzj.soopin.goods.domain.bo.ProductBo;
import com.wzj.soopin.goods.domain.entity.Product;
import com.wzj.soopin.goods.domain.entity.Sku;
import com.wzj.soopin.goods.domain.vo.ProductVO;
import com.wzj.soopin.goods.service.ProductService;
import com.wzj.soopin.goods.service.SkuService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.web.core.BusinessImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
@AllArgsConstructor
public class ProductBusinessImpl extends BusinessImpl<ProductService, ProductConvert, ProductVO, ProductBo, Product> implements IProductBusiness {

    private final ProductService productService;
    private final SkuService skuService;
    private final SkuConvert skuConvert;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(ProductBo bo) {

        Product product = converter.toPo(bo);
        product.setType(1);
        product.setSales("0");
        productService.saveOrUpdate(product);
        //清理掉旧的SKU
        skuService.remove(new LambdaQueryWrapper<Sku>().eq(Sku::getProductId, product.getId()));
        // 2. 保存SKU列表
        if (CollectionUtils.isNotEmpty(bo.getSkuList())) {
            List<Sku> skus = bo.getSkuList().stream()
                .map(skuBO -> skuConvert.toPo(skuBO))
                .collect(Collectors.toList());
            skuService.saveBatch(skus);
        }

        return false;
    }


    @Override
    public boolean audit(Long id, Integer authFlag, String reasons) {
        Product productToUpdate = productService.getById(id);
        if (productToUpdate == null) {
            throw new RuntimeException("商品不存在");
        }
        productToUpdate.setAuthFlag(authFlag);
        productToUpdate.setReasons(reasons);
        productService.updateById(productToUpdate);
        return true;
    }

    @Override
    public boolean publish(Long id, Integer publishStatus) {
        Product product = productService.getById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        product.setPublishStatus(publishStatus);
        productService.updateById(product);
        return true;
    }

    @Override
    public IPage<ProductVO> getRecommendPage(Page<Product> page) {
        return productService.getRecommendPage(page);
    }
}
