package com.sunda.spmsweb.usercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.OrderKeyValueConfig;
import com.sunda.spmsorder.service.IOrderKeyValueConfigService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.excel.SpmsUserExcel;
import com.sunda.spmsuser.service.*;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.ExcelUtil;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmsweb.util.MD5Utils;
import com.sunda.spmswms.service.IWerksService;
import com.sunda.spmswms.service.IWhsService;
import com.sunda.spmswms.service.IWorkshopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmscommon.Constans.SUCCESS;

/**
 * <p>
 * SPMS用户信息表 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-01-25
 */
@RestController
@RequestMapping("/spmsUser")
@Api(tags = "系统用户接口", description = "系统用户接口")
public class SpmsUserController {

    @Autowired
    ISpmsUserService iSpmsUserService;
    
    @Autowired
    ISpmsRoleService iSpmsRoleService;

    @Autowired
    ISpmsUserWhsService iSpmsUserWhsService;

    @Autowired
    ISpmsUserWorkshopService iSpmsUserWorkshopService;

    @Autowired
    IWhsService iWhsService;
    @Autowired
    IWorkshopService iWorkshopService;

    @Autowired
    IWerksService iWerksService;

    @Autowired
    ISpmsPermissionService iSpmsPermissionService;
    @Autowired
    IOrderKeyValueConfigService iOrderKeyValueConfigService;

    @Value("${oa.new.url}")
    String oaUrl;
    
    @Value("${oa.ipo.url}")
    String oaIpoUrl;

