package com.tuoheng.service.impl;

import com.tuoheng.mapper.AuthoritiesMapper;
import com.tuoheng.mapper.UserMapper;
import com.tuoheng.model.dto.UserBaseInfoDto;
import com.tuoheng.model.param.CreateUserDto;
import com.tuoheng.model.param.GetUserInfoDto;
import com.tuoheng.model.po.AuthoritiesPo;
import com.tuoheng.model.po.UserPo;
import com.tuoheng.service.UserSevice;
import com.tuoheng.until.JsonResult;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcUserInfoAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.expression.Lists;

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

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/10/8 11:35
 */
@Service
public class UserServiceImpl implements UserSevice {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthoritiesMapper authoritiesMapper;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult createUser(CreateUserDto createUserDto){
        UserPo userPo = new UserPo()
                .setUsername(createUserDto.getUsername())
                .setPassword("{bcrypt}" + new BCryptPasswordEncoder().encode(createUserDto.getPassword()));
        userMapper.insertUser(userPo);

        List<AuthoritiesPo> authoritiesPos = new ArrayList<>();
        for(String authority : createUserDto.getAuthorities()){
            AuthoritiesPo authoritiesPo = new AuthoritiesPo()
                    .setUserId(userPo.getId())
                    .setUsername(createUserDto.getUsername())
                    .setAuthority(authority);
            authoritiesPos.add(authoritiesPo);
        }
        authoritiesMapper.batchInsert(authoritiesPos);
        return JsonResult.success(userPo.getId());
    }

    @Override
    public JsonResult getUserInfo(GetUserInfoDto getUserInfoDto){
        UserBaseInfoDto userBaseInfoDto = userMapper.getMpUserInfo(getUserInfoDto.getUsername());

        return JsonResult.success(userBaseInfoDto);
    }


}
