package com.stylefeng.guns.modular.system.controller; import com.alibaba.druid.support.json.JSONUtils; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.stylefeng.guns.config.properties.GunsProperties; import com.stylefeng.guns.core.base.controller.BaseController; import com.stylefeng.guns.core.base.tips.Tip; import com.stylefeng.guns.core.common.annotion.BussinessLog; import com.stylefeng.guns.core.common.annotion.Permission; import com.stylefeng.guns.core.common.constant.Const; import com.stylefeng.guns.core.common.constant.dictmap.UserDict; import com.stylefeng.guns.core.common.constant.factory.ConstantFactory; import com.stylefeng.guns.core.common.constant.state.ManagerStatus; import com.stylefeng.guns.core.common.exception.BizExceptionEnum; import com.stylefeng.guns.core.datascope.DataScope; import com.stylefeng.guns.core.db.Db; import com.stylefeng.guns.core.exception.GunsException; import com.stylefeng.guns.core.log.LogObjectHolder; import com.stylefeng.guns.core.shiro.ShiroKit; import com.stylefeng.guns.core.shiro.ShiroUser; import com.stylefeng.guns.core.util.ToolUtil; import com.stylefeng.guns.modular.system.dao.UserMapper; import com.stylefeng.guns.modular.system.dto.LoginWarpper; import com.stylefeng.guns.modular.system.dto.QuestionDto; import com.stylefeng.guns.modular.system.factory.UserFactory; import com.stylefeng.guns.modular.system.model.TTags; import com.stylefeng.guns.modular.system.model.TUserData; import com.stylefeng.guns.modular.system.model.User; import com.stylefeng.guns.modular.system.service.ITTagsService; import com.stylefeng.guns.modular.system.service.IUserService; import com.stylefeng.guns.modular.system.transfer.ResgisDto; import com.stylefeng.guns.modular.system.transfer.UserDto; import com.stylefeng.guns.modular.system.util.ExcelUtil; import com.stylefeng.guns.modular.system.util.R; import com.stylefeng.guns.modular.system.warpper.UserWarpper; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.naming.NoPermissionException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.File; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import static org.apache.shiro.web.filter.mgt.DefaultFilter.user; /** * 系统管理员控制器 * * @author fengshuonan * @Date 2017年1月11日 下午1:08:17 */ @Controller @RequestMapping("/mgr") public class UserMgrController extends BaseController { private static String PREFIX = "/system/user/"; @Autowired private GunsProperties gunsProperties; @Autowired private IUserService userService; @Autowired private ITTagsService tagsService; /** * 跳转到查看管理员列表的页面 */ @RequestMapping("") public String index() { return PREFIX + "user.html"; } @RequestMapping("/user/tolist") public String tolist(Model model) { List tTags = tagsService.selectList(null); model.addAttribute("tags",tTags); return PREFIX + "userList.html"; } @RequestMapping("/frozen/allert/{id}") public String tolist(@PathVariable Integer id, Model model) { model.addAttribute("id",id); User user = userService.selectById(id); model.addAttribute("item",user); return PREFIX + "user_frozen_allert.html"; } @RequestMapping("/frozen/allert1/{id}") public String tolist1(@PathVariable Integer id, Model model) { model.addAttribute("id",id); User user = userService.selectById(id); model.addAttribute("item",user); return PREFIX + "user_frozen_allert1.html"; } @RequestMapping("/tosettags/{id}") public String tosettags(@PathVariable Integer id, Model model) { model.addAttribute("id",id); User user = userService.selectById(id); model.addAttribute("item",user); String tags = user.getTags(); if (tags!=null&&tags!="") { String[] split = tags.split(","); List tTags = tagsService.selectList(null); for (TTags tTag : tTags) { if (Arrays.asList(split).contains(tTag.getId().toString())) { tTag.setChecked(1); } } model.addAttribute("tags", tTags); }else { List tTags = tagsService.selectList(null); model.addAttribute("tags", tTags); } return PREFIX + "set_tags.html"; } @RequestMapping("/user/detail/{userId}") public String detail(@PathVariable Integer userId,Model model) { User user = userService.selectById(userId); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 设置日期时间格式 String strDate = formatter.format(user.getCreatetime()); // 将Date类型转换为String user.setCreatetimestr(strDate); user.setBirthDayStr(formatter.format(user.getBirthday())); model.addAttribute("user", user); // model.addAttribute("phone", user); if (user.getQuestion()==null){ QuestionDto questionDto = new QuestionDto(); questionDto.setQ1(0); questionDto.setQ2(0); questionDto.setQ3(0); questionDto.setQ4(0); questionDto.setQ5(0); model.addAttribute("question", questionDto); model.addAttribute("score", 0); }else { model.addAttribute("question", JSONUtils.parse(user.getQuestion())); String question = user.getQuestion(); // QuestionDto parse = (QuestionDto) JSONUtils.parse(question); ObjectMapper mapper = new ObjectMapper(); QuestionDto parse =new QuestionDto(); try { // 将JSON字符串转换为TUserData数组 parse = mapper.readValue(question, QuestionDto.class); // 打印转换后的数组,以便验证 // System.out.println(Arrays.toString(tUserDataArray)); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("score", parse.getQ1()+parse.getQ2()+parse.getQ3()+parse.getQ4()+parse.getQ5()); } return PREFIX + "userDetail.html"; } @RequestMapping("/user/getDetail/{userId}") @ResponseBody public R getDetail(@PathVariable Integer userId) { User user = userService.selectById(userId); List tTags = tagsService.selectList(new EntityWrapper().in("id", user.getTags())); if (tTags==null||tTags.isEmpty()){ return R.ok(); } List strings =new ArrayList<>(); for (TTags tTag : tTags) { strings.add(tTag.getTagName()); } String result = String.join(",", strings); return R.ok(result); } @RequestMapping("/changeTag") @ResponseBody public R changeTag(String tags,@RequestParam Integer id) { User user = userService.selectById(id); user.setTags(tags); userService.updateById(user); return R.ok(); } /** * 跳转到查看管理员列表的页面 */ @RequestMapping("/user_add") public String addView() { return PREFIX + "user_add.html"; } /** * 跳转到角色分配页面 */ //@RequiresPermissions("/mgr/role_assign") //利用shiro自带的权限检查 @Permission @RequestMapping("/role_assign/{userId}") public String roleAssign(@PathVariable Integer userId, Model model) { if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } User user = (User) Db.create(UserMapper.class).selectOneByCon("id", userId); model.addAttribute("userId", userId); model.addAttribute("userAccount", user.getAccount()); return PREFIX + "user_roleassign.html"; } /** * 跳转到编辑管理员页面 */ @Permission @RequestMapping("/user_edit/{userId}") public String userEdit(@PathVariable Integer userId, Model model) { if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } assertAuth(userId); User user = this.userService.selectById(userId); model.addAttribute(user); model.addAttribute("roleName", ConstantFactory.me().getRoleName(user.getRoleid())); model.addAttribute("deptName", ConstantFactory.me().getDeptName(user.getDeptid())); LogObjectHolder.me().set(user); return PREFIX + "user_edit.html"; } /** * 跳转到查看用户详情页面 */ @RequestMapping("/user_info") public String userInfo(Model model) { Integer userId = ShiroKit.getUser().getId(); if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } User user = this.userService.selectById(userId); model.addAttribute(user); model.addAttribute("roleName", ConstantFactory.me().getRoleName(user.getRoleid())); model.addAttribute("deptName", ConstantFactory.me().getDeptName(user.getDeptid())); LogObjectHolder.me().set(user); return PREFIX + "user_view.html"; } /** * 跳转到修改密码界面 */ @RequestMapping("/user_chpwd") public String chPwd() { return PREFIX + "user_chpwd.html"; } /** * 修改当前用户的密码 */ @RequestMapping("/changePwd") @ResponseBody public Object changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) { if (!newPwd.equals(rePwd)) { throw new GunsException(BizExceptionEnum.TWO_PWD_NOT_MATCH); } Integer userId = ShiroKit.getUser().getId(); User user = userService.selectById(userId); String oldMd5 = ShiroKit.md5(oldPwd, user.getSalt()); if (user.getPassword().equals(oldMd5)) { String newMd5 = ShiroKit.md5(newPwd, user.getSalt()); user.setPassword(newMd5); user.updateById(); return SUCCESS_TIP; } else { throw new GunsException(BizExceptionEnum.OLD_PWD_NOT_RIGHT); } } /** * 查询管理员列表 */ @RequestMapping("/list") @Permission @ResponseBody public Object list(@RequestParam(required = false) String name, @RequestParam(required = false) String phone, @RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) Integer deptid, @RequestParam(required = false) Integer high1, @RequestParam(required = false) Integer high2, @RequestParam(required = false) Integer weight1, @RequestParam(required = false) Integer weight2, @RequestParam(required = false) String hospital, @RequestParam(required = false) Integer tag ) { // if (ShiroKit.isAdmin()) { // List> users = userService.selectUsers(null, name, beginTime, endTime, deptid); // return new UserWarpper(users).warp(); // } else { // DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope()); // List> users = userService.selectUsers(dataScope, name, beginTime, endTime, deptid); // return new UserWarpper(users).warp(); // } if (beginTime!=null&&beginTime!="") { String[] split = beginTime.split(" - "); beginTime = split[0]; endTime = split[1]; } List> users = userService.selectUsers(null, name,phone, beginTime, endTime, deptid,high1,high2,weight1,weight2,hospital,tag); return new UserWarpper(users).warp(); } /** * 添加管理员 */ @RequestMapping("/add") @BussinessLog(value = "添加管理员", key = "account", dict = UserDict.class) @Permission(Const.ADMIN_NAME) @ResponseBody public Tip add(@Valid UserDto user, BindingResult result) { if (result.hasErrors()) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } // 判断账号是否重复 User theUser = userService.getByAccount(user.getAccount()); if (theUser != null) { throw new GunsException(BizExceptionEnum.USER_ALREADY_REG); } // 完善账号信息 user.setSalt(ShiroKit.getRandomSalt(5)); user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt())); user.setStatus(ManagerStatus.OK.getCode()); user.setCreatetime(new Date()); this.userService.insert(UserFactory.createUser(user)); return SUCCESS_TIP; } @PostMapping("/regis") @ApiOperation("注册") @ResponseBody public Tip regis(@RequestBody ResgisDto resgisDto) { // 判断账号是否重复 User theUser = userService.getByAccount(resgisDto.getPhone()); if (theUser != null) { throw new GunsException(BizExceptionEnum.USER_ALREADY_REG); } // 完善账号信息 resgisDto.setSalt(ShiroKit.getRandomSalt(5)); resgisDto.setPassword(ShiroKit.md5(resgisDto.getPassword(), resgisDto.getSalt())); resgisDto.setStatus(ManagerStatus.OK.getCode()); resgisDto.setCreatetime(new Date()); resgisDto.setAccount(resgisDto.getPhone()); this.userService.insert(UserFactory.createUser1(resgisDto)); return SUCCESS_TIP; } /** * 修改管理员 * * @throws NoPermissionException */ @RequestMapping("/edit") @BussinessLog(value = "修改管理员", key = "account", dict = UserDict.class) @ResponseBody public Tip edit(@Valid UserDto user, BindingResult result) throws NoPermissionException { if (result.hasErrors()) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } User oldUser = userService.selectById(user.getId()); if (ShiroKit.hasRole(Const.ADMIN_NAME)) { this.userService.updateById(UserFactory.editUser(user, oldUser)); return SUCCESS_TIP; } else { assertAuth(user.getId()); ShiroUser shiroUser = ShiroKit.getUser(); if (shiroUser.getId().equals(user.getId())) { this.userService.updateById(UserFactory.editUser(user, oldUser)); return SUCCESS_TIP; } else { throw new GunsException(BizExceptionEnum.NO_PERMITION); } } } /** * 删除管理员(逻辑删除) */ @RequestMapping("/delete") @BussinessLog(value = "删除管理员", key = "userId", dict = UserDict.class) @Permission @ResponseBody public Tip delete(@RequestParam Integer userId) { if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } //不能删除超级管理员 if (userId.equals(Const.ADMIN_ID)) { throw new GunsException(BizExceptionEnum.CANT_DELETE_ADMIN); } assertAuth(userId); this.userService.setStatus(userId, ManagerStatus.DELETED.getCode()); return SUCCESS_TIP; } /** * 查看管理员详情 */ @RequestMapping("/view/{userId}") @ResponseBody public User view(@PathVariable Integer userId) { if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } assertAuth(userId); return this.userService.selectById(userId); } // @ResponseBody // @PostMapping("/base/driver/driverLogin") // @ApiOperation(value = "登录操作", tags = {"APP登录"}, notes = "") // @ApiImplicitParams({ // @ApiImplicitParam(value = "手机号码", name = "phone", required = true, dataType = "String"), // @ApiImplicitParam(value = "密码", name = "password", required = true, dataType = "String") // }) // public R driverLogin(String phone, String password){ // try { // return userService.driverLogin(phone, password); // }catch (Exception e){ // e.printStackTrace(); // return R.fail(); // } // } // @ResponseBody // @PostMapping("/api/question") // @ApiOperation(value = "填写问卷调查", tags = {"问卷调查"}, notes = "") // @ApiImplicitParams({ // @ApiImplicitParam(name = "Authorization", value = "Bearer +token", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....") // }) // public R queryHomeData(HttpServletRequest request){ // // return R.ok("填写成功"); // } /** * 重置管理员的密码 */ @RequestMapping("/reset") @BussinessLog(value = "重置管理员密码", key = "userId", dict = UserDict.class) @Permission(Const.ADMIN_NAME) @ResponseBody public Tip reset(@RequestParam Integer userId) { if (ToolUtil.isEmpty(userId)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } assertAuth(userId); User user = this.userService.selectById(userId); user.setSalt(ShiroKit.getRandomSalt(5)); user.setPassword(ShiroKit.md5(Const.DEFAULT_PWD, user.getSalt())); this.userService.updateById(user); return SUCCESS_TIP; } /** * 冻结用户 */ @RequestMapping("/freeze") @BussinessLog(value = "冻结用户", key = "userId", dict = UserDict.class) @Permission(Const.ADMIN_NAME) @ResponseBody public Tip freeze(@RequestParam Integer id,String reason) { if (ToolUtil.isEmpty(id)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } //不能冻结超级管理员 if (id.equals(Const.ADMIN_ID)) { throw new GunsException(BizExceptionEnum.CANT_FREEZE_ADMIN); } assertAuth(id); this.userService.setStatus(id, ManagerStatus.FREEZED.getCode()); User user = userService.selectById(id); user.setFrozenReason(reason); userService.updateById(user); return SUCCESS_TIP; } @RequestMapping(value = "/export") @ResponseBody public void exportUserInfo(Integer id, Integer state, HttpServletResponse response) { try { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyyMMdd"); String time1 = format.format(date); String fileName ="用户信息.xls"; String[] title = new String[] {"用户名","手机号","出生日期","身高","体重","就诊医院","用户标签","注册时间","问卷调查分数"}; List> users = userService.selectUsers(null, null,null, null, null, null,null,null,null,null,null,null); String[][] values = new String[users.size()][]; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期时间格式 SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期时间格式 for (int i = 0; i < users.size(); i++) { Map d = users.get(i); values[i] = new String[title.length]; values[i][0] = (String) d.get("name"); values[i][1] = (String) d.get("phone"); String strDate = formatter.format(d.get("birthday")); // 将Date类型转换为String values[i][2] = strDate; values[i][3] = d.get("high").toString(); values[i][4] = d.get("weight").toString(); values[i][5] = (String) d.get("hospital"); String tagsName = (String) d.get("tagsName"); if (tagsName!=null) { String replace = tagsName.replace(",", ";"); values[i][6] = replace; } values[i][7] = formatter1.format(d.get("createtime")); // 将Date类型转换为String values[i][8] = formatter.format(d.get("createtime")); // 将Date类型转换为String } HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("Variance"+time1, title, values, null); ExcelUtil.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); }catch(Exception e){ e.printStackTrace(); } } /** * 解除冻结用户 */ @RequestMapping("/unfreeze") @BussinessLog(value = "解除冻结用户", key = "userId", dict = UserDict.class) @Permission(Const.ADMIN_NAME) @ResponseBody public Tip unfreeze(@RequestParam Integer id) { if (ToolUtil.isEmpty(id)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } assertAuth(id); this.userService.setStatus(id, ManagerStatus.OK.getCode()); return SUCCESS_TIP; } /** * 分配角色 */ @RequestMapping("/setRole") @BussinessLog(value = "分配角色", key = "userId,roleIds", dict = UserDict.class) @Permission(Const.ADMIN_NAME) @ResponseBody public Tip setRole(@RequestParam("userId") Integer userId, @RequestParam("roleIds") String roleIds) { if (ToolUtil.isOneEmpty(userId, roleIds)) { throw new GunsException(BizExceptionEnum.REQUEST_NULL); } //不能修改超级管理员 if (userId.equals(Const.ADMIN_ID)) { throw new GunsException(BizExceptionEnum.CANT_CHANGE_ADMIN); } assertAuth(userId); this.userService.setRoles(userId, roleIds); return SUCCESS_TIP; } /** * 上传图片 */ @RequestMapping(method = RequestMethod.POST, path = "/upload") @ResponseBody public String upload(@RequestPart("file") MultipartFile picture) { String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename()); try { String fileSavePath = gunsProperties.getFileUploadPath(); picture.transferTo(new File(fileSavePath + pictureName)); } catch (Exception e) { throw new GunsException(BizExceptionEnum.UPLOAD_ERROR); } return pictureName; } /** * 判断当前登录的用户是否有操作这个用户的权限 */ private void assertAuth(Integer userId) { // if (ShiroKit.isAdmin()) { // return; // } // List deptDataScope = ShiroKit.getDeptDataScope(); // User user = this.userService.selectById(userId); // Integer deptid = user.getDeptid(); // if (deptDataScope.contains(deptid)) { // return; // } else { // throw new GunsException(BizExceptionEnum.NO_PERMITION); // } } }