package com.lyms.talkonlineweb.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyms.talkonlineweb.annotation.TokenRequired;
import com.lyms.talkonlineweb.domain.LymsPermission;
import com.lyms.talkonlineweb.domain.LymsUser;
import com.lyms.talkonlineweb.domain.UserroleInfo;
import com.lyms.talkonlineweb.mapper.LymsUserMapper;
import com.lyms.talkonlineweb.result.BaseResponse;
import com.lyms.talkonlineweb.result.CheckResult;
import com.lyms.talkonlineweb.service.LymsUserService;
import com.lyms.talkonlineweb.service.LymsUserroleService;
import com.lyms.talkonlineweb.service.UserroleInfoService;
import com.lyms.talkonlineweb.util.Constant;
import com.lyms.talkonlineweb.util.HXService;
import com.lyms.talkonlineweb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;
@RestController
@Log4j2
public class UserContoller {
// public static Cache<String, Object> cache = CacheBuilder.newBuilder()
// .expireAfterAccess(20, TimeUnit.HOURS)
// .build();
@Autowired
private LymsUserService lymsUserService;
@Autowired
private LymsUserMapper lymsUserMapper;
@Autowired
private HXService hxService;
@Autowired
private UserroleInfoService userroleInfoService;//视图
@Autowired
private LymsUserroleService lymsUserroleService;//用户角色关系表
@Value("${hx.APPKEY}")
private String appKey;
@Value("${hx.ClientID}")
private String clientId;
@Value("${hx.ClientSecret}")
private String clientSecret;
@RequestMapping(value = "login",method = {RequestMethod.GET,RequestMethod.POST,RequestMethod.OPTIONS})
public BaseResponse login(String username, String passwd){
// QueryWrapper queryWrapper= Wrappers.query(LymsUser.class);
log.info(">>>>>");
BaseResponse baseResponse=new BaseResponse();
Map<String,Object> tMap=new HashMap<>();
tMap.put("token","");
List<LymsUser> uLst=lymsUserMapper.sltUser(username,DigestUtils.md5DigestAsHex(passwd.getBytes()));
if(uLst.size()>0){
LymsUser user=uLst.get(0);
String JWT = JwtUtils.createJWT("1", user.getLogin(), Constant.JWT_TTL);
tMap.put("token",JWT);
if(user.getHxid()==null && user.getHid()==null){
JSONObject json=hxService.addUser(user.getLogin(),Constant.COMMON_PASSWD);
JSONArray rArr=json.getJSONArray("entities");
if(rArr.size()>0){
user.setHxid(rArr.getJSONObject(0).getString("uuid"));
}
}
lymsUserService.saveOrUpdate(user);
user.setPasswd(null);
tMap.put("user",user);
}
baseResponse.setObject(tMap);
baseResponse.setErrorcode(0);
return baseResponse;
}
/**
* 得到用户权限
* @return
*/
@PostMapping("getPermission")
public BaseResponse getPermission(@RequestHeader String authorization){
BaseResponse baseResponse=new BaseResponse();
try {
Claims claims =JwtUtils.parseJWT(authorization);
String username=claims.getSubject();
List<LymsPermission> permiss=lymsUserService.getPermissionByUsername(username);
baseResponse.setObject(permiss);
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
baseResponse.setErrorcode(1);
baseResponse.setErrormsg(e.getMessage());
}
return baseResponse;
}
/**
* 添加用户
* @param user
* @param authorization
* @return
*/
@RequestMapping("saveUser")
public BaseResponse saveUser(@Validated LymsUser user, BindingResult result, @RequestHeader String authorization){
BaseResponse baseResponse=new BaseResponse();
baseResponse.setErrormsg("");
try {
LymsUser curUser=lymsUserService.getUserByToken(authorization);
user.setCreatedby(curUser.getUid());
user.setCreatedtime(new Date());
if(user.getUid()==null){
user.setPasswd(DigestUtils.md5DigestAsHex("123456".getBytes()));
}
if(result.hasErrors()){
result.getAllErrors().forEach(e->{
baseResponse.setErrormsg(baseResponse.getErrormsg()+e.getDefaultMessage()+";");
});
baseResponse.setErrorcode(1);
return baseResponse;
}
boolean f=lymsUserService.saveOrUpdate(user);
baseResponse.setErrorcode(f==true?0:1);
// hxAddUser(user);
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
baseResponse.setErrorcode(1);
baseResponse.setErrormsg(e.getMessage());
}
return baseResponse;
}
// public void hxAddUser(LymsUser user) {
// EMUser emUser=emService.user().get(user.getLogin()).block();
//
// }
/**
* 删除用户
* @param uid
* @return
*/
@PostMapping("delUser")
public BaseResponse delUser(int uid){
BaseResponse baseResponse=new BaseResponse();
boolean f=lymsUserService.removeById(uid);
baseResponse.setErrorcode(f==true?0:1);
if(!f){
baseResponse.setErrormsg("不存在改用户!");
}
return baseResponse;
}
/**
* 查询用户列表
* @param user
* @param current
* @param size
* @return
*/
@GetMapping("sltUser")
public BaseResponse sltUser(LymsUser user,int current,int size){
BaseResponse baseResponse=new BaseResponse();
Page<LymsUser> page=new Page<>(current,size);
Page<LymsUser> userIPage=lymsUserService.page(page,Wrappers.query(user).orderByDesc("updated_time","createdtime"));
baseResponse.setObject(userIPage);
return baseResponse;
}
/**
* 添加用户角色关系
* @param uid
* @param rids
* @return
*/
@PostMapping("addUserRoles")
public BaseResponse addUserRoles(int uid,String rids){
BaseResponse baseResponse=new BaseResponse();
String[] ridArr=rids.split(",");
int cnt=lymsUserroleService.delRoleByUser(uid);//删除用户角色关系
for (int i = 0; i < ridArr.length; i++) {
cnt=lymsUserroleService.addRoleUser(uid,Integer.parseInt(ridArr[i]));
}
return baseResponse;
}
/**
* 获取用户和角色列表
* @param user
* @param current
* @param size
* @return
*/
@GetMapping("getUserRoleLst")
public BaseResponse getUserRoleLst(UserroleInfo user, int current, int size){
BaseResponse baseResponse=new BaseResponse();
Page<UserroleInfo> page=new Page<>(current,size);
Page<UserroleInfo> userIPage=userroleInfoService.page(page,Wrappers.query(user).orderByDesc("updated_time","createdtime"));
baseResponse.setObject(userIPage);
return baseResponse;
}
/**
* 添加用户包含的角色
* @param uid
* @param roles 如果是多个权限需要用","分割
* @return
*/
@PostMapping("addUserByRoles")
public BaseResponse addRoleByPerms(int uid,String roles){
BaseResponse baseResponse=new BaseResponse();
String[] pArr=roles.split(",");
int cnt=0;
cnt=lymsUserroleService.delRoleByUser(uid);//删除旧的关系
for (int i = 0; i < pArr.length; i++) {
cnt=lymsUserroleService.addRoleUser(uid,Integer.parseInt(pArr[i]));//添加用户和角色映射
}
return baseResponse;
}
}