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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallSeckillSessionConvert;
import com.jeesharp.business.modules.mall.dto.MallSeckillSessionSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallSeckillSession;
import com.jeesharp.business.modules.mall.service.MallSeckillSessionService;
import com.jeesharp.business.modules.mall.vo.MallSeckillSessionInfoVO;
import com.jeesharp.business.modules.mall.vo.MallSeckillSessionListVO;
import com.jeesharp.business.modules.mall.vo.MallSeckillSessionQueryVO;
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 MallSeckillSessionApplicationService {

    private final MallSeckillSessionService mallSeckillSessionService;

    public MallSeckillSessionInfoVO get(String id) {
        return MallSeckillSessionConvert.INSTANCE.toInfoVO(mallSeckillSessionService.get(id));
    }

    public PageRespVO<MallSeckillSessionListVO> findPage(Page<MallSeckillSession> page, MallSeckillSessionQueryVO query) {
        Page<MallSeckillSession> result = mallSeckillSessionService.findPage(page, query);
        return MallSeckillSessionConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MallSeckillSessionSaveDTO dto) {
        MallSeckillSession entity = MallSeckillSessionConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallSeckillSessionService.createSession(entity);
            return;
        }
        mallSeckillSessionService.updateSession(entity);
    }

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

    /**
     * 获取当前进行中的秒杀场次
     */
    public List<MallSeckillSession> getActiveSessions() {
        return mallSeckillSessionService.getActiveSessions();
    }

    /**
     * 更新场次状态（定时任务调用）
     */
    @Transactional(readOnly = false)
    public void updateSessionStatus() {
        mallSeckillSessionService.updateSessionStatus();
    }
}