    @RequestMapping("/getUserListByPage")
    @ApiOperation(value = "获取全部用户分页信息",notes = "获取全部用户分页信息", httpMethod = "GET")
    public ResponseResult getUserListByPage(@RequestParam(defaultValue = "1") int pageNo ,
                                            @RequestParam(defaultValue = "20") int pageSize) {
        Page<SpmsUser> page = new Page<>(pageNo,pageSize);
        try{
            return ResponseResult.success().add("pageInfo", iSpmsUserService.spmsUserList(page));
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }
    
    @RequestMapping("/findUserListByPage")
    @ApiOperation(value = "分页获取用户信息", notes = "分页获取用户信息。\n" +
    		"{\n" +
            "\t\t\t\"userId\": \"用户ID\",\n" +
            "\t\t\t\"lastName\": \"用户姓名\",\n" +
            "\t\t\t\"company\": \"公司\",\n" +
            "\t\t\t\"subcompanyName\": \"分公司\",\n" +
            "\t\t\t\"deptName\": \"部门\",\n" +
            "\t\t\t\"spmsStatus\": \"状态\",\n" +
            "\t\t\t\"positionName\": \"职位\",\n" +
            "\t\t\t\"pageNo\": 1,\n" +
            "\t\t\t\"pageSize\": 20\n" +
            "\t\t}", httpMethod = "POST")
    @RequiresPermissions("spmsUser-getUserListByPage")
    public ResponseResult findUserListByPage(@RequestBody JSONObject jsonObject){
    	try {
    		if (!jsonObject.containsKey("pageNo") || !jsonObject.containsKey("pageSize")){
                return ResponseResult.error("请求参数错误");
            }
    		return ResponseResult.success().add("pageInfo", iSpmsUserService.getUserListByParam(jsonObject));
    	}catch (Exception e){
    		e.printStackTrace();
    		return ResponseResult.error("请求数据失败").add("error", e.getMessage());
    	}
    }

    @RequestMapping("/getAllUserList")
    @ApiOperation(value = "获取全部用户信息不分页",notes = "获取全部用户信息不分页", httpMethod = "GET")
    @RequiresPermissions("spmsUser-getAllUserList")
    public ResponseResult getAllUserList() {
        try{
            return ResponseResult.success().add("spmsUserList", iSpmsUserService.getAllSpmsUserList());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    /**
     * 导出车间请购单详情
     */
    @RequestMapping("/exportAllUserList")
    @ApiOperation(value = "导出全部用户信息", notes = "获取全部用户信息不分页", httpMethod = "POST")
    public void exportAllUserList(HttpServletResponse response) {
        try {
            List<SpmsUser> result = iSpmsUserService.getAllSpmsUserList();
            List<SpmsUserExcel> itemList = new ArrayList<SpmsUserExcel>();
            if(result!=null && result.size()>0) {
                for (int i = 0; i < result.size(); i++) {
                    SpmsUser map =   result.get(i);
                    SpmsUserExcel report = JSONObject.parseObject(JSONObject.toJSONString(map), SpmsUserExcel.class);
                    itemList.add(report);
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateTime = sdf.format(new Date() );
            ExcelUtil.export(response, "AllUserList" + dateTime, "bodyData", itemList, SpmsUserExcel.class);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @RequestMapping("/userProfile")
    @ApiOperation(value = "获取用户配置信息SPMS",notes = "根据用户工号获取用户配置信息，如果系统存在则返回用户在本系统配置信息，" +
            "如果不存在则从OA请求用户信息。userId = 999950",
            httpMethod = "POST")
    @RequiresPermissions("spmsUser-userProfile")
    public ResponseResult userProfile(@RequestParam String userId) {
        try{
            SpmsUser userInfo = iSpmsUserService.getByUserId(userId);
            if (userInfo != null && userInfo.toString().length() > 0){
                List<Map<String, Object>> roleList = iSpmsRoleService.getRoleById(userId);
                List<Map<String, Object>> userWhs = iSpmsUserWhsService.getUserWhsList(userId);
                List<Map<String, Object>> userWorkshop = iSpmsUserWorkshopService.getUserWorkshopList(userId);
                return ResponseResult.success()
                        .add("userInfo", userInfo)
                        .add("userRole", roleList)
                        .add("userWhs", userWhs)
                        .add("userWorkshop", userWorkshop);
            }else {
            	// 用户信息从MDM获取 2023-12-27 XZP add
//            	Map<String, Object> map = iSpmsUserService.getMdmUserInfo(userId);
//            	if (map == null){
//            		return ResponseResult.error("从MDM获取用户信息失败");
//                }
//            	if (!"1".equals(map.get("oaStatus"))) {
//                	return ResponseResult.error("用户："+userId+"状态为离职状态，不能添加用户");
//                }
                OaService oaService = new OaService();
                List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
                boolean newOa = false;
                if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                    String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                    if("0".equals(oaConfig)){//0:启用新OA接口
                        newOa = true;
                    }
                }
                Map<String, Object> map = new HashMap<>();
                // 工号30开头的用户信息从OA-IPO获取，不是30开头的从OA集团获取
                String url = oaUrl;
                if (userId.startsWith("30")) {
                	url = oaIpoUrl;
                }
                if(newOa){
                	map = oaService.getUserInfoByOaV2(userId,url);
                }else{
                	map = oaService.getUserInfo(userId);
                }
                if (map == null){
                    return ResponseResult.error("获取OA用户信息为空");
                }
                // 判断用户在OA状态是否可用，不可用就不能创建SPMS用户账号（OA状态值大于等于4的为不可用，小于4的为可用）
                if (!"0".equals(map.get("oaStatus")) && !"1".equals(map.get("oaStatus")) && !"2".equals(map.get("oaStatus")) && !"3".equals(map.get("oaStatus"))) {
                	return ResponseResult.error("用户："+userId+"OA状态为不可用，不能添加用户");
                }

                return ResponseResult.success().add("userInfo", map);
            }
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getUserInfo")
    @ApiOperation(value = "根据工号获取用户详细信息OA",notes = "获取指定工号的用户详细信息，示例 userId = 999950",
            httpMethod = "POST")
    @RequiresPermissions("spmsUser-getUserInfo")
    public ResponseResult getOrderScenario(String userId) {
        OaService oaService = new OaService();
        try{
        	// 获取用户从OA改为从MDM获取 2023-12-28 xzp add 
//        	Map<String, Object> map = iSpmsUserService.getMdmUserInfo(userId);
//        	if (map == null){
//                return ResponseResult.error("从MDM获取用户信息失败");
//            }
//        	if (!"1".equals(map.get("oaStatus"))) {
//            	return ResponseResult.error("用户："+userId+"状态为离职状态，不能添加用户");
//            }
            List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
            boolean newOa = false;
            if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                if("0".equals(oaConfig)){//0:启用新OA接口
                    newOa = true;
                }
            }
            Map<String, Object> map = new HashMap<>();
            // 工号30开头的用户信息从OA-IPO获取，不是30开头的从OA集团获取
            String url = oaUrl;
            if (userId.startsWith("30")) {
            	url = oaIpoUrl;
            }
            if(newOa){
                map = oaService.getUserInfoByOaV2(userId,url);
            }else{
                map = oaService.getUserInfo(userId);
            }
            if (map == null){
                return ResponseResult.error("从OA获取用户信息失败");
            }
            // 判断用户在OA状态是否可用，不可用就不能创建SPMS用户账号（OA状态值大于等于4的为不可用，小于4的为可用）
            if (!"0".equals(map.get("oaStatus")) && !"1".equals(map.get("oaStatus")) && !"2".equals(map.get("oaStatus")) && !"3".equals(map.get("oaStatus"))) {
            	return ResponseResult.error("用户："+userId+"OA状态为不可用，不能添加用户");
            }
            return ResponseResult.success().add("userInfo", map);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/createSpmsUser")
    @ApiOperation(value = "新增/更新用户",notes = "新增或更新用户，传入JSON字符串格式，传入参数示例中：userId 必填，其余字段值可选。\n" +
            "loginPassword 后台默认 123456，传值会被忽略\n" +
            "{\n" +
            "\t\"userInfo\": {\n" +
            "\t\t\"userId\": \"20001\",\n" +
            "\t\t\"workId\": \"20001\",\n" +
            "\t\t\"lastName\": \"20001\",\n" +
            "\t\t\"telephone\": \"13866668888\",\n" +
            "\t\t\"mobile\": \"13866668888\",\n" +
            "\t\t\"email\": \"sunda@sunda.com\",\n" +
            "\t\t\"positionId\": \"11\",\n" +
            "\t\t\"positionName\": \"position name\",\n" +
            "\t\t\"deptId\": \"123\",\n" +
            "\t\t\"deptName\": \"dept name\",\n" +
            "\t\t\"subcompanyId\": \"1234\",\n" +
            "\t\t\"subcompanyName\": \"subcompany id\",\n" +
            "\t\t\"company\": \"company\",\n" +
            "\t\t\"branchPoint\": \"12345\",\n" +
            "\t\t\"branchLine\": \"123456\",\n" +
            "\t\t\"managerId\": \"10000\",\n" +
            "\t\t\"managerName\": \"10000\",\n" +
            "\t\t\"oaStatus\": \"1\",\n" +
            "\t\t\"spmsStatus\": \"1\"\n" +
            "\t},\n" +
            "\t\"userRole\": [{\n" +
            "\t\t\"uuid\": \"161556d97ae44139ad21659c5fb98e00\",\n" +
            "\t\t\"roleId\": \"1001\"\n" +
            "\t}],\n" +
            "\t\"userWhs\": [{\n" +
            "\t\t\"werks\": \"CN01\",\n" +
            "\t\t\"whsLocationCode\": \"1061\"\n" +
            "\t}],\n" +
            "\t\"userWorkshop\": [{\n" +
            "\t\t\"werks\": \"GH01\",\n" +
            "\t\t\"workshopCode\": \"1002\"\n" +
            "\t}]\n" +
            "}", httpMethod = "POST")
    @ApiImplicitParam(name = "jsonObject", value = "JSONObject 示例字符串", dataTypeClass = String.class, required = true, paramType = "body", dataType = "string")
    @RequiresPermissions("spmsUser-createSpmsUser")
    public ResponseResult createSpmsUser(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("userInfo") || jsonObject.getString("userInfo").length() == 0){
            return ResponseResult.error("参数错误请重试！");
        }
        JSONObject userInfo = jsonObject.getJSONObject("userInfo");
        if (!userInfo.containsKey("userId") || userInfo.getString("userId").length() == 0){
            return ResponseResult.error("参数错误请重试！");
        }
        String userId = userInfo.getString("userId");
        //String loginPassword = userInfo.getString("loginPassword");
        String MDPassword = MD5Utils.encrypt(userId, "12345678");
        return iSpmsUserService.createSpmsUser(jsonObject, MDPassword);

    }
    
    @RequestMapping("/createSystemUser")
    @ApiOperation(value = "新增系统用户",notes = "新增系统用户，传入JSON字符串格式，传入参数示例中：字段都必填。\n" +
    		"{\n" +
    		"\t\"userInfo\": {\n" +
    		"\t\t\"userId\": \"20001\",\n" +
    		"\t\t\"lastName\": \"20001\",\n" +
    		"\t\t\"positionName\": \"position name\",\n" +
    		"\t\t\"deptName\": \"dept name\",\n" +
    		"\t\t\"spmsStatus\": \"1\"\n" +
    		"\t}\n" +
    		"}", httpMethod = "POST")
    @ApiImplicitParam(name = "jsonObject", value = "JSONObject 示例字符串", dataTypeClass = String.class, required = true, paramType = "body", dataType = "string")
    @RequiresPermissions("spmsUser-createSystemUser")
    public ResponseResult createSystemUser(@RequestBody JSONObject jsonObject) {
    	if (!jsonObject.containsKey("userInfo") || jsonObject.getString("userInfo").length() == 0){
    		return ResponseResult.error("参数错误请重试！");
    	}
    	JSONObject userInfo = jsonObject.getJSONObject("userInfo");
    	if (!userInfo.containsKey("userId") || userInfo.getString("userId").length() == 0){
    		return ResponseResult.error("用户ID不能为空");
    	}
    	String userId = userInfo.getString("userId");
    	//String loginPassword = userInfo.getString("loginPassword");
    	String MDPassword = MD5Utils.encrypt(userId, "12345678");
    	String operationUserId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    	return iSpmsUserService.createSystemUser(jsonObject, MDPassword, operationUserId);
    	
    }

    @RequestMapping("/updatePassword")
    @ApiOperation(value = "更新登录密码",notes = "更新登录密码", httpMethod = "GET")
    public ResponseResult updatePassword(String userId, String password) {
        try{
            return iSpmsUserService.updatePassword(userId, MD5Utils.encrypt(userId, password));
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getWerksInfo")
    @ApiOperation(value = "获取全部工厂仓库车间角色信息",notes = "获取全部工厂仓库车间角色基本信息",
            httpMethod = "GET")
    public ResponseResult getWerksInfo() {
        try{
            return ResponseResult.success().add("whsInfo", iWhsService.getWhsList())
                    .add("workshopInfo", iWorkshopService.getWorkshopList())
                    .add("roleList", iSpmsRoleService.getRoleList())
                    .add("allWerks",iWerksService.getWerksList());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getRolePerm")
    @ApiOperation(value = "获取全部角色权限信息",notes = "获取全部权限表信息、全部角色权限关系表信息",
            httpMethod = "GET")
    public ResponseResult getRolePerm() {
        try{
            return ResponseResult.success().add("rolePermList", iSpmsPermissionService.getRolePerm())
                    .add("permissionList", iSpmsPermissionService.getAllPerm());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateSpmsUserInfo")
    @ApiOperation(value = "实时同步用户OA信息到SPMS",notes = "实时同步用户OA信息到SPMS",
            httpMethod = "GET")
    public ResponseResult updateSpmsUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)){
            return ResponseResult.error("请求参数不能为空");
        }
        try{
            OaService oaService = new OaService();
            List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
            boolean newOa = false;
            if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                if("0".equals(oaConfig)){//0:启用新OA接口
                    newOa = true;
                }
            }
            // 工号30开头的用户信息从OA-IPO获取，不是30开头的从OA集团获取
            String url = oaUrl;
            if (userId.startsWith("30")) {
            	url = oaIpoUrl;
            }
            Map<String, Object> map = new HashMap<>();
            if(newOa){
                map = oaService.getUserInfoByOaV2(userId,url);
            }else{
                map = oaService.getUserInfo(userId);
            }
            if (map == null || map.size() == 0){
                return ResponseResult.error("OA返回信息错误");
            }
            // 判断用户在OA状态是否可用，不可用就不能创建SPMS用户账号（OA状态值大于等于4的为不可用，小于4的为可用）
            if (!"0".equals(map.get("oaStatus")) && !"1".equals(map.get("oaStatus")) && !"2".equals(map.get("oaStatus")) && !"3".equals(map.get("oaStatus"))) {
            	return ResponseResult.error("用户："+userId+"OA状态为不可用，不能添加用户");
            }
        	// 从MDM获取用户信息
//        	Map<String, Object> map = iSpmsUserService.getMdmUserInfo(userId);
//        	if (map == null){
//                return ResponseResult.error("从MDM获取用户信息失败");
//            }
//        	if (!"1".equals(map.get("oaStatus"))) {
//            	return ResponseResult.error("用户："+userId+"状态为离职状态，不能添加用户");
//            }
            return iSpmsUserService.updateSpmsUserInfo(map);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateAllSpmsUserInfo")
    @ApiOperation(value = "一键同步所有用户OA信息到SPMS",notes = "一键同步所有用户OA信息到SPMS",
            httpMethod = "GET")
    @RequiresPermissions("spmsUser-updateAllSpmsUserInfo")
    public ResponseResult updateAllSpmsUserInfo() {
        try{
            List<SpmsUser> spmsUserList = iSpmsUserService.getAllSpmsUserList();
            int re = 0;

            List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
            boolean newOa = false;
            if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                if("0".equals(oaConfig)){//0:启用新OA接口
                    newOa = true;
                }
            }
            Map<String, Object> map = new HashMap<>();
            for (SpmsUser spmsUser : spmsUserList){
            	// 工号30开头的用户信息从OA-IPO获取，不是30开头的从OA集团获取
            	String url = oaUrl;
            	if (spmsUser.getUserId().startsWith("30")) {
            		url = oaIpoUrl;
            	}
                OaService oaService = new OaService();
                if(newOa){
                    map = oaService.getUserInfoByOaV2(spmsUser.getUserId(),url);
                }else{
                    map = oaService.getUserInfo(spmsUser.getUserId());
                }
               // Map<String, Object> map = oaService.getUserInfo(spmsUser.getUserId());
                //System.out.println(map);
                if (map != null && map.size() > 0){
                    ResponseResult updateResult = iSpmsUserService.updateSpmsUserInfo(map);
                    if (updateResult.getCode() == SUCCESS){
                        re += 1;
                    }
                }
            }
            return ResponseResult.success("更新完成").add("系统用户总数：", spmsUserList.size()).add("此次更新人数：", re);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }
    
    @RequestMapping("/copyUserProfile")
    @ApiOperation(value = "复制SPMS用户信息",notes = "复制SPMS用户信息" +
    			"copyUserId是被复制的用户工号，targetUserId是要创建用户的工号",
            httpMethod = "POST")
    @RequiresPermissions("spmsUser-copyUserProfile")
    public ResponseResult copyUserProfile(@RequestParam(required = true) String copyUserId, @RequestParam(required = true) String targetUserId) {
        try{
        	// 查询需要创建的用户在OA的状态是否可用，如果不可用则不能进行复制操作
        	OaService oaService = new OaService();
            List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
            boolean newOa = false;
            if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                if("0".equals(oaConfig)){//0:启用新OA接口
                    newOa = true;
                }
            }
            // 工号30开头的用户信息从OA-IPO获取，不是30开头的从OA集团获取
        	String url = oaUrl;
        	if (targetUserId.startsWith("30")) {
        		url = oaIpoUrl;
        	}
            Map<String, Object> map = new HashMap<>();
            if(newOa){
                map = oaService.getUserInfoByOaV2(targetUserId,url);
            }else{
                map = oaService.getUserInfo(targetUserId);
            }
            if (map == null){
                return ResponseResult.error("创建的用户："+targetUserId+"在OA不存在");
            }
            // 判断用户在OA状态是否可用，不可用就不能创建SPMS用户账号（OA状态值大于等于4的为不可用，小于4的为可用）
            if (!"0".equals(map.get("oaStatus")) && !"1".equals(map.get("oaStatus")) && !"2".equals(map.get("oaStatus")) && !"3".equals(map.get("oaStatus"))) {
            	return ResponseResult.error("用户："+targetUserId+"OA状态为不可用，不能添加用户");
            }
        	// 判断用户在MDM状态是否可用
//        	Map<String, Object> map = iSpmsUserService.getMdmUserInfo(targetUserId);
//        	if (map == null){
//                return ResponseResult.error("创建的用户："+targetUserId+"在MDM不存在");
//            }
//        	if (!"1".equals(map.get("oaStatus"))) {
//            	return ResponseResult.error("用户："+targetUserId+"状态为离职状态，不能添加用户");
//            }
        	// 可用则复制账号的权限
            SpmsUser userInfo = iSpmsUserService.getByUserId(copyUserId);
            if (userInfo != null && userInfo.toString().length() > 0){
                List<Map<String, Object>> roleList = iSpmsRoleService.getRoleById(copyUserId);
                List<Map<String, Object>> userWhs = iSpmsUserWhsService.getUserWhsList(copyUserId);
                List<Map<String, Object>> userWorkshop = iSpmsUserWorkshopService.getUserWorkshopList(copyUserId);
                JSONObject doc = new JSONObject();
                map.put("spmsStatus", "1");
                map.put("userId", targetUserId);
                doc.put("userInfo", map);
                doc.put("userRole", roleList);
                doc.put("userWhs", userWhs);
                doc.put("userWorkshop", userWorkshop);
                String MDPassword = MD5Utils.encrypt(targetUserId, "12345678");
                iSpmsUserService.saveSpmsUser(doc, MDPassword);
                return ResponseResult.success()
                        .add("userInfo", map)
                        .add("userRole", roleList)
                        .add("userWhs", userWhs)
                        .add("userWorkshop", userWorkshop);
            } else {
            	return ResponseResult.success().add("userInfo", map);
            }
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

}
