package com.izouma.immall.service;

import com.izouma.immall.domain.User;
import com.izouma.immall.domain.VipUser;
import com.izouma.immall.enums.VipType;
import com.izouma.immall.exception.BusinessException;
import com.izouma.immall.repo.UserRepo;
import com.izouma.immall.repo.VipUserRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@AllArgsConstructor
public class VipUserService {
    @Autowired
    private VipUserRepo vipUserRepo;

    @Autowired
    private UserRepo userRepo;

    public VipUser buy(Long userId, VipType vipType) {
        if (userId == null) {
            new BusinessException("用户错误");
        }
        if (vipType == null) {
            new BusinessException("Vip类型错误");
        }
        if (vipUserRepo.findAllByUserId(userId) == null) {
            User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
            LocalDateTime now = LocalDateTime.now();
            VipUser vipUser = VipUser.builder()
                    .userId(userId)
                    .vipType(vipType)
                    .startTime(now)
                    .endTime(now.plusYears(1L))
                    .openId(user.getOpenId())
                    .enabled(true)
                    .build();
            return vipUser;
        }
        return null;
    }

    public Boolean isVip(Long userId, VipType vipType) {
        List<VipUser> vipUsers = vipUserRepo.findAllByUserId(userId);
        if (vipUsers != null) {
            LocalDateTime now = LocalDateTime.now();
            for (VipUser vip : vipUsers) {
                LocalDateTime endTime = vip.getEndTime();


            }
        }
        return true;
    }
}
