package com.ruoyi.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.UserRegStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.enums.CardTimeStatus;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Service
public class CommService {
    private final ISysConfigService configService;
    private final IDzCardsService cardsService;

    public CommService(ISysConfigService configService, IDzCardsService cardsService) {
        this.configService = configService;
        this.cardsService = cardsService;
    }


    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }

    public void requireVip() {
        if (true){
            return;
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!UserRegStatus.Student.equals(user.getRegStatus())) {
            throw new CustomException("没有权限，请开通VIP", 405);
        }
        DzCards card = cardsService.selectDzCardsByCardId(user.getCardId());
        Date nowDate = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
        if (!CardTimeStatus.Valid.getVal().equals(card.getTimeStatus()) || (null != card.getOutDate() && card.getOutDate().getTime() < nowDate.getTime())) {
            throw new CustomException("没有权限，请开通VIP", 405);
        }
    }
}
