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

import com.jeesharp.business.modules.mall.entity.MallPresale;
import com.jeesharp.business.modules.mall.mapper.MallPresaleMapper;
import com.jeesharp.business.modules.mall.service.MallPresaleService;
import com.jeesharp.business.modules.mall.vo.MallPresaleQueryVO;
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
@Transactional(readOnly = true)
public class MallPresaleServiceImpl extends CrudService<MallPresaleMapper, MallPresale, MallPresaleQueryVO> implements MallPresaleService {

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

    @Override
    @Transactional(readOnly = false)
    public void createPresale(MallPresale entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updatePresale(MallPresale entity) {
        update(entity);
    }

    @Override
    public MallPresale getBySpuId(String spuId) {
        MallPresaleQueryVO query = new MallPresaleQueryVO();
        query.setSpuId(spuId);
        query.setStatus(ENABLED_STATUS);
        List<MallPresale> presales = findList(query);
        return presales.isEmpty() ? null : presales.get(0);
    }

    @Override
    public boolean isInPresalePeriod(String spuId) {
        MallPresale presale = getBySpuId(spuId);
        if (presale == null) {
            return false;
        }
        Date now = new Date();
        return now.after(presale.getTailStartTime()) && now.before(presale.getTailEndTime());
    }

    @Override
    public boolean canPayTail(String spuId) {
        MallPresale presale = getBySpuId(spuId);
        if (presale == null) {
            return false;
        }
        Date now = new Date();
        return now.after(presale.getTailStartTime()) && now.before(presale.getTailEndTime());
    }
}
