package com.unis.crk.basic.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unis.crk.basic.entity.*;
import com.unis.crk.basic.entity.vo.UserAndRoleInfo;
import com.unis.crk.basic.entity.vo.UserInfoVo;
import com.unis.crk.basic.entity.vo.UserLongVo;
import com.unis.crk.basic.mapper.UserInfoMapper;
import com.unis.crk.basic.mapper.UserRoleMapper;
import com.unis.crk.basic.service.*;
import com.unis.crk.basic.util.TokenUtil;
import com.unis.crk.enums.LogConstant;
import com.unis.crk.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Api(value = "用户信息表",tags = {"用户信息表"})
@RestController
@RequestMapping("userInfo")
@CrossOrigin
public class UserInfoController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private IUserOperationlogService userOperationlogService;
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IRoleInfoService roleInfoService;
    @Autowired
    private IOrgInfoService orgInfoService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private UserInfoMapper UserInfoMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private ISysParamsService sysParamsService;
    @ApiOperation(value="分页查询查询用户信息", notes="分页对象和条件(用户名，用户真实名,单位ID)")
    @PostMapping("getUserInfo")
    public ResultUtil getUserInfo(@RequestBody UserLongVo userLongVo){
        ResultUtil<IPage<Map<String,Object>>> data = new ResultUtil<>();
        Page<UserAndRoleInfo> p =new Page<>(userLongVo.getPageNum(),userLongVo.getPageSize());
        QueryWrapper<UserAndRoleInfo> userAndRoleInfoQueryWrapper = new QueryWrapper<>();
        if(  StrUtil.isNotBlank(userLongVo.getUsername())){
            userAndRoleInfoQueryWrapper.like("username",data.getQueryWrapperformat(userLongVo.getUsername()));
        }

        if(StrUtil.isNotBlank(userLongVo.getRealName())){
            userAndRoleInfoQueryWrapper.like("real_name",data.getQueryWrapperformat(userLongVo.getRealName()));
        }
        if( StrUtil.isNotBlank(userLongVo.getOrgId())){
            userAndRoleInfoQueryWrapper.eq("ui.org_id",userLongVo.getOrgId());

        }
        String sqlSelect = userAndRoleInfoQueryWrapper.getSqlSelect();
        IPage<Map<String, Object>> mapIPage = userInfoService.queryAll(p, userAndRoleInfoQueryWrapper);

        List<Map<String, Object>> records = mapIPage.getRecords();
        for (Map<String, Object> m : records)
        {
            List<RoleInfo> userRoleByUserID = roleInfoService.getUserRoleByUserID(m.get("userId").toString());
            String roleNames = m.get("realName").toString();
            if(userRoleByUserID !=null && userRoleByUserID.size()>0){
                for (int i = 0; i < userRoleByUserID.size(); i++) {
                    RoleInfo s = userRoleByUserID.get(i);
                    if(s!=null){
                        roleNames=roleNames + ","+s.getRoleName();
                    }
                }
            }
            m.put("roleNames",roleNames);


        }

        data.success(mapIPage);
        return data;
    }

    /**
     * 查找审批用户信息
     * @param roleName	角色名称
     * @param orgId	组织机构编码
     * @return
     */
    @RequestMapping(value="/getAuditUser", method = RequestMethod.GET)
    @ApiOperation(value="查询用户信息", notes = "查找审批用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName", value = "角色名称", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构编码", paramType = "query")
    })
    public List<Map<Object, Object>> getAuditUserInfo(  String roleName,  String orgId) {
        Map<Object, Object> map = new HashMap<>();
        if ( StrUtil.isNotBlank(roleName)&& StrUtil.isNotBlank(orgId)) {
            map.put("roleName", roleName);
            map.put("orgId", orgId);
        }
        List<Map<Object, Object>> listMap = userInfoService.queryAuditUser(map);
        return listMap;
    }


    @ApiOperation(value="查询", notes="根据ID查询数据")
    @GetMapping("getOne/{userId}")
    public Map<String, Object> getOne(@PathVariable("userId") String userId) {
        Map<String, Object> modelMap = new HashMap<>();
        // JSON字符串转对象
        ObjectMapper mapper = new ObjectMapper();
        UserInfoVo userInfoVo = userInfoService.selectUserInfoVoById(userId);
        if(userInfoVo !=null) {
            modelMap.put("userInfo", userInfoVo);
        }
        OrgInfo orgInfo = orgInfoService.getById(userInfoVo.getOrgId());
        List<RoleInfo> userRoleByUserID = roleInfoService.getUserRoleByUserID(userId);
        if(userRoleByUserID!=null && userRoleByUserID.size()>0) {
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < userRoleByUserID.size(); i++) {
                RoleInfo s = userRoleByUserID.get(i);
                strings.add(s.getRoleId());
            }
            userInfoVo.setRoleIds(strings);
            //OrgInfo orgInfo = (OrgInfo)request.getSession().getAttribute("orgInfo");
            modelMap.put("orgInfo", orgInfo);
        }



        return modelMap;
    }
    /**
     * 单点登录
     * @return
     */
    @RequestMapping(value="/ssoLogin", method = RequestMethod.GET)
    @ApiOperation(value="单点登录", notes = "单点登录")
    public ResultUtil<Map> ssoLogin1(String code) {
        ResultUtil<Map> data = new ResultUtil<>();
        JSONObject returnJson = userInfoService.ssoLogin(code);
        if (returnJson.getBool("success")){
            System.out.println(returnJson);
            return data.success(returnJson.getJSONObject("map"));
        }else{
            data.failed(returnJson.getStr("message"));
            return data;
        }
    }
    /**
     * 单点登录
     * @return
     */
    @RequestMapping(value="/callBack", method = RequestMethod.GET)
    @ApiOperation(value="单点登录进行页面跳转", notes = "页面跳转")
    public void callBack(@ApiParam(value = "code") String code, HttpServletRequest request,HttpServletResponse response) {
        ResultUtil<Map> data = new ResultUtil<>();
        try {
            String url=null;
            SysParams byId = sysParamsService.getById("yingshe.url");
            if(ObjectUtils.isEmpty(byId)){
                 url = "http://" + request.getLocalAddr()+":"+request.getLocalPort();
            }else{
                url=byId.getParamVal();
            }
            response.sendRedirect(url+"/web/#/welcome?code="+code);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * DDM用户登录
     * @param          name
     * @return
     */
    @GetMapping(value="ddmLogin/{name}")
    @ApiOperation(value="用户登录名称登陆", notes = "ddm用户登录名称登陆")
    public void ddmLogin(@PathVariable(value = "name") String name,HttpServletRequest request,HttpServletResponse response) throws IOException {
        try {
            String url=null;
            SysParams byId = sysParamsService.getById("yingshe.url");
            if(ObjectUtils.isEmpty(byId)){
                url = "http://" + request.getLocalAddr()+":"+request.getLocalPort();
            }else{
                url=byId.getParamVal();
            }
            response.sendRedirect(url+"/web/#/welcomeddm?name="+name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * DDM单点登录
     * @return
     */
    @GetMapping(value="/ddmSsoLogin/{name}")
    @ApiOperation(value="ddm单点登录", notes = "ddm单点登录")
    public ResultUtil<Map> ddmSsoLogin(@PathVariable(value = "name") String name) {
        ResultUtil<Map> data = new ResultUtil<>();
        JSONObject returnJson = userInfoService.ddmLogin(name);
        if (returnJson.getBool("success")){
            System.out.println(returnJson);
            return data.success(returnJson.getJSONObject("map"));
        }else{
            data.failed(returnJson.getStr("message"));
            return data;
        }
    }

    /**
     * 下载用户中心用户数据
     * @return
     */
    @RequestMapping(value="/downSsoUserInfos", method = RequestMethod.POST)
    @ApiOperation(value="下载用户", notes = "下载用户中心用户数据")
    public ResultUtil<JSONObject> downSsoUserInfos(@RequestBody JSONObject jsonObject) {
        ResultUtil<JSONObject> data = new ResultUtil<>();
        JSONObject returnJSON = userInfoService.downSsoUserInfos(jsonObject);
        if (returnJSON.getBool("success")){
            data.success(returnJSON.getStr("message"));
        }else{
            data.failed(returnJSON.getStr("message"));
        }
        return data;
    }

    /**
     * 用户登录
     * @param          userLongVo
     * @return
     */
    @RequestMapping(value="/login", method = RequestMethod.POST)
    @ApiOperation(value="用户登录", notes = "用户登录(用户名,密码)")
    public ResultUtil<Map> Login( @RequestBody UserLongVo userLongVo) {
        String username = userLongVo.getUsername();
        String password=userLongVo.getPassword();
        Map<String, Object> map = new HashMap<String, Object>();
        String token=null;
        ResultUtil<Map> data = new ResultUtil<>();
        HashMap hashMap1 = new HashMap();
        // 获取MD5加密后的字符串
        password = SecureUtil.md5(password);
        // 把用MD5加密过的密码再用SHA1的方式加密一次，然后用SHA1加密后的密码去数据库中保存的密码做检索
        password = SHA1Util.encode(password);
        QueryWrapper<UserInfo> userInfoQuery = new QueryWrapper<>();
        userInfoQuery.eq("username",username);
        List<UserInfo> userInfou =userInfoService.list(userInfoQuery);

        if(userInfou == null  || userInfou.size()<1){
            data.failed("用户名错误");
            return data;
        }

        userInfoQuery.eq("password",password);
        List<UserInfo> userInfop =userInfoService.list(userInfoQuery);
        if(userInfop == null  || userInfop.size()<1){
            data.failed("密码错误");
            return data;
        }

        HashMap hashMap = new HashMap();
        hashMap.put("username",username);
        hashMap.put("password",password);

        List<UserInfoVo> userInfoVos = UserInfoMapper.selectUserInfoVo(hashMap);

        if ( userInfoVos!=null && userInfoVos.size()>0) {
            UserInfoVo userInfoVo = userInfoVos.get(0);
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id",userInfoVo.getUserId());
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
            List<String> roleIds = new ArrayList<>();
            List<String> roleNames = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                roleIds.add(userRole.getRoleId());
                roleNames.add(roleInfoService.getById(userRole.getRoleId()).getRoleName());
            }
            userInfoVo.setRoleIds(roleIds);
            userInfoVo.setRoleNames(roleNames);
            token= TokenUtil.sign(userInfoVo);
            hashMap1.put("token", token);
            hashMap1.put("userInfo", userInfoVo);
            UserOperationlog userOperationlog = new UserOperationlog();
            userOperationlog.setUserId(Integer.parseInt(userInfoVo.getUserId()));
            userOperationlog.setOperationTime(new Date());
            userOperationlog.setUotId(LogConstant.LOGIN);
            userOperationlog.setParameterValue("登录");
            userOperationlogService.save(userOperationlog);
        }

        return data.success(hashMap1);
    }
    /**
     * 用户登录
     * @return
     */
    @RequestMapping(value="/loginAuto", method = RequestMethod.GET)
    @ApiOperation(value="用户登录", notes = "用户登录(用户名,密码)")
    public ResultUtil<Map> LoginAuto() {
        String username = "zms";
        String password="123456";
        Map<String, Object> map = new HashMap<String, Object>();
        String token=null;
        ResultUtil<Map> data = new ResultUtil<>();
        HashMap hashMap1 = new HashMap();
        // 获取MD5加密后的字符串
        password = SecureUtil.md5(password);
        QueryWrapper<UserInfo> userInfoQuery = new QueryWrapper<>();
        userInfoQuery.eq("username",username);
        List<UserInfo> userInfou =userInfoService.list(userInfoQuery);

        if(userInfou == null  || userInfou.size()<1){
            data.failed("用户名错误");
            return data;
        }

        userInfoQuery.eq("password",password);
        List<UserInfo> userInfop =userInfoService.list(userInfoQuery);
        if(userInfop == null  || userInfop.size()<1){
            data.failed("密码错误");
            return data;
        }

        HashMap hashMap = new HashMap();
        hashMap.put("username",username);
        hashMap.put("password",password);

        List<UserInfoVo> userInfoVos = UserInfoMapper.selectUserInfoVo(hashMap);

        if ( userInfoVos!=null && userInfoVos.size()>0) {
            UserInfoVo userInfoVo = userInfoVos.get(0);
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id",userInfoVo.getUserId());
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
            List<String> roleIds = new ArrayList<>();
            List<String> roleNames = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                roleIds.add(userRole.getRoleId());
                roleNames.add(roleInfoService.getById(userRole.getRoleId()).getRoleName());
            }
            userInfoVo.setRoleIds(roleIds);
            userInfoVo.setRoleNames(roleNames);
            token= TokenUtil.sign(userInfoVo);
            hashMap1.put("token", token);
            hashMap1.put("userInfo", userInfoVo);
            UserOperationlog userOperationlog = new UserOperationlog();
            userOperationlog.setUserId(Integer.parseInt(userInfoVo.getUserId()));
            userOperationlog.setOperationTime(new Date());
            userOperationlog.setUotId(LogConstant.LOGIN);
            userOperationlog.setParameterValue("登录");
            userOperationlogService.save(userOperationlog);
        }

        return data.success(hashMap1);
    }
    @ApiOperation(value = "获取登录验证码")
    @GetMapping("/captcha")
    public ResultUtil captcha() {
        ResultUtil<Map> data = new ResultUtil<>();
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(130, 48, 4, 4);
        String verCode = captcha.getCode();
        String key = IdUtil.simpleUUID();
        HashMap<String, String> map = new HashMap();
        map.put("key", key);
        map.put("image", captcha.getImageBase64());
        map.put("verCode",verCode);
        return data.success(map);
    }
    /**
     * 获取用户登录信息,包括当前用户、当前组织、当前库、当前库编号
     * @param userId
     * @return
     */


    @ApiOperation(value="获取用户登录信息", notes="根据用户ID获取用户登录信息")
    @GetMapping("getLoginInfoVo/{userId}")
    public Map<String, Object> getLoginInfoVo(@PathVariable("userId") String userId) {
        Map<String, Object> modelMap = new HashMap<>();
            // JSON字符串转对象
            ObjectMapper mapper = new ObjectMapper();
            UserInfoVo userInfoVo = userInfoService.selectUserInfoVoById(userId);
            if(userInfoVo !=null) {
                modelMap.put("userInfo", userInfoVo);
            }
            OrgInfo orgInfo = orgInfoService.getById(userInfoVo.getOrgId());
            if(orgInfo !=null) {
                //OrgInfo orgInfo = (OrgInfo)request.getSession().getAttribute("orgInfo");
                modelMap.put("orgInfo", orgInfo);
            }



        return modelMap;
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping(value="/exitLogin", method = RequestMethod.GET)
    @ApiOperation(value="退出登录", notes = "退出登录，删除session")
    public Map<String, Object> exitLogin(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        request.getSession().removeAttribute("userInfo");
        request.getSession().removeAttribute("orgInfo");
        request.getSession().removeAttribute("depotInfo");
        request.getSession().removeAttribute("orgId");
        request.getSession().removeAttribute("depotId");
        request.getSession().invalidate();//强制销毁session
        MySessionContext.DelSession(request.getSession());
        modelMap.put("status", "success");
        return modelMap;
    }


    @ApiOperation(value="验证用户名", notes="验证用户名是否可用")
    @GetMapping("validUsername/{userId,username}")
    public Boolean validUsername(  @PathVariable("userId") String userId,  @PathVariable("username") String username) {
        return userInfoService.validUsername(userId, username);
    }
    /**
     * 通过用户名查询手机号
     * @param username	用户名
     * @return
     */
    @RequestMapping(value="/queryPhoneByusername", method = RequestMethod.GET)
    @ApiOperation(value="查询手机号", notes = "通过用户名查询手机号")
    public Map<String,Object> queryPhoneByusername(  String username) {
        Map<String,Object> map = new HashMap<String,Object>();
        String phone = userInfoService.queryPhoneByusername(username);
        map.put("phone", phone);
        return map;
    }
    /**
     * 验证手机号是否存在
     * @param phoneNumber	手机号
     * @return
     */
    @RequestMapping(value="/validPhone", method = RequestMethod.GET)
    @ApiOperation(value="验证手机号", notes = "验证手机号是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户编号", paramType = "query")
    })
    public Boolean validPhone(  String phoneNumber,   String  userId) {
        boolean flag = false;
        String username = userInfoService.validPhone(phoneNumber,userId);
        if(!username.equals("")) {
            flag = true;
        }
        return flag;
    }

    /**
     * 验证用户输入的原密码是否正确
     * @param oldPassword	用户输入的原密码
     * @return
     */
    @RequestMapping(value="/validPassword", method = RequestMethod.GET)
    @ApiOperation(value="验证用户输入的原密码是否正确", notes = "验证用户输入的原密码是否正确")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "用户密码", paramType = "query")
    })
    public boolean validPassword(HttpServletRequest request,   String oldPassword) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        String userInfoObject = org.apache.commons.lang.ObjectUtils.toString(request.getSession().getAttribute("userInfo"),"");
        UserInfoVo userInfo = mapper.readValue(userInfoObject, UserInfoVo.class);
        String resPassword = userInfo.getPassword();
        return userInfoService.validPassword(resPassword, oldPassword);
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @RequestMapping(value="/resetPassword", method = RequestMethod.POST)
    @ApiOperation(value="重置密码", notes = "重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户编号"),
            @ApiImplicitParam(name = "userPwd", value = "用户密码")
    })
    public void resetPassword(  String userId,  String userPwd) {
        userInfoService.resetPassword(userId,userPwd);
    }

    /**
     * 根据编号查找用户信息
     * @param userId 用户编号
     * @return	UserInfo	用户信息
     */
    @RequestMapping(value="/getUserRolesInfoByid", method = RequestMethod.GET)
    @ApiOperation(value="根据编号查找用户信息", notes = "根据编号查找用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户编号", paramType = "query")
    })
    public UserInfoVo getUserRolesInfoByid(  String userId) {
        UserInfoVo user = new UserInfoVo();
        HashMap<Object, Object> map = new HashMap<Object, Object>();
        map.put("username", userId);
//        if (userId != null) {
        if (StrUtil.isNotBlank(userId)) {
            user = this.userInfoService.selectUserInfoVoById(userId);
        }
        //if("正常".equals(NetStateUtil.connectingAddress(wsdlUrl))) {
        try {
            List<String> roleIds = user.getRoleIds();
            List<RoleInfo> data = roleInfoService.getUserRoleByUserID(user.getUserId());
            for(int i=0;i<data.size();i++) {
                RoleInfo roleInfo = data.get(i);
                roleIds.add(roleInfo.getRoleId());
            }
            user.setRoleIds(roleIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //}
        return user;
    }

    /**
     *
     * @param userInfoVo
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @RequestMapping(value="/save", method = RequestMethod.POST)
    @ApiOperation(value="保存用户", notes = "保存用户信息，新增或者修改")
    public Map<String, Object> save( @RequestBody UserInfoVo userInfoVo) throws Exception {
        List<String> roleIds = userInfoVo.getRoleIds();

        Map<String, Object> modelMap = new HashMap<>();

        UserInfo userInfo = userInfoVo;
        //检查用户名是否存在
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("username",userInfo.getUsername());
        //修改排除当前用户
        if(StrUtil.isNotBlank(userInfo.getUserId())){
            userInfoQueryWrapper.ne("user_id",userInfo.getUserId());
        }
        userInfoQueryWrapper.last("limit 1");
        UserInfo userInfo1 = userInfoService.getOne(userInfoQueryWrapper);
        if (userInfo1 != null){ //表示用户已经存在,排除修改
            modelMap.put("status", "failed");
            modelMap.put("msg", "用户名已存在");
            return modelMap;
        }
        if(StrUtil.isBlank(userInfo.getUserId())){
            userInfoService.save(userInfo);
        }else{
            userInfoService.updateById(userInfo);
            userRoleService.deleteByUserID(userInfo.getUserId());
        }

        if (roleIds!=null &&  roleIds.size()>0) {
            for (String id : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userInfo.getUserId());
                userRole.setUrId(IdUtil.simpleUUID());
//                userRole.setRoleId(Integer.parseInt(id));
                userRole.setRoleId(id);
                userRoleService.save(userRole);
            }
        }
        modelMap.put("status", "success");
        return modelMap;
    }
    /**
     * 修改密码
     * @param request
     * @param oldPassword	原密码
     * @param newPassword	新密码
     * @return
     */
    @RequestMapping(value="/modifyPwd", method = RequestMethod.POST)
    @ApiOperation(value="修改密码", notes = "修改用户登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "原密码"),
            @ApiImplicitParam(name = "newPassword", value = "新密码")
    })
    public UserInfoVo modifyPwd(HttpServletRequest request,  String oldPassword, String newPassword) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String userInfoObject = org.apache.commons.lang.ObjectUtils.toString(request.getSession().getAttribute("userInfo"),"");
            UserInfoVo userInfo = mapper.readValue(userInfoObject, UserInfoVo.class);
            if (userInfo.getPassword().equals( SecureUtil.md5(oldPassword)) ) {
                userInfo.setPassword(SecureUtil.md5(newPassword) );
                userInfoService.updateById(userInfo);

                String userInfoObjectNew = mapper.writeValueAsString(userInfo);
                request.getSession().setAttribute("userInfo", userInfoObjectNew);
                return userInfo;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 查询当前库下所有的用户
     * @param orgId
     * @return
     */
    @RequestMapping(value="/findAllUserByOrgId", method = RequestMethod.GET)
    @ApiOperation(value="查询当前库下所有的用户", notes = "查询当前库下所有的用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "单位ID", paramType = "form")
    })
    public List<UserInfo> findAllUserByOrgId( @RequestBody String orgId){
        List<UserInfo> list = null;
        try {

            list = userInfoService.findAllUserByOrgId(orgId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 查询当前库下所有的用户枚举，返回id与用户姓名的map.
     * @param request
     * @return
     */
    @RequestMapping(value="/findAllUserMapByOrgId", method = RequestMethod.GET)
    public Map<String, Object> findAllUserMapByOrgId(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            String depotInfoObject =  org.apache.commons.lang.ObjectUtils.toString(request.getSession().getAttribute("depotInfo"),"");
            if(!depotInfoObject.isEmpty()) {
                OrgInfo orgInfo = mapper.readValue(depotInfoObject, OrgInfo.class);
                List<UserInfo> list = null;
                try {
                    String orgId = null;
                    if (orgInfo != null) {
                        orgId=orgInfo.getOrgId().toString();//所属库id
                    }
                    // 拼接查询条件单位
//                    if (null != orgId && !"".equals(orgId)) {
                    if (StrUtil.isNotBlank(orgId)) {
                        list = userInfoService.findAllUserByOrgId(orgId);
                    }
                    for (UserInfo userInfo : list) {
                        map.put(userInfo.getUserId(), userInfo.getRealName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return map;
    }
    /**
     * 生成验证码图片, 并将验证码图片上传到服务器，然后将生成的验证码串值保存到session 中
     *
     * @param request
     **/
    @RequestMapping(value="/getCode", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value="生成验证码图片", notes = "生成验证码图片")
    public Map<String, Object> getCode(HttpServletRequest request,  Integer fontSize,  Integer width,   Integer heigth) {

        // 图片流
        BufferedImage image;

        // 获取验证码数字字符串
        String yzm_code = SecurityCode.getSecurityCode(4, SecurityCode.SecurityCodeLevel.Hard, false).toLowerCase();
        request.getSession().setAttribute("Service_Code", yzm_code);
        // 生成验证码图片
        image = SecurityImage.createImage(yzm_code, fontSize, width, heigth);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        //将图片转换为base64位二进制编码返回
        String imgBase64 = new Base64().encode(baos.toByteArray());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("file", imgBase64);
        return map;
    }
    /**
     * 查询全部数据
     * @return
     */
    @ApiOperation(value="查询", notes="查询全部数据")
    @GetMapping("getAll")
    public ResultUtil getAll(){
        ResultUtil<List<UserInfo>> data = new ResultUtil<>();
        data.success(this.userInfoService.list());
        return data;
    }


    /**
     * 新增一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="新增", notes="新增一条数据")
    @PostMapping("add")
    public ResultUtil add(@RequestBody UserInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.userInfoService.save(param));
        return data;
    }


    /**
     * 修改一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="修改", notes="修改一条数据")
    @PatchMapping("edit")
    public ResultUtil edit(@RequestBody UserInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.userInfoService.updateById(param));
        return data;
    }


    /**
     * 根据ID删除数据
     * @param id
     * @return
     */
    @ApiOperation(value="删除", notes="根据ID删除数据")
    @DeleteMapping("delete/{id}")
    public ResultUtil delete(@PathVariable("id") String id){
        LOGGER.info("入参为:{}", id);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(id)){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.userInfoService.removeById(id));
        return data;
    }


}

