package com.zcxk.service;



import com.alibaba.fastjson.JSONObject;
import com.zcxk.dao.UserMapper;
import com.zcxk.dto.UserDto;
import com.zcxk.model.LoginUser;

import com.zcxk.model.ResultStatus;

import com.zcxk.security.exception.SecurityException;
import org.apache.commons.lang3.StringUtils;
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.Service;

import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
 * 〈自定义UserDetailService〉
 */
@Service("userDetailService")
public class MyUserDetailService implements UserDetailsService {




    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {

        UserDto userDto=new UserDto();
        //解析不到参数
         userDto.setPhone(phone);
        //如果电话和租户值任意为空，设置条件使user查不出
        if(StringUtils.isEmpty(phone)){
            userDto.setPhone("-1");

        }
        List<UserDto> loginInfos = userMapper.findLoginInfo(userDto);

        if (loginInfos.size()==0) {
            throw new SecurityException(ResultStatus.PHONE_NUMBER_NOT_FOUND_ERROR);
        }
        LoginUser loginUser = new LoginUser(null);
        loginUser.setId(loginInfos.get(0).getId());
        loginUser.setLoginToken(UUID.randomUUID().toString());
        loginUser.setPhoneNumber(phone);
        loginUser.setUserInfos(JSONObject.toJSONString(loginInfos));
        return loginUser;
    }






}

