package com.manage.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.manage.dao.Power_NoticeMapper;
import com.manage.dao.Power_UserMapper;
import com.manage.encrypt.Base64;
import com.manage.encrypt.MD5;
import com.manage.entity.*;
import com.manage.service.*;
import com.manage.service.cache.Cache;
import com.manage.service.cache.CacheManager;
import com.manage.service.ipml.Power_NoticeServiceImpl;
import com.manage.service.webSocket.WsPool;
import com.manage.util.DateUtils;
import com.manage.util.ExceptionPrintUtil;
import com.manage.util.Msg;
import com.manage.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/7/9 15:07
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/7/9 15:07
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("font/")
public class FontController {
    @Value("${STR_SPLIT}")
    private String STR_SPLIT;
    @Value("${defaultRoleId}")
    private String defaultRoleId;
    @Value("${defaultDeptId}")
    private String defaultDeptId;
    @Autowired
    private PowerService powerService;
    @Autowired
    private User_Dept_MenuService userDeptMenuService;
    @Autowired
    private Power_NoticeMapper powerNoticeMapper;
    @Autowired
    private Power_UserMapper userMapper;
    @Autowired
    private Power_NoticeServiceImpl noticeService;
    @Autowired
    private Power_UserService userService;
    @Value("${TOKEN_EXPIRE_TIME}")
    private long TOKEN_EXPIRE_TIME;
    @Autowired
    private Power_MenuService powerMenuService;
    @Autowired
    private Power_DeptService power_deptService;

