package com.jeesharp.business.modules.mall.service.impl;

import com.jeesharp.business.modules.mall.entity.MallSeckillSku;
import com.jeesharp.business.modules.mall.mapper.MallSeckillSkuMapper;
import com.jeesharp.business.modules.mall.service.MallSeckillSkuService;
import com.jeesharp.business.modules.mall.vo.MallSeckillSkuQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 秒杀商品 Service 实现类
 */
@Service
@Transactional(readOnly = true)
public class MallSeckillSkuServiceImpl extends CrudService<MallSeckillSkuMapper, MallSeckillSku, MallSeckillSkuQueryVO> implements MallSeckillSkuService {

    private static final int ENABLED_STATUS = 1;
    private static final String IDS_SEPARATOR = ",";

    @Override
    @Transactional(readOnly = false)
    public void createSeckillSku(MallSeckillSku entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSeckillSku(MallSeckillSku entity) {
        update(entity);
    }

    @Override
    public List<MallSeckillSku> getSessionSkus(String sessionId) {
        MallSeckillSkuQueryVO query = new MallSeckillSkuQueryVO();
        query.setSessionId(sessionId);
        query.setStatus(ENABLED_STATUS);
        return findList(query);
    }

    @Override
    public boolean hasSeckillStock(String skuId, Integer quantity) {
        MallSeckillSkuQueryVO query = new MallSeckillSkuQueryVO();
        query.setSkuId(skuId);
        query.setStatus(ENABLED_STATUS);
        List<MallSeckillSku> seckillSkus = findList(query);
        if (seckillSkus.isEmpty()) {
            return false;
        }
        MallSeckillSku seckillSku = seckillSkus.get(0);
        return seckillSku.getSeckillStock() - seckillSku.getSoldCount() >= quantity;
    }

    @Override
    @Transactional(readOnly = false)
    public boolean deductSeckillStock(String skuId, Integer quantity) {
        MallSeckillSkuQueryVO query = new MallSeckillSkuQueryVO();
        query.setSkuId(skuId);
        query.setStatus(ENABLED_STATUS);
        List<MallSeckillSku> seckillSkus = findList(query);
        if (seckillSkus.isEmpty()) {
            return false;
        }
        MallSeckillSku seckillSku = seckillSkus.get(0);
        int remainingStock = seckillSku.getSeckillStock() - seckillSku.getSoldCount();
        if (remainingStock < quantity) {
            return false;
        }
        seckillSku.setSoldCount(seckillSku.getSoldCount() + quantity);
        update(seckillSku);
        return true;
    }
}
