package com.jeesharp.business.modules.mall.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallSeckillSkuConvert;
import com.jeesharp.business.modules.mall.dto.MallSeckillSkuSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallSeckillSku;
import com.jeesharp.business.modules.mall.service.MallSeckillSkuService;
import com.jeesharp.business.modules.mall.vo.MallSeckillSkuInfoVO;
import com.jeesharp.business.modules.mall.vo.MallSeckillSkuListVO;
import com.jeesharp.business.modules.mall.vo.MallSeckillSkuQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 秒杀商品 Application Service
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallSeckillSkuApplicationService {

    private final MallSeckillSkuService mallSeckillSkuService;

    public MallSeckillSkuInfoVO get(String id) {
        return MallSeckillSkuConvert.INSTANCE.toInfoVO(mallSeckillSkuService.get(id));
    }

    public PageRespVO<MallSeckillSkuListVO> findPage(Page<MallSeckillSku> page, MallSeckillSkuQueryVO query) {
        Page<MallSeckillSku> result = mallSeckillSkuService.findPage(page, query);
        return MallSeckillSkuConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MallSeckillSkuSaveDTO dto) {
        MallSeckillSku entity = MallSeckillSkuConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallSeckillSkuService.createSeckillSku(entity);
            return;
        }
        mallSeckillSkuService.updateSeckillSku(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        mallSeckillSkuService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 获取场次的秒杀商品列表
     */
    public List<MallSeckillSku> getSessionSkus(String sessionId) {
        return mallSeckillSkuService.getSessionSkus(sessionId);
    }

    /**
     * 检查商品是否还有秒杀库存
     */
    public boolean hasSeckillStock(String skuId, Integer quantity) {
        return mallSeckillSkuService.hasSeckillStock(skuId, quantity);
    }

    /**
     * 扣减秒杀库存
     */
    @Transactional(readOnly = false)
    public boolean deductSeckillStock(String skuId, Integer quantity) {
        return mallSeckillSkuService.deductSeckillStock(skuId, quantity);
    }
}