    /**
     * 2.1
     * @ProjectName:    getRolePowerTreeBySysFlag
     * @Description:    获取菜单通过系统标识
     * @Param           无
     * @Return          getMenusByUserIdAndSysFlag
     * @Author:         曾文和
     * @CreateDate:     2019/7/9 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/7/9 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getMenusByUserIdAndSysFlag",method = RequestMethod.GET)
    @ResponseBody
    public Msg getMenusByUserIdAndSysFlag(String userName,String sysFlag,Integer userId,Integer roleId,Integer sysId,Integer hospitalId) throws Exception{
        if(StringUtils.isNotBlank(sysFlag) && StringUtils.isBlank(userName) &&  userId == null && roleId == null
                && sysId == null && hospitalId == null){
            return Msg.fail("查询复杂,数据大,暂不支持只带sysFlag参数查询");
        }
        if(StringUtils.isBlank(sysFlag) && StringUtils.isBlank(userName) &&  userId == null && roleId == null
                && sysId != null && hospitalId == null){
            return Msg.fail("查询复杂,数据大,暂不支持只带sysId参数查询");
        }
        if(StringUtils.isBlank(sysFlag) && StringUtils.isBlank(userName) &&  userId == null && roleId == null
                && sysId == null && hospitalId != null){
            return Msg.fail("查询复杂,数据大,暂不支持只带hospitalId参数查询");
        }
        if(StringUtils.isNotBlank(userName)){
            List<Power_User> powerUsers = userMapper.checkUserName(userName);
            if(null != powerUsers && !powerUsers.isEmpty()){
                if(powerUsers.get(0).getRoleId().equals(0) || powerUsers.get(0).getRoleId().equals(-100)){
                    roleId = powerUsers.get(0).getRoleId();
                }
            }
        }

        List<User_Dept_Menu> list = userDeptMenuService.selectAll(userName, sysFlag, userId, roleId, sysId, hospitalId);
        CacheManager.addExcCount("noExc");
        return Msg.success().add("list",list);
    }

    /**
     * 2.2
     * @ProjectName:    selectAllByUserIdOrRoleIdAndSysIdOrSysFlag
     * @Description:    根据用户id或角色id和系统id或系统标识查询通知记录
     * @Param           无
     * @Return          selectAllByUserIdOrRoleIdAndSysIdOrSysFlag
     * @Author:         曾文和
     * @CreateDate:     2019/7/29 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/7/29 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "selectAllByUserIdOrRoleIdAndSysIdOrSysFlag")
    @ResponseBody
    public Msg selectAllByUserIdOrRoleIdAndSysIdOrSysFlag(Integer userId,Integer roleId,Integer sysId,String sysFlag) throws Exception{
        List<Power_Notice> list = powerNoticeMapper.selectAllByUserIdOrRoleIdAndSysIdOrSysFlag(userId, roleId, sysId, sysFlag);
        CacheManager.addExcCount("noExc");
        return Msg.success().add("list",list);
    }

    /**
     * 2.4
     * @ProjectName:    getUserPowerTreeBySysFlag
     * @Description:    获取系统用户树通过系统标识
     * @Param           无
     * @Return          PowerTree
     * @Author:         曾文和
     * @CreateDate:     2019/7/9 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/7/9 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getUserPowerTreeBySysFlag",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getUserPowerTreeBySysFlag(String sysFlag,Integer userId){
        try {
            if(null != userId){
                //查询该用户
                Power_UserVo user = userMapper.selectByPrimaryKey(userId);
                List<PowerTree> dicts = powerService.getUserPowerTreeBySysFlag(sysFlag,user);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(dicts);
                CacheManager.addExcCount("noExc");
                return json;
            }else{
                return null;
            }
        }catch(Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 2.5
     * @ProjectName:    getRolePowerTreeBySysFlag
     * @Description:    获取系统角色树通过系统标识
     * @Param           无
     * @Return          PowerTree
     * @Author:         曾文和
     * @CreateDate:     2019/7/9 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/7/9 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getRolePowerTreeBySysFlag",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getRolePowerTreeBySysFlag(String sysFlag,Integer userId){
        try {
            if(null != userId){
                Power_UserVo user = userMapper.selectByPrimaryKey(userId);
                List<PowerTree> dicts = powerService.getRolePowerTreeBySysFlag(sysFlag,user);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(dicts);
                CacheManager.addExcCount("noExc");
                return json;
            }else{
                return null;
            }
        }catch(Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 2.6
     * @ProjectName:    getUserList
     * @Description:    获取用户id和用户名
     * @Param           无
     * @Return          userList
     * @Author:         曾文和
     * @CreateDate:     2019/9/6 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/9/6 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getUserList")
    @ResponseBody
    public Msg getUserList(String userName) throws Exception{
        List<User> list = new ArrayList<>();
        if(StringUtils.isNoneBlank(userName)){
            List<Power_User> users = userMapper.checkUserName(userName);
            if(null != users && !users.isEmpty()){
                Integer roleId = users.get(0).getRoleId();
                if(roleId == 0){
                    list = userMapper.selectUserIdAndUserNameList(null);
                }else{
                    list = userMapper.selectUserIdAndUserNameList(users.get(0).getUserId());
                }
            }
        }else{
            return Msg.fail("用户名不能为空");
        }
        CacheManager.addExcCount("noExc");
        return Msg.success().add("userList",list);
    }

    /**
     * 2.7
     * @ProjectName:    checkToken
     * @Description:    验证token是否有效
     * @Param           无
     * @Return          Msg
     * @Author:         曾文和
     * @CreateDate:     2019/9/24 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/9/24 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "checkToken",method = RequestMethod.POST)
    @ResponseBody
    public Msg checkToken(String token) throws Exception{
        if(StringUtils.isNotBlank(token) && StringUtils.isNotBlank(token) ) {
            token = MD5.JM(Base64.decode(token));
            Cache cache = CacheManager.getCacheInfo(token);
            if (cache == null) {
                return Msg.fail("token已过期或不存在");
            }
            //更新过期时间
            Power_UserVo user = (Power_UserVo) cache.getValue();
            String date = String.valueOf(DateUtils.getDate());
            CacheManager.putCache(token,new Cache(date,user,TOKEN_EXPIRE_TIME));
        }else{
            return Msg.fail("token不能为空");
        }
        return Msg.success();
    }

    /**
     * 2.8
     * @ProjectName:    getUserByToken
     * @Description:    根据token获取用户
     * @Param           无
     * @Return          getMenuListByToken
     * @Author:         曾文和
     * @CreateDate:     2019/10/31 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/10/31 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getUserByToken",method = RequestMethod.POST)
    @ResponseBody
    public Msg getMenuListByToken(String token,String sysFlag) throws Exception{
        if(StringUtils.isBlank(token)){
            return Msg.fail("token不能为空!");
        }
        if(StringUtils.isBlank(sysFlag)){
            return Msg.fail("sysFlag不能为空!");
        }
        token = MD5.JM(Base64.decode(token));
        Cache cacheInfo = CacheManager.getCacheInfo(token);
        Power_UserVo user = (Power_UserVo) cacheInfo.getValue();
        if(null != user){
            List<User_Dept_Menu> menuList = user.getMenuList();
            List<User_Dept_Menu> list = new ArrayList<>();
            Set<String> menus = new TreeSet<>();
            if(null != menuList && !menuList.isEmpty()){
                for (int i = 0; i < menuList.size(); i++) {
                    String menuSysFlag = menuList.get(i).getSysFlag();
                    if(StringUtils.isNotBlank(menuSysFlag) && menuSysFlag.equals(sysFlag)){
                        list.add(menuList.get(i));
                        if(StringUtils.isNotBlank(menuList.get(i).getMethod())){
                            menus.add(menuList.get(i).getMenuUrl());
                        }
                    }
                }
            }
            user.setMenuList(list);
            user.setMenus(menus);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            //查询用户集合
            List<User> userList = new ArrayList<>();
            Integer roleId = userVo.getRoleId();
            if(roleId == 0){
                userList = userMapper.selectUserIdAndUserNameList(null);
            }else{
                userList = userMapper.selectUserIdAndUserNameList(userVo.getUserId());
            }
            //设置用户集合
            userVo.setUserList(userList);
            CacheManager.addExcCount("noExc");
            return Msg.success().add("user",userVo);
        }else{
            return Msg.fail("token已失效");
        }
    }

    /**
     * 2.9
     * @ProjectName:    getMenuByToken
     * @Description:    根据token获取菜单
     * @Param           无
     * @Return          getMenuListByToken
     * @Author:         曾文和
     * @CreateDate:     2019/10/31 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/10/31 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getMenuByToken",method = RequestMethod.POST)
    @ResponseBody
    public Msg getMenuByToken(String token,String sysFlag) throws Exception{
        if(StringUtils.isBlank(token)){
            return Msg.fail("token不能为空!");
        }
        if(StringUtils.isBlank(sysFlag)){
            return Msg.fail("sysFlag不能为空!");
        }
        token = MD5.JM(Base64.decode(token));
        Cache cacheInfo = CacheManager.getCacheInfo(token);
        Power_UserVo user = (Power_UserVo) cacheInfo.getValue();
        List<User_Dept_Menu> menuList = user.getMenuList();
        List<User_Dept_Menu> list = new ArrayList<>();
        if(null != menuList && !menuList.isEmpty()){
            for (int i = 0; i < menuList.size(); i++) {
                String menuSysFlag = menuList.get(i).getSysFlag();
                if(StringUtils.isNotBlank(menuSysFlag) && menuSysFlag.equals(sysFlag)){
                    list.add(menuList.get(i));
                }
            }
        }
        CacheManager.addExcCount("noExc");
        return Msg.success().add("list",list);
    }

    /**
     * 将xml转换为Map。 支持xml标签多层嵌套，并以"."分隔多级标签（不包括根节点）。 不支持XML标签重复时的情况
     *
     * @param xml
     * @param map
     * @return
     */
    private Map<String, String> parseXml2Map(String xml, Map<String, String> map) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new StringReader(xml));
            Element root = doc.getRootElement();
            String path = "";
            if (map.containsKey(root.getName().trim())) {
                path = map.get(root.getName().trim());
                map.remove(root.getName().trim());
            }
            for (Iterator i = root.elementIterator(); i.hasNext();) {
                Element element = (Element) i.next();
                if (element.isTextOnly()) {
                    if (path.length() > 0) {
                        map.put(path + element.getName().trim(), element.getTextTrim());
                    } else {
                        map.put(element.getName().trim(), element.getTextTrim());
                    }
                } else {
                    map.put(element.getName().trim(), path+ element.getName().trim() + ".");
                    parseXml2Map(element.asXML(), map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 解析result中xml中的name节点值
     * @param result
     * @param name
     * @return
     */
    private String analysis(String result, String name) {
        String nameValue = "";
        Map<String,String> map = new HashMap<>();
        Map<String, String> valueMap = parseXml2Map(result, map);
        nameValue = valueMap.get(name);
        return nameValue;
    }

    /**
     * 2.10
     * @ProjectName:    南方医院第三方认证getToken
     * @Description:    获取token
     * @Param           无
     * @Return          Msg
     * @Author:         曾文和
     * @CreateDate:     2019/11/06 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/11/06 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getTokenForHis",method = RequestMethod.POST)
    @ResponseBody
    public Msg getTokenForHis(String userName,String password){
        if(StringUtils.isBlank(userName)){
            return Msg.fail("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            return Msg.fail("密码不能为空");
        }
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes()).toUpperCase();
        //2.根据userName查询我们的用户表是否存在
        Power_UserVo userVo = new Power_UserVo();
        // 判断数据库中是否有此用户，如果没有则插入数据库
        String result = linkHisLogin(userName, password);
        if(StringUtils.isBlank(result)){
            return Msg.fail("调用第三方认证失败");
        }
        List<Power_User> userList = userMapper.checkUserName(userName);
        if (CollectionUtils.isEmpty(userList)) {
            //2.1不存在往用户表新增这条用户
            userVo.setUserName(userName);
            userVo.setUserPwd(Base64.encode(MD5.KL("123456")));
            //TODO name从应答的xml解析
            String name = analysis(result,"Name");
            userVo.setName(name);
            userVo.setRoleId(Integer.valueOf(defaultRoleId));
            userVo.setDeptId(defaultDeptId);
            userVo.setEffective(1);
            userVo.setCreater("his");
            SimpleDateFormat fmt= new SimpleDateFormat("yyyy-MM-dd");
            userVo.setCreateDate(fmt.format(new Date()));
            //插入00
            userMapper.insert(userVo);
        }else{
            BeanUtils.copyProperties(userList.get(0),userVo);
        }
        String token = setToken(userVo);
        return Msg.success().add("token",token);
    }

    private String linkHisLogin(String userName, String password) {
        //创建连接工厂
        JAXDynamicClientFactory dcf = JAXDynamicClientFactory.newInstance();
        //创建客户端
        Object[] objects = new Object[0];
        Client client = dcf.createClient("http://192.168.128.170/csp/hsb/DHC.Published.PUB0025.BS.PUB0025.CLS?WSDL=1");
        try {
//            //医院给的webservice地址
//            String url = "http://192.168.128.170/csp/hsb/DHC.Published.PUB0025.BS.PUB0025.CLS?WSDL=1";
//            client = dcf.createClient(url);
            //动态调用getInfosByUserId方法
            //获取请求参数xml字符串
            String xmlStr = getXml(userName,password);
            objects = client.invoke("HIPManagerInfo","S0110", xmlStr);
            //应答信息
            String result = objects[0].toString();
            System.out.println(result);
            //新用户存到数据库
            if (result.contains("成功")) {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != client) {
                client.destroy();
            }
        }
        return null;
    }

    private String getXml(String userName, String password) {
        // 1、创建document对象
        Document document = DocumentHelper.createDocument();
        // 2、创建根节点rss
        Element requestElement = document.addElement("Request");
//        Element patInfo = Requst.addElement("PatInfo");
//        patInfo.addElement("VUID").setText("12412");
        requestElement.addElement("SourceSystem").setText("厦门嘉时");
        requestElement.addElement("TargetSystem").setText("医院信息平台");
        requestElement.addElement("username").setText(userName);
        requestElement.addElement("password").setText(password);
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码格式
        format.setEncoding("UTF-8");
        String xml = document.asXML();
        System.out.println(xml);

//        String res = service.outHOSREG(xml);
//        TBasicWebServiceService serviceService=new TBasicWebServiceService();
//        TBasicWebService service = serviceService.getTBasicWebServicePort();
//        String res = service.outHOSCAN(xml);
//        System.out.println(res);

        return document.asXML();
    }

    private String setToken(Power_UserVo userVo){
        String date = String.valueOf(DateUtils.getDate());
        String token = Base64.encode(MD5.KL(date));
        List<Power_Menu> list = null;
        List<User_Dept_Menu> menuList = new ArrayList<>();
        Set<String> menus = new TreeSet<>();
        if (userVo.getRoleId().equals(0) || userVo.getRoleId().equals(-100)) {
            list = powerMenuService.queryAllPowerMenu(null,userVo.getRoleId());
        } else {
            list = powerMenuService.selectUserAndRoleMenuListPower(userVo.getUserId(),null);
        }
        if(null != list && !list.isEmpty()){
            for (Power_Menu powerMenu : list) {
                User_Dept_Menu deptMenu = new User_Dept_Menu();
                String menuUrl = powerMenu.getMenuUrl();
                if (StringUtils.isNotBlank(menuUrl)) {
                    BeanUtils.copyProperties(powerMenu, deptMenu);
                    deptMenu.setMethodParent(powerMenu.getParentId());
                    menuList.add(deptMenu);
                }
                if (StringUtils.isNotBlank(powerMenu.getMethod())) {
                    menus.add(powerMenu.getMenuUrl());
                }
            }
        }
        userVo.setMenuList(menuList);
        userVo.setMenus(menus);

        //设置科室
        StringBuilder powerDepts = new StringBuilder();
        List<Power_Dept> powerDeptList = power_deptService.selectByPrimaryKeys(userVo.getDeptId());
        for(int j = 0;j < powerDeptList.size();j++){
            if(j<powerDeptList.size()-1){
                powerDepts.append(powerDeptList.get(j).getDeptName()).append(",");
            }else{
                powerDepts.append(powerDeptList.get(j).getDeptName());
            }
        }
        userVo.setRemark(powerDepts.toString());
        //移除缓存
        CacheManager.removeCacheByObject(userVo);
        CacheManager.putCache(date,new Cache(date,userVo,TOKEN_EXPIRE_TIME));
        return token;
    }

    /**
     * 2.10
     * @ProjectName:    getToken
     * @Description:    获取token
     * @Param           无
     * @Return          Msg
     * @Author:         曾文和
     * @CreateDate:     2019/11/06 10:00
     * @UpdateUser:     更新者
     * @UpdateDate:     2019/11/06 10:00
     * @UpdateRemark:   更新说明
     * @Version:        1.0
     */
    @RequestMapping(value = "getToken",method = RequestMethod.POST)
    @ResponseBody
    public Msg getToken(String userName,String password) throws Exception{
        if(StringUtils.isBlank(userName)){
            return Msg.fail("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            return Msg.fail("密码不能为空");
        }
        Power_User user = new Power_User();
        user.setUserName(userName);
        user.setRemark(password);
        Power_UserVo userVo = userService.findPowerUserByUserNameAndRemark(user);
        if(null == userVo){
            return Msg.fail("用户名或密码不正确");
        }
        String date = String.valueOf(DateUtils.getDate());
        String token = Base64.encode(MD5.KL(date));

        List<Power_Menu> list = null;
        List<User_Dept_Menu> menuList = new ArrayList<>();
        Set<String> menus = new TreeSet<>();
        if (userVo.getRoleId().equals(0) || userVo.getRoleId().equals(-100)) {
            list = powerMenuService.queryAllPowerMenu(null,userVo.getRoleId());
        } else {
            list = powerMenuService.selectUserAndRoleMenuListPower(userVo.getUserId(),null);
        }
        if(null != list && !list.isEmpty()){
            for (Power_Menu powerMenu : list) {
                User_Dept_Menu deptMenu = new User_Dept_Menu();
                String menuUrl = powerMenu.getMenuUrl();
                if (StringUtils.isNotBlank(menuUrl)) {
                    BeanUtils.copyProperties(powerMenu, deptMenu);
                    deptMenu.setMethodParent(powerMenu.getParentId());
                    menuList.add(deptMenu);
                }
                if (StringUtils.isNotBlank(powerMenu.getMethod())) {
                    menus.add(powerMenu.getMenuUrl());
                }
            }
        }
        userVo.setMenuList(menuList);
        userVo.setMenus(menus);

        //设置科室
        StringBuilder powerDepts = new StringBuilder();
        List<Power_Dept> powerDeptList = power_deptService.selectByPrimaryKeys(userVo.getDeptId());
        for(int j = 0;j < powerDeptList.size();j++){
            if(j<powerDeptList.size()-1){
                powerDepts.append(powerDeptList.get(j).getDeptName()).append(",");
            }else{
                powerDepts.append(powerDeptList.get(j).getDeptName());
            }
        }
        userVo.setRemark(powerDepts.toString());
        //移除缓存
        CacheManager.removeCacheByObject(userVo);
        CacheManager.putCache(date,new Cache(date,userVo,TOKEN_EXPIRE_TIME));
        return Msg.success().add("token",token);
    }

    /**
     * 不需密码
     * @param userName
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getToken1",method = RequestMethod.POST)
    @ResponseBody
    public Msg getToken1(String userName) throws Exception{
        if(StringUtils.isBlank(userName)){
            return Msg.fail("用户名不能为空");
        }
        List<Power_User> powerUsers = userService.checkUserName(userName);
        if(CollectionUtils.isEmpty(powerUsers)){
            return Msg.fail("用户名不正确");
        }
        String date = String.valueOf(DateUtils.getDate());
        String token = Base64.encode(MD5.KL(date));
        Power_UserVo userVo = new Power_UserVo();
        BeanUtils.copyProperties(powerUsers.get(0),userVo);
        List<Power_Menu> list = null;
        List<User_Dept_Menu> menuList = new ArrayList<>();
        Set<String> menus = new TreeSet<>();
        if (userVo.getRoleId().equals(0) || userVo.getRoleId().equals(-100)) {
            list = powerMenuService.queryAllPowerMenu(null,userVo.getRoleId());
        } else {
            list = powerMenuService.selectUserAndRoleMenuListPower(userVo.getUserId(),null);
        }
        if(null != list && !list.isEmpty()){
            for (Power_Menu powerMenu : list) {
                User_Dept_Menu deptMenu = new User_Dept_Menu();
                String menuUrl = powerMenu.getMenuUrl();
                if (StringUtils.isNotBlank(menuUrl)) {
                    BeanUtils.copyProperties(powerMenu, deptMenu);
                    deptMenu.setMethodParent(powerMenu.getParentId());
                    menuList.add(deptMenu);
                }
                if (StringUtils.isNotBlank(powerMenu.getMethod())) {
                    menus.add(powerMenu.getMenuUrl());
                }
            }
        }
        userVo.setMenuList(menuList);
        userVo.setMenus(menus);

        //设置科室
        StringBuilder powerDepts = new StringBuilder();
        if(StringUtils.isNotBlank(userVo.getDeptId())) {
            List<Power_Dept> powerDeptList = power_deptService.selectByPrimaryKeys(userVo.getDeptId());
            for (int j = 0; j < powerDeptList.size(); j++) {
                if (j < powerDeptList.size() - 1) {
                    powerDepts.append(powerDeptList.get(j).getDeptName()).append(",");
                } else {
                    powerDepts.append(powerDeptList.get(j).getDeptName());
                }
            }
            userVo.setRemark(powerDepts.toString());
        }
        //移除缓存
        CacheManager.removeCacheByObject(userVo);
        CacheManager.putCache(date,new Cache(date,userVo,TOKEN_EXPIRE_TIME));
        return Msg.success().add("token",token);
    }

    /**
     * 2.11
     * @MethodName getUnReadCount
     * @Description: 根据用户获取未读通知数量
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-10-17
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-10-17
     * @UpdateRemark: 更新说明
     * @Version: 1.2.2
     */
    @RequestMapping("notice/getUnReadCount")
    @ResponseBody
    public Msg getUnReadCount(Integer userId) throws Exception{
        if(null == userId){
            return Msg.fail("用户id不能为空");
        }
        Power_UserVo userVo = userMapper.selectByPrimaryKey(userId);
        if(null == userVo){
            return Msg.fail("用户id不存在");
        }
        int unReadCount = noticeService.getUnReadCount(userId);
        CacheManager.addExcCount("noExc");
        return Msg.success().add("unReadCount",unReadCount);
    }

    /**
     * @MethodName checkUserName
     * @Description: 根据用户名判断用户是否存在
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2020-04-22
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-04-22
     * @UpdateRemark: 更新说明
     * @Version: 1.2.2
     */
    @RequestMapping("checkUserName")
    @ResponseBody
    public Msg checkUserName(String userName) throws Exception{
        if(StringUtils.isBlank(userName)){
            return Msg.fail("工号不能为空!");
        }
        //查询用户
        List<Power_User> user = userMapper.checkUserName(userName);
        if(null == user || user.isEmpty()){
            return Msg.fail("该工号不存在!");
        }
        return Msg.success().add("user",user);
    }

    /**
     * @MethodName sendEmrRecordApproveNotice
     * @Description: 给病案管理系统发送审批通知
     * @Param applyType 申请类型
     * @Param count 新的待审批份数
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2020-04-24
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-04-24
     * @UpdateRemark: 更新说明
     * @Version:
     */
    @RequestMapping("sendEmrRecordApproveNotice")
    @ResponseBody
    public void sendEmrRecordApproveNotice(String applyType,Integer count){
        try {
            String title = "待审批通知";
            String content = "您有"+count+"份"+applyType+"待审批!";
            //查询有借阅审批权限的id集合
            String menuUrl = "/approve/updateApprove";
            List<Power_User> users = userMapper.selectUserIdsWithApprove(menuUrl);
            for(Power_User user : users){
                if(null != user) {
                    WsPool.sendMessageToAll("emr_record_" + user.getUserId(), title + STR_SPLIT + content + STR_SPLIT + "emr_record");
                }
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }
}
