package com.philisense.www.service.impl;

import com.philisense.www.core.text.Convert;
import com.philisense.www.dao.JwtPermissionDAO;
import com.philisense.www.pojos.entity.JwtUser;
import com.philisense.www.service.JwtUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service("jwtUserDetailsService")
public class JwtUserDetailsServiceImpl implements JwtUserDetailsService {

    @Autowired
    private JwtPermissionDAO jwtPermissionDAO;


    @Override
    public UserDetails loadUserByUsername(String username){
        return createJwtUser(jwtPermissionDAO.getByUsername(username));
    }

    @Override
    public UserDetails loadUserByPhone(String phone) {
        Map<String, Object> vars = new HashMap<>();
        vars.put("phone", phone);
        return createJwtUser(jwtPermissionDAO.getUserByMap(vars));
    }

    @Override
    public UserDetails loadUserByEmail(String email) {
        Map<String, Object> vars = new HashMap<>();
        vars.put("email", email);
        return createJwtUser(jwtPermissionDAO.getUserByMap(vars));
    }

    @Override
    public UserDetails loadUserById(String userid) {
        Map<String, Object> vars = new HashMap<>();
        vars.put("userId", userid);
        return createJwtUser(jwtPermissionDAO.getUserByMap(vars));
    }

    @Override
    public Set<Map<String, Object>> getAuthoritiesNoGroupByUserId(String userid) {
        return jwtPermissionDAO.getAuthoritiesNoGroupByUserId(userid);
    }

    /**
     * 处理用户信息
     * @param userMap
     * @return
     */
    private UserDetails createJwtUser(Map<String,Object> userMap) {
        if (userMap == null|| userMap.isEmpty() ) {
            throw new RuntimeException("用户不存在或者密码错误");
        }

        String userId = Convert.toStr(userMap.get("user_id"), ""),
                usernameCn = Convert.toStr(userMap.get("user_name_cn"), ""),
                deptCode = Convert.toStr(userMap.get("dept_code"), ""),
                deptName = Convert.toStr(userMap.get("dept_name"), "");

        JwtUser jwtUser = new JwtUser(userId, usernameCn, deptCode, deptName, userMap);
        Set<Map<String, Object>> roles = jwtPermissionDAO.getAuthoritiesNoGroupByUserId(userId);
        jwtUser.setAuthorities(roles.stream().map(role -> new SimpleGrantedAuthority(Convert.toStr(role.get("auth_type"))))
                .collect(Collectors.toList()));
        return jwtUser;
    }
}
