package com.ruoyi.framework.web.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.basic.service.impl.YjAppUserServiceImpl;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.JpushClientUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.course.service.IScStudentService;
import com.ruoyi.system.service.SysTeacherService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */

@Component("AppUserDetailsServiceImpl")
public class AppUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class);

    @Autowired
    private YjAppUserServiceImpl userService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private IScStudentService studentService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        AppUser user = userService.selectAppUserByPhone(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        else if (user.getStatus() == 0)
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        List<Long> roles=new ArrayList<>();
        roles.add(107l);
        if (ObjectUtil.isNotEmpty(user.getManageAccountId())){
            //todo 角色ID；顾问：103 ；教练：104 ；店长：105 ；普通用户：107；

            SysUser sysUser=  sysUserService.selectUserById(user.getManageAccountId());
            if (ObjectUtil.isEmpty(sysUser)){
                log.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 所属租户异常，请联系管理员！");
            }
            List<SysRole> roles1=sysUser.getRoles();
            for (SysRole sysRole : roles1) {
                roles.add(sysRole.getRoleId());
            }
        }
        Long studentId=studentService.getStudentByAppUserId(user.getId());

//        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
//        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
//        if (!SecurityUtils.matchesPassword(password,user.getPassword())){
//            throw new RuntimeException(Constants.LOGIN_INFO.WRONG);
//        }

        SysUser user1=new SysUser();
        user1.setPassword(user.getPassword());
        passwordService.validate(user1);

        return createLoginUser(user,roles.toArray(new Long[roles.size()]) ,studentId);
    }

    public UserDetails createLoginUser(AppUser user, Long[] roles,Long studentId)
    {
        return new AppLoginUser(user.getId(),user.getUserName(), user.getManageAccountId(),roles,studentId, user);
    }
}
