package com.apobates.forum.member.impl.service;

import com.apobates.forum.member.api.dao.MemberDao;
import com.apobates.forum.member.api.dao.MemberVipExchangeRecordsDao;
import com.apobates.forum.member.api.service.MemberVipExchangeRecordsService;
import com.apobates.forum.member.entity.MemberGroupEnum;
import com.apobates.forum.member.entity.MemberVipExchangeRecords;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.stream.Stream;

/**
 *
 * @author xiaofanku
 * @since 20200921
 */
@Service
public class MemberVipExchangeRecordsServiceImpl implements MemberVipExchangeRecordsService {
    @Autowired
    private MemberVipExchangeRecordsDao memberVipExchangeRecordsDao;
    @Autowired
    private MemberDao memberDao;
    private final static Logger logger = LoggerFactory.getLogger(MemberVipExchangeRecordsServiceImpl.class);

    @Override
    public Page<MemberVipExchangeRecords> getAll(LocalDateTime start, LocalDateTime finish, Pageable pageable) {
        return memberVipExchangeRecordsDao.findAll(start, finish, pageable);
    }

    @Override
    public Page<MemberVipExchangeRecords> getAll(long memberId, Pageable pageable) {
        return memberVipExchangeRecordsDao.findAllByMember(memberId, pageable);
    }

    @Override
    public Page<MemberVipExchangeRecords> getAll(Pageable pageable) {
        return memberVipExchangeRecordsDao.findAll(pageable);
    }

    @Override
    public Stream<MemberVipExchangeRecords> getRecent(int size) {
        return memberVipExchangeRecordsDao.findAllOfRecent(size);
    }

    @Override
    public Optional<Boolean> expired(long id) throws IllegalArgumentException, IllegalStateException {
        MemberVipExchangeRecords obj = memberVipExchangeRecordsDao.findOne(id).orElseThrow(()->new IllegalArgumentException("VIP交易记录不存在"));
        //
        if (DateTimeUtils.isFeatureDate(obj.getLapseDateTime())) {
            throw new IllegalStateException("VIP会员未到期,不可以作废");
        }
        Optional<Boolean> result = memberVipExchangeRecordsDao.expired(obj.getId());
        result.ifPresent(bol-> {
            if(bol){ memberDao.editMemberGroup(obj.getMemberId(), MemberGroupEnum.CARD);}
        });
        return result;
    }
}
