package com.ruoyi.web.service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.LoginCard;
import com.ruoyi.common.enums.ErrorCodes;
import com.ruoyi.common.enums.UserRegStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ErrorException;
import com.ruoyi.common.utils.PhoneUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.domain.DzSubject;
import com.ruoyi.dz.mapper.DzClassesMapper;
import com.ruoyi.dz.mapper.DzSchoolMapper;
import com.ruoyi.dz.mapper.DzSubjectMapper;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.enums.CardDistributeStatus;
import com.ruoyi.enums.CardTimeStatus;
import com.ruoyi.framework.web.service.SysPasswordService;
import com.ruoyi.framework.web.service.SysPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;

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

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IDzCardsService dzCardsService;
    @Autowired
    private DzSchoolMapper dzSchoolMapper;
    @Autowired
    private DzClassesMapper dzClassesMapper;
    @Autowired
    private DzSubjectMapper dzSubjectMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        boolean isPhoneLogin = PhoneUtils.isPhoneNumber(username);
        SysUser user = isPhoneLogin ? userService.selectUserByMobile(username) : userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ErrorException("账号不存在", ErrorCodes.UnRegister);
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被关闭.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        if(!isPhoneLogin) {
            passwordService.validate(user);
        }
        LoginCard card = new LoginCard();
        if(null != user.getCardId()) {
            DzCards dzCards = dzCardsService.selectDzCardsByCardId(user.getCardId());
            BeanUtils.copyProperties(dzCards, card, "password");
            if(null != dzCards.getSchoolId()) {
                card.setSchoolName(dzSchoolMapper.selectDzSchoolById(dzCards.getSchoolId()).getName());
            }
            if(null != dzCards.getClassId()) {
                card.setClassName(dzClassesMapper.selectDzClassesByClassId(dzCards.getClassId()).getName());
            }
            Date nowDate = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
            if (UserRegStatus.Student.equals(user.getRegStatus()) && (CardDistributeStatus.Close.getVal().equals(dzCards.getDistributeStatus())
                    || !CardTimeStatus.Valid.getVal().equals(dzCards.getTimeStatus())
                    || (null != dzCards.getOutDate() && dzCards.getOutDate().getTime() < nowDate.getTime()))) {
                // 过期后处理降级
                SysUser upUser = new SysUser();
                upUser.setUserId(user.getUserId());
                upUser.setRegStatus(UserRegStatus.User);
                user.setRegStatus(UserRegStatus.User);
                userService.updateUserProfile(upUser);
            }
        }
        if(null != user.getExamMajor()) {
            DzSubject dzSubject = dzSubjectMapper.selectDzSubjectBySubjectId(user.getExamMajor().longValue());
            user.setExamMajorName(null != dzSubject ? dzSubject.getSubjectName() : "");
        }
        LoginUser loginUser = createLoginUser(user, card);
        if(isPhoneLogin) {
            user.setPassword(UserConstants.LOGIN_SMS_PASS);
            loginUser.setLoginUserName(user.getPhonenumber());
        }
        return loginUser;
    }

    public LoginUser createLoginUser(SysUser user, LoginCard card)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, card, permissionService.getMenuPermission(user));
    }
}
