package com.fdkanfang.web.backend.utils;

import com.fdkanfang.common.enums.ResultCodeEnum;
import com.fdkanfang.common.exception.CommonBaseException;
import com.fdkanfang.domain.backend.UserEntity;
import com.fdkanfang.service.backend.UserService2;
import com.fdkanfang.web.shiro.JWTUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.US_ASCII;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author abnerhou
 * @date 2020/7/27 16:40
 * @desciption
 */
@Service
@Log4j2
public class UserUtils {

    @Autowired
    UserService2 userService2;

    public List<String> getRolesByToken(String token){
        if(StringUtils.isBlank(token)){
            log.warn("token为空，无法获取token对应的用户的权限");
            return null;
        }
        String userName = JWTUtil.getUserName(token);
        UserEntity user = userService2.findByUserName(userName);
        if(null == user){
            throw new CommonBaseException(ResultCodeEnum.D101 , "用户不存在");
        }
        // 获取用户角色
        Set<String> roles = userService2.findRoleByUserId(user.getId());
        return new ArrayList<>(roles);
    }

    public UserEntity getUserByToken(String token){
        if(StringUtils.isBlank(token)){
            log.warn("token为空，无法获取token对应的用户限");
            return null;
        }
        String userName = JWTUtil.getUserName(token);
        UserEntity user = userService2.findByUserName(userName);
        if(null == user){
            throw new CommonBaseException(ResultCodeEnum.D101 , "用户不存在");
        }
       return user;
    }

    public int  addNewUserByPhone(String phoneNum , String password , int kankanUserId){
        if(StringUtils.isBlank(phoneNum)){
            return -1;
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(phoneNum);
        userEntity.setPhone(phoneNum);
        userEntity.setRealName(phoneNum);
        userEntity.setKankanUserId(kankanUserId);
        if(StringUtils.isNotBlank(password)){
            userEntity.setPassword(password);
        }
        userEntity.setRecStatus("A");
        userEntity.setCreateTime(new Date());
        userEntity.setUpdateTime(new Date());
        int insert = userService2.save(userEntity);
        if(insert != 1){
            throw new CommonBaseException(ResultCodeEnum.D101 , "新增用户失败");
        }
        return 1;
    }


}
