package cc.mrbird.febs.auth.service.impl;

import cc.mrbird.febs.auth.manager.UserManager;
import com.ruoyi.common.core.domain.*;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.utils.FebsUtil;
import com.ruoyi.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.core.domain.R.SUCCESS;

/**
 * oauth2用户信息加载方法，加上统一认证
 * @author gx
 */
@Service
@RequiredArgsConstructor
public class FebsUserDetailServiceImpl implements UserDetailsService {

    @Value("${unifiedAuth:false}")
    private boolean unifiedAuth;

    private final UserManager userManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
        String grantType = httpServletRequest.getParameter(ParamsConstant.GRANT_TYPE);
        R<LoginUser> userInfo;
        if (unifiedAuth && "password".equals(grantType)) {
            userInfo = userManager.findByPhone(username);
        } else {
            userInfo = userManager.findByName(username);
        }
        if (userInfo != null && userInfo.getCode() == SUCCESS && userInfo.getData() != null) {
            LoginUser loginUser = userInfo.getData();
            loginUser.setLoginTime(new Date().getTime());
            SysUser user = userInfo.getData().getSysUser();
            List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(StringConstant.COMMA, loginUser.getPermissions()));
            boolean notLocked = StringUtils.equals(UserStatus.OK.getCode(), user.getStatus());
            String password = user.getPassword();
            Oauth2LoginUser authUser = new Oauth2LoginUser(user.getUserName(), password, true, true, true, notLocked,
                    grantedAuthorities);
            BeanUtils.copyProperties(loginUser, authUser);
            authUser.setUserId(loginUser.getUserid());
            return authUser;
        } else {
            throw new UsernameNotFoundException("");
        }
    }
}
