package com.njcn.product.auth.service;

import cn.hutool.core.bean.BeanUtil;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.product.auth.pojo.bo.BusinessUser;
import com.njcn.product.auth.pojo.dto.UserDTO;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @author hongawen
 * <p>
 * 自定义用户认证和授权
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements CustomUserDetailsService {

    private final IUserService userService;


    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        String clientId = RequestUtil.getOAuth2ClientId();
        BusinessUser businessUser = new BusinessUser(loginName, null, null);
        businessUser.setClientId(clientId);
        UserDTO userDTO = userService.getUserByName(loginName);
        LogUtil.njcnDebug(log, "用户认证时，用户名：{}获取用户信息：{}", loginName, userDTO.toString());
        //成功获取用户信息
        BeanUtil.copyProperties(userDTO, businessUser, true);
        //处理头像
//        dealHead(businessUser);
        businessUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", userDTO.getRoleName())));
        return businessUser;
    }


    @Override
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        String clientId = RequestUtil.getOAuth2ClientId();
        BusinessUser businessUser = new BusinessUser(phone, null, null);
        businessUser.setClientId(clientId);
        UserDTO userDTO = userService.loadUserByPhone(phone);
        LogUtil.njcnDebug(log, "用户验证码认证时，用户名：{}获取用户信息：{}", phone, userDTO.toString());
        //成功获取用户信息
        BeanUtil.copyProperties(userDTO, businessUser, true);
//        dealHead(businessUser);
        businessUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", userDTO.getRoleName())));
        return businessUser;
    }



}
