package cn.reghao.tnb.content.app.mall.service;

import cn.reghao.file.api.iface.OssService;
import cn.reghao.jutil.jdk.db.PageList;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.tool.id.SnowFlake;
import cn.reghao.oss.sdk.model.dto.media.ImageInfo;
import cn.reghao.tnb.content.api.dto.TaobaoItem;
import cn.reghao.tnb.content.app.mall.db.mapper.ProductMapper;
import cn.reghao.tnb.content.app.mall.db.repository.MallRepository;
import cn.reghao.tnb.content.app.mall.model.dto.ProductAddDto;
import cn.reghao.tnb.content.app.mall.model.po.Product;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2024-04-16 11:00:17
 */
@Service
public class ProductService {
    @DubboReference(check = false)
    private OssService ossService;

    private final int pageSize = 12;
    private final SnowFlake idGenerator;
    private final ProductMapper productMapper;
    private final MallRepository mallRepository;

    public ProductService(ProductMapper productMapper, MallRepository mallRepository) {
        this.idGenerator = new SnowFlake(1L, 1L);
        this.productMapper = productMapper;
        this.mallRepository = mallRepository;
    }

    public void add(TaobaoItem taobaoItem) {
        Product product = new Product(taobaoItem);
        productMapper.save(product);
    }

    public Result addProduct(ProductAddDto productAddDto) throws Exception {
        String coverFileId = productAddDto.getCoverFileId();
        int coverChannelId = productAddDto.getCoverChannelId();
        ImageInfo imageInfo = ossService.getImageInfo(coverChannelId, coverFileId);
        if (imageInfo == null) {
            String errMsg = String.format("封面文件 %s 在 oss 中不存在", coverFileId);
            return Result.fail(errMsg);
        }

        long productId = idGenerator.nextId();
        String coverUrl = imageInfo.getUrl();
        Product product = new Product(productAddDto, productId, coverUrl);
        productMapper.save(product);
        return Result.success();
    }

    public PageList<Product> getPage(int pageNumber) {
        int total = 1;
        List<Product> list = productMapper.findAll();
        return PageList.pageList(pageNumber, pageSize, total, list);
    }

    public Product getProduct(Long itemId) {
        return mallRepository.getProduct(itemId);
    }
}
