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

import com.jeesharp.business.modules.mall.entity.MallSeckillSession;
import com.jeesharp.business.modules.mall.mapper.MallSeckillSessionMapper;
import com.jeesharp.business.modules.mall.service.MallSeckillSessionService;
import com.jeesharp.business.modules.mall.vo.MallSeckillSessionQueryVO;
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.Date;
import java.util.List;

/**
 * 秒杀场次 Service 实现类
 */
@Service
@Transactional(readOnly = true)
public class MallSeckillSessionServiceImpl extends CrudService<MallSeckillSessionMapper, MallSeckillSession, MallSeckillSessionQueryVO> implements MallSeckillSessionService {

    private static final int NOT_STARTED_STATUS = 0;
    private static final int ACTIVE_STATUS = 1;
    private static final int ENDED_STATUS = 2;
    private static final String IDS_SEPARATOR = ",";

    @Override
    @Transactional(readOnly = false)
    public void createSession(MallSeckillSession entity) {
        entity.setStatus(resolveStatus(entity, new Date()));
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSession(MallSeckillSession entity) {
        entity.setStatus(resolveStatus(entity, new Date()));
        update(entity);
    }

    @Override
    public List<MallSeckillSession> getActiveSessions() {
        MallSeckillSessionQueryVO query = new MallSeckillSessionQueryVO();
        query.setStatus(ACTIVE_STATUS);
        return findList(query);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSessionStatus() {
        Date now = new Date();
        List<MallSeckillSession> allSessions = findList(new MallSeckillSessionQueryVO());
        for (MallSeckillSession session : allSessions) {
            Integer newStatus = resolveStatus(session, now);
            if (!newStatus.equals(session.getStatus())) {
                session.setStatus(newStatus);
                update(session);
            }
        }
    }

    private Integer resolveStatus(MallSeckillSession session, Date now) {
        if (now.before(session.getStartTime())) {
            return NOT_STARTED_STATUS;
        }
        if (now.after(session.getEndTime())) {
            return ENDED_STATUS;
        }
        return ACTIVE_STATUS;
    }
}
