package cn.com.capcloud.api.action.myself.system;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.api.action.service.DataSourceService;
import cn.com.capcloud.api.action.service.MongoService;
import cn.com.capcloud.api.action.service.util.TextUtil;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.ccui.core.common.utils.StringUtil;
import cn.com.capcloud.core.noentitydb.*;
import cn.com.capcloud.core.util.*;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.system.security.JwtTokenProvider;
import cn.com.capcloud.core.system.security.MyUserDetails;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserRepository;
import cn.com.capcloud.core.system.user.UserService;
import cz.mallat.uasparser.UserAgentInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Component
public class UserAction extends DefaultAction {
    //创建用户时自动绑定角色(KEY)
    private static final String SYSTEM_SETTINGS_DS_USER_ROLE_DEFAULT="system.settings.ds.user.role.default";
    //系统配置(KEY)
    private static final String SYSTEM_SETTINGS_DS_SYSTEM_CONFIG_JSON="system.settings.ds.system.config.json";
    @Autowired
    private BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ApiService apiService;
    @Autowired
    private KHCRedisCache khcRedisCache;
    @Autowired
    private MyUserDetails myUserDetails;
    @Autowired
    private MongoService mongoService;
    @Autowired
    private IPSearcher ipSearcher;
    @Autowired
    private ReadProperty readProperty;
    @Autowired
    private DataSourceService dsService;
    private static UserAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.khcRedisCache =this.khcRedisCache;
        action.myUserDetails=this.myUserDetails;
        action.mongoService=this.mongoService;
        action.ipSearcher=this.ipSearcher;
        action.readProperty=this.readProperty;
        action.dsService=this.dsService;
    }
    public Map<String,Object> login(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
    	//todo 由于记录各种日志导致代码阅读较差，后续有时间回来优化一下。
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonStr);
        String username=String.valueOf(jsonObject.get("username"));
        //此参数也可存储，每次请求校验是否已存在，存在说明该请求是被爬虫拦截到请求参数二次请求。
        String passwordStr=String.valueOf(jsonObject.get("password"));
        String queryLoginPasswordCountSql="SELECT COUNT(1) FROM "+ TblLogNames.TBL_LOG_LOGIN_PASSWORD+" WHERE PASSWORD='"+passwordStr+"'";
        Integer queryLoginPasswordCount=this.getJdbcTemplate().queryForObject(queryLoginPasswordCountSql,Integer.class);
        if(queryLoginPasswordCount!=0){//已存在说明该请求体是被爬虫拦截到请求参数后使用第三方工具二次请求。
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("4009")));
            return new HashMap<>();
        }
        Map<String,Object> loginPasswordMap=new HashMap<>();
        loginPasswordMap.put("user_login_name", username);
        loginPasswordMap.put("password", passwordStr);
        action.baseService.save(TblLogNames.TBL_LOG_LOGIN_PASSWORD,loginPasswordMap);//mysql记录
        passwordStr=action.apiService.smDecrypt(passwordStr);//解析密码
        JackJSONObject passwordJson= JackJSONObject.fromObject(passwordStr);
        String ip= IPUtil.getIpAddress(request);
        String password=String.valueOf(passwordJson.get("password"));
        Map<String,Object> systemConfigMap= JackJSON.parseObject(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_SYSTEM_CONFIG_JSON)), HashMap.class);
        String token=null;
        User user=null;
        // start save login log 登录日志
        Map<String,Object> visMap=new HashMap<>();
        visMap.put("ip", ip);
        visMap.put("password","");
        visMap.put("user_login_name",username);//默认登录名，后面转成真实姓名
        visMap.put("name","3");//1：用户登录  2：用户登出  3：登录失败   默认状态3，登录成功则修改状态为1
        String userAgent = request.getHeader("User-Agent").toUpperCase();
        if (StringUtil.isNotEmpty(userAgent)) {
            try {
                UserAgentInfo userAgentInfo= UserAgentUtil.getUasParser().parse(userAgent);
                visMap.put("os_name",userAgentInfo.getOsName());
                String browser=UserAgentUtil.identifyBrowser(request);
                visMap.put("ua_family",browser);
                if(browser.equals("")){
                    visMap.put("ua_family",userAgentInfo.getUaFamily());
                }
            } catch (IOException e) {
            }
        }
        String yzmURL=String.valueOf(jsonObject.get("yzmURL"));
        String yzm=String.valueOf(jsonObject.get("yzm"));
        String cacheYZM=action.khcRedisCache.getYZMByURL(yzmURL,"");
        if(StringUtil.isEmpty(yzmURL)){
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10030")));
            visMap.put("msg","10030："+retJson.get("message"));
            if(DBCheck.isMongoDB()){
                action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }else{
                action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }
            return new HashMap<>();
        }
        if (yzmURL.endsWith(".jpg")) {
            deleteFile(action.readProperty.getCaptchaFilePath() + yzmURL);
        }
        if(StringUtil.isEmpty(yzm)||
                (cacheYZM.length()==0||!cacheYZM.equals(yzm))){
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10030")));
            visMap.put("msg","10030："+retJson.get("message"));
            if(DBCheck.isMongoDB()){
                action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }else{
                action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }
            action.khcRedisCache.deleteYZMByURL(yzmURL);
            return new HashMap<>();
        }
        action.khcRedisCache.deleteYZMByURL(yzmURL);
        try {
            action.userService.deleteByUserLoginName(username);//删除旧的用户缓存信息，确保每次登录都是最新的用户信息（含角色权限等等）
            user=action.userService.findByUserLoginName(username);
            if(user==null){
                retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10010")));
                visMap.put("msg","10010："+retJson.get("message"));
                if(DBCheck.isMongoDB()){
                    action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
                }else{
                    action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
                }
                return new HashMap<>();
            }
            String passwordErrorNum=String.valueOf(systemConfigMap.get("password_error_num"));
            if(!passwordErrorNum.equals("null")&&!passwordErrorNum.equals("0")&&passwordErrorNum.length()>0){
                if(user.getLoginCount()>=Integer.valueOf(passwordErrorNum)){
                    retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10013")));
                    visMap.put("msg","10013："+retJson.get("message"));
                    if(DBCheck.isMongoDB()){
                        action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
                    }else{
                        action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
                    }
                    return new HashMap<>();
                }
            }
            action.myUserDetails.getUserInfoMap().remove(username);
            if(user.getIsMultiDeviceLogin().equals("N")){
                token = action.userService.signing(username, password);
            }else{
                token = action.userService.signingByMultiDevice(username, password);//拥有多设备登录权限的用户
            }
            String sql="update tbl_system_user set login_count='0' where id="+user.getId();//登录成功后重置次数
            this.getJdbcTemplate().execute(sql);
            if(user.getUserStatus().equals("0")){
                BaseDao.setDefaultValue(visMap,user);
                String isSourceLimitL=user.getIsSourceLimit();
                if(isSourceLimitL.equals("Y")){//是否限源
                    String sourceIp=user.getSourceIp();
                    if(!sourceIp.contains(ip)&&!"127.0.0.1".contains(ip)){//白名单应该写成配置
                        retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10012")));
                        visMap.put("msg","10012："+retJson.get("message"));
                        retJson.put("message",retJson.get("message")+"，当前源IP("+ip+")");
                        if(DBCheck.isMongoDB()){
                            action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
                        }else{
                            action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
                        }
                        return new HashMap<>();
                    }
                }
            }else{
                retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10011")));
                visMap.put("msg","10011："+retJson.get("message"));
                if(DBCheck.isMongoDB()){
                    action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
                }else{
                    action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
                }
                return new HashMap<>();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	if(user!=null){
                long loginCount=user.getLoginCount()+1;
                String sql="update tbl_system_user set login_count='"+loginCount+"' where id="+user.getId();
                this.getJdbcTemplate().execute(sql);
            }
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10010")));
            visMap.put("msg","10010："+retJson.get("message"));
            if(DBCheck.isMongoDB()){
                action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }else{
                action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }
            return new HashMap<>();
        }
        Map<String,Object> map=new HashMap<>();
        visMap.put("user_login_name",username);
        visMap.put("user_id",user.getId());
        visMap.put("password","登录成功");
        visMap.put("msg","登录成功");
        visMap.put("name","1");//1：用户登录  2：用户登出  3：登录失败
        if(DBCheck.isMongoDB()){
            action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
        }else{
            action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
        }
        // start save online user 在线用户
        if(user.getIsMultiDeviceLogin().equals("N")){
            this.getJdbcTemplate().execute("update tbl_data_online_user set status=1 where create_user_id='"+user.getId()+"'");
        }
        Map<String,Object> onlineMap=new HashMap<>();
        onlineMap.put("ip", ip);
        onlineMap.put("ip_region", action.ipSearcher.getIP(ip));
        onlineMap.put("user_login_name",user.getUserLoginName());
        onlineMap.put("token",token);
        userAgent = request.getHeader("User-Agent").toUpperCase();
        if (!userAgent.equals("null") && userAgent.length()>0) {
            try {
                UserAgentInfo userAgentInfo= UserAgentUtil.getUasParser().parse(userAgent);
                onlineMap.put("os_name",userAgentInfo.getOsName());
                String browser=UserAgentUtil.identifyBrowser(request);
                onlineMap.put("ua_family",browser);
                if(browser.equals("")){
                    onlineMap.put("ua_family",userAgentInfo.getUaFamily());
                }
            } catch (IOException e) {
            }
        }
        action.baseService.save("tbl_data_online_user",onlineMap,user);//mysql记录
        // end save online user 在线用户
        map.put("token",token);
        map.put("redirect_url",user.getRedirectUrl());
        return map;
    }
    public Map<String,Object> logout(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        try {
            User user=action.userService.getUser(request);
            action.myUserDetails.getUserInfoMap().remove(user.getUserLoginName());
            action.khcRedisCache.deleteMenuByUserId(user.getId());
            if(user.getIsMultiDeviceLogin().equals("N")){
                action.userService.deleteToken(user.getUserLoginName());
                //退出成功后将用户在线表信息更新
                this.getJdbcTemplate().execute("update tbl_data_online_user set status=1 where create_user_id='"+user.getId()+"'");
            }else{
                String token=action.userService.getToken(request);
                action.userService.deleteToken(token);
                //退出成功后将用户在线表信息更新
                this.getJdbcTemplate().execute("update tbl_data_online_user set status=1 where token='"+token+"'");
            }
            // start save login log 登录日志
            Map<String,Object> visMap=new HashMap<>();
            String ip=IPUtil.getIpAddress(request);
            visMap.put("ip", ip);
            visMap.put("user_login_name",user.getUserLoginName());
            visMap.put("user_id",user.getId());
            visMap.put("password","");
            visMap.put("msg","登出成功");
            visMap.put("name","2");//1：用户登录  2：用户登出  3：登录失败
            String userAgent = request.getHeader("User-Agent").toUpperCase();
            if (StringUtil.isNotEmpty(userAgent)) {
                try {
                    UserAgentInfo userAgentInfo=UserAgentUtil.getUasParser().parse(userAgent);
                    visMap.put("os_name",userAgentInfo.getOsName());
                    visMap.put("ua_family",userAgentInfo.getUaFamily());
                } catch (IOException e) {
                }
            }
            if(DBCheck.isMongoDB()){
                action.mongoService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }else{
                action.baseService.save(TblLogNames.TBL_LOG_VIS,visMap);
            }
        } catch (Exception e) {
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("10020")));
            retJson.put("message",retJson.get("message"));
            return new HashMap<>();
        }
        Map<String,Object> map=new HashMap<>();
        map.put("message","注销成功");
        return map;
    }


    public Map<String,Object> rePassword(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        String sql = this.buildSql(jsonStr,retJson,request);
        String powerSql = this.buildPowerSql(jsonStr,retJson,request);

        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        String userId= String.valueOf(json.get("userId"));
        sql=sql+powerSql+" and id='"+userId+"'";//todo 这块先默认都是字符串，且在MySQL是加单引号是不影响的，如果更换数据库影响请动态判断
        try {
            Map<String,Object> returnMap = this.getJdbcTemplate().queryForMap(sql);
        } catch (Exception e) {
            retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("4031")));
            return new HashMap<>();
        }
        String password= TextUtil.getRandomNum(12);
        String hashed=encoder.encode(password.trim());
        String encodedPassword="{bcrypt}"+hashed;
        String updateSql="update tbl_system_user set user_password='"+encodedPassword+"' where id="+userId;
        this.getJdbcTemplate().execute(updateSql);
        Map<String,Object> map=new HashMap<>();
        map.put("message","新密码是："+password);
        return map;
    }
    public Map<String,Object> unbanUser(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String userId= String.valueOf(json.get("userId"));
        String sql="update tbl_system_user set login_count='0' where id="+userId;
        this.getJdbcTemplate().execute(sql);
        Map<String,Object> map=new HashMap<>();
        map.put("message","解禁成功");
        return map;
    }

    public JackJSONArray userSaveBefore(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        Map<String,Object> dsMap=action.dsService.findDataSourceByJsonStr(jsonStr);
        String pkFieldName = String.valueOf(dsMap.get("ds_pk_id"));
        for (int i = 0; i < array.size(); i++) {
            String orgId=String.valueOf(array.getJackJSONObject(i).get("org_id"));
            String levelSql="SELECT org_name FROM tbl_system_org WHERE id='"+orgId+"'";
            String orgName=this.getJdbcTemplate().queryForObject(levelSql,String.class);
            array.getJackJSONObject(i).put("org_name",orgName);
            String pkId=String.valueOf(array.getJackJSONObject(i).get(pkFieldName));
            if(StringUtil.isEmpty(pkId)){
                String userMobile=String.valueOf(array.getJackJSONObject(i).get("user_mobile"));//默认密码为手机号
                BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
                String hashed=encoder.encode(userMobile.trim());
                String encodedPassword="{bcrypt}"+hashed;
                array.getJackJSONObject(i).put("user_password",encodedPassword);
            }
        }
        return array;
    }

    @Override
    public JackJSONArray saveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        Map<String,Object> dsMap=action.dsService.findDataSourceByJsonStr(jsonStr);
        String pkFieldName = String.valueOf(dsMap.get("ds_pk_id"));
        JackJSONArray saveBeforeData=JackJSONObject.fromObject(jsonStr).getJackJSONArray("saveData");
        String pkId=String.valueOf(saveBeforeData.getJackJSONObject(0).get(pkFieldName));//取出保存之前的id，有值则为编辑，空则为新增
        //判断是新增则绑定默认角色
        if(StringUtil.isEmpty(pkId)){
            String roles=action.khcRedisCache.getBaseConfigByCode(SYSTEM_SETTINGS_DS_USER_ROLE_DEFAULT);
            if(!roles.equals("")){
                String userId=String.valueOf(array.getJackJSONObject(0).get(pkFieldName));
                String[] arr = roles.split(",");
                for (int i = 0; i < arr.length; i++) {
                    if(!arr[i].equals("")){
                        Map<String,Object> map=new HashMap<>();
                        map.put("role_id",arr[i]);
                        map.put("user_id",userId);
                        action.baseService.save("tbl_system_roleuser",map);
                    }
                }
            }
        }
        return array;
    }

    public JackJSONArray saveBeforeUserByUpdatePass(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array){
        User user=action.userService.getUser(request);
        array.getJackJSONObject(0).remove("re_user_password");
        String password=String.valueOf(array.getJackJSONObject(0).get("user_password"));
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        String hashed=encoder.encode(password.trim());
        String encodedPassword="{bcrypt}"+hashed;
        array.getJackJSONObject(0).put("user_password",encodedPassword);
        String ip=IPUtil.getIpAddress(request);
        Map<String,Object> logMap=new HashMap<>();
        BaseDao.setDefaultValue(logMap,user);
        logMap.put("ip", ip);
        logMap.put("user_name",user.getUserName());
        logMap.put("user_id",user.getId());
        if(DBCheck.isMongoDB()){
            action.mongoService.save(TblLogNames.TBL_LOG_USER_PASSWORD_UPDATE,logMap);
        }else{
            action.baseService.save(TblLogNames.TBL_LOG_USER_PASSWORD_UPDATE,logMap);
        }
        return array;
    }

    public Map<String,Object> getAllRoleByUserId(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String userId= String.valueOf(json.get("userId"));
        String sql="select * from tbl_system_roleuser where user_id="+userId;
        List<Map<String, Object>> list= this.getJdbcTemplate().queryForList(sql);
        String roleStr="";
        for (int i = 0; i < list.size(); i++) {
            roleStr+=list.get(i).get("role_id")+",";
        }
        if(roleStr!=""){
            roleStr=roleStr.substring(0,roleStr.length()-1);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("message","查询成功");
        map.put("data",roleStr);
        return map;
    }

    public Map<String,Object> getAllUserByRoleId(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String roleId= String.valueOf(json.get("roleId"));
        String sql="select * from tbl_system_roleuser where role_id="+roleId;
        List<Map<String, Object>> list= this.getJdbcTemplate().queryForList(sql);
        String roleStr="";
        for (int i = 0; i < list.size(); i++) {
            roleStr+=list.get(i).get("user_id")+",";
        }
        if(roleStr!=""){
            roleStr=roleStr.substring(0,roleStr.length()-1);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("message","查询成功");
        map.put("data",roleStr);
        return map;
    }

    //用户拥有的角色
    public JackJSONArray saveBeforeUserRole(String jsonStr, JackJSONObject retJson, HttpServletRequest request,JackJSONArray array){
        JackJSONObject json =array.getJackJSONObject(0);
        String userId=String.valueOf(json.get("user_id"));
        String roles=String.valueOf(json.get("role_id"));
        action.getJdbcTemplate().execute("delete from tbl_system_roleuser where user_id="+userId);
        if(!roles.equals("")){
            String[] arr = roles.split(",");
            for (int i = 0; i < arr.length; i++) {
                if(!arr[i].equals("")){
                    Map<String,Object> map=new HashMap<>();
                    map.put("role_id",arr[i]);
                    map.put("user_id",userId);
                    action.baseService.save("tbl_system_roleuser",map);
                }
            }
        }
        retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("ok")));
        Map<String,Object> map=new HashMap<>();
        map.put("saveData",array);
        retJson.put("data",map);
        return new JackJSONArray();
    }

    //角色拥有的用户
    public JackJSONArray saveBeforeRoleUser(String jsonStr, JackJSONObject retJson, HttpServletRequest request,JackJSONArray array){
        JackJSONObject json =array.getJackJSONObject(0);
        String userIds=String.valueOf(json.get("user_id"));
        String roleId=String.valueOf(json.get("role_id"));
        action.getJdbcTemplate().execute("delete from tbl_system_roleuser where role_id="+roleId);
        if(!userIds.equals("")){
            String[] arr = userIds.split(",");
            for (int i = 0; i < arr.length; i++) {
                if(!arr[i].equals("")){
                    Map<String,Object> map=new HashMap<>();
                    map.put("role_id",roleId);
                    map.put("user_id",arr[i]);
                    action.baseService.save("tbl_system_roleuser",map);
                }
            }
        }
        retJson.putAll(JackJSONObject.fromObject(action.apiService.getReturnDataByCode("ok")));
        Map<String,Object> map=new HashMap<>();
        map.put("saveData",array);
        retJson.put("data",map);
        return new JackJSONArray();
    }

    /**
     * 驼峰式命名
     */
    public Map<String,Object> findOneUser(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        User user=action.userService.getUser(request);
        Map<String,Object> map=new HashMap<>();
        map.put("message","查询成功");
        map.put("data",user);
        return map;
    }
    /**
     * 下划线命名
     */
    public Map<String,Object> findOneUserInfo(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        User user=action.userService.getUser(request);
        String sql="SELECT * FROM tbl_system_user WHERE id="+user.getId();
        List<Map<String,Object>> userList=getJdbcTemplate().queryForList(sql);
        Map<String,Object> map=new HashMap<>();
        map.put("message","查询成功");
        map.put("data",userList.get(0));
        return map;
    }

    //借调保存之前的一些处理
    public JackJSONArray saveBeforeUserSecondment(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        Map<String,Object> dsMap=action.dsService.findDataSourceByJsonStr(jsonStr);
        for (int i = 0; i < array.size(); i++) {
            String orgId=String.valueOf(array.getJackJSONObject(i).get("org_id"));
            String parentId=String.valueOf(array.getJackJSONObject(i).get("parent_id"));
            String queryUserNumSql="SELECT COUNT(1) FROM tbl_system_user WHERE org_id="+orgId+" AND (parent_id='"+parentId+"' OR id="+parentId+")";
            Integer userNum=this.getJdbcTemplate().queryForObject(queryUserNumSql,Integer.class);
            if(userNum>0){
                retJson.put("message","借调失败，原因：用户已在该部门有用户");
                return new JackJSONArray();
            }
            String queryOrgInfo="SELECT * FROM tbl_system_org WHERE id='"+orgId+"'";
            Map<String, Object> orgMap=this.getJdbcTemplate().queryForMap(queryOrgInfo);
            array.getJackJSONObject(i).put("org_name",orgMap.get("org_name"));
        }
        return array;
    }

    public String userSecondmentBuildPowerSql(String jsonStr, JackJSONObject retJson, HttpServletRequest request) {
        User user=action.userService.getUser(request);
        String sql=" ";
        if(user.getParentId().equals("")){
            sql+=" AND (id='"+user.getId()+"' or parent_id='"+user.getId()+"') ";
        }else{
            sql+=" AND (id='"+user.getParentId()+"' or parent_id='"+user.getParentId()+"') ";
        }
        return sql;
    }

    public Map<String,Object> switchUser(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String userId= String.valueOf(json.get("userId"));
        User user=action.userService.getUser(Long.valueOf(userId));
        //免验证 直接创建token
        String token = action.jwtTokenProvider.createToken(user.getUserLoginName(),action.userRepository.findByUserLoginName(user.getUserLoginName()).getRoles());
        Map<String,Object> map=new HashMap<>();
        map.put("message","切换成功");
        map.put("token",token);
        return map;
    }

    public JtPage userSecondmentShowAllAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JtPage jtPage) {
        User user=action.userService.getUser(request);
        for (int i = 0; i < jtPage.getContent().size(); i++) {
            String isLoginMessage="";
            String userId=String.valueOf(jtPage.getContent().get(i).get("id"));
            if(userId.equals(String.valueOf(user.getId()))){
                isLoginMessage="(当前登录)";
            }
            if(String.valueOf(jtPage.getContent().get(i).get("parent_id")).equals("")){
                jtPage.getContent().get(i).put("parent_id","主账户"+isLoginMessage);
            }else{
                jtPage.getContent().get(i).put("parent_id","子账号"+isLoginMessage);
            }
        }
        return jtPage;
    }

    private void deleteFile(String filePath){
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            imageFile.delete();
        }
    }
}

