package com.sv.service.api;

import com.sv.entity.MemberEnterVenueLog;
import com.sv.mapper.MemberEnterVenueLogMapper;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Service - 篮球进场订单
 *
 * @author zhaoziyu
 * @since 2018-08-11
 */
@Service
@Transactional(readOnly = true)
public class MemberEnterVenueLogService extends BaseServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(MemberEnterVenueLogService.class);

    @Resource
    private MemberEnterVenueLogMapper memberEnterVenueLogMapper;

    /**
     * 获取用户最后的进场记录
     *
     * @param memberId
     * @return
     */
    public MemberEnterVenueLog findMemberLastLog(Integer memberId, Integer venueId) {
        return memberEnterVenueLogMapper.findLastByMember(memberId, venueId);
    }

    /**
     * 获取用户最后的进场记录
     *
     * @param memberId
     * @return
     */
    public MemberEnterVenueLog findMemberLastLogNoType(Integer memberId, Integer venueId) {
        return memberEnterVenueLogMapper.findLastNoTypeByMember(memberId, venueId);
    }

    /**
     * 查看该免费卡今天是否可用
     *
     * @param memberCardId
     * @return
     */
    public boolean isFreeCardUseful(Integer memberCardId) {
        String today = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        Integer count = memberEnterVenueLogMapper.countByMemberCardId(today, memberCardId);
        return count <= 0;
    }

    @Transactional
    public void save(MemberEnterVenueLog memberEnterVenueLog) {
        memberEnterVenueLogMapper.insert(memberEnterVenueLog);
    }

    /**
     * 查看用户今天连续两次进场多少次
     *
     * @param memberId
     * @param venueId
     * @param date
     */

    public Integer countEnterByDate(Integer memberId, Integer venueId, Date date) {
        List<MemberEnterVenueLog> logs = memberEnterVenueLogMapper.findMemberEnterLogByDate(memberId, venueId, DateFormatUtils.format(date, "yyyy-MM-dd"));
        int count = 0;
        if (CollectionUtils.isNotEmpty(logs)) {
            int c = 0;
            for (MemberEnterVenueLog log : logs) {
                //查看今天是否有连续进场
                if (log.getType() == 0) {
                    //进场
                    c++;
                } else {
                    c = 0;
                }
                if (c >= 2) {
                    count++;
                    c = 0;
                }
            }
        }
        return count;
    }

}

