package com.dk.mdm.service.core;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.constant.OauthConstants;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.mapper.BaseMapper;
import com.dk.common.mapper.opinfo.OpInfoMapper;
import com.dk.common.model.pojo.PageList;
import com.dk.common.model.vo.core.StaffEntity;
import com.dk.common.model.vo.core.UserVO;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.service.BaseService;
import com.dk.common.util.oauth.JwtUtil;
import com.dk.mdm.infrastructure.convert.core.UserConvert;
import com.dk.mdm.infrastructure.convert.core.UserRightConvert;
import com.dk.mdm.mapper.common.CommonMapper;
import com.dk.mdm.mapper.core.FactoryMapper;
import com.dk.mdm.mapper.core.UserLockedMapper;
import com.dk.mdm.mapper.core.UserMapper;
import com.dk.mdm.model.pojo.core.*;
import com.dk.mdm.model.query.core.UserQuery;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.model.pojo.core.*;
import com.dk.common.model.response.core.UserResponse;
import com.dk.mdm.model.vo.core.UserRightVO;
import eu.bitwalker.useragentutils.UserAgent;
import org.postgresql.util.PGobject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserService extends BaseService<User> {

    @Override
    public BaseMapper<User> getRepository() {
        return userMapper;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private OpInfoMapper opInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FactoryMapper factoryMapper;

    @Autowired
    private UserLockedMapper userLockedMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private UserConvert userConvert;

    @Autowired
    private UserRightConvert userRightConvert;

    @Override
    public String getPrimaryKey() {
        return "user_id";
    }

    /**
     * @desc : 条件查询
     * @author : 姜宁
     * @date : 2023/1/29 11:17
     */
    @Pagination
    public ResponseResultVO<PageList<UserResponse>> selectByCond(UserQuery userQuery) {
        return super.mergeListWithCount(userQuery, userMapper.selectByCond(userQuery),
                userMapper.countByCond(userQuery));
    }

    /**
     * @desc : 登录
     * @author : 周兴
     * @date : 2022-5-5 17:18
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO login(UserVO userVo) {
        return null;
//        // 校验应用
//        ResponseResultVO appVO = checkApp(userVo);
//        if (appVO != null) {
//            return appVO;
//        }
//        UserResponse user;
//        // TODO CR 220516 登录时没有redis，登录后验证或api用户获取token时，才需要验证redis
//        // 2022-05-21 周兴 暂时保留
//
//        //在缓存中查询登录的用户信息
//        //如果缓存中不存在当前登录的用户信息
//        // TODO CR 220516 redis还要加上app_uuid？共用token？token作为redis的key
//        // 2022-05-21 周兴 redis key 修改为 USER-{token}-{userid}
//
//        // 判断工厂编码是否存在
//        Long count = factoryMapper.selectByCode(new Factory().setFtyCode(userVo.getFtyCode()));
//        if (count <= 0) {
//            stringRedisTemplate.opsForValue().set(Constant.RedisConstant.REDIS_LOGIN.getName() + userVo.getFtyCode() + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getAppCode()
//                    + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getUserCode(), "null", 30, TimeUnit.SECONDS);
//            return ResponseResultUtil.error(ErrorCodeEnum.FTY_ERROR.getCode(), ErrorCodeEnum.FTY_ERROR.getMessage());
//        }
//        //根据用户编码查询数据库中的用户信息
//        user = userMapper.selectByCode(userVo.getUserCode(), userVo.getFtyCode());
//        //查询不到用户信息，在缓存中将此用户信息设置为空，过期时间为30秒（在此期间不会访问数据库）
//        if (user == null) {
//            stringRedisTemplate.opsForValue().set(Constant.RedisConstant.REDIS_LOGIN.getName() + userVo.getFtyCode() + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getAppCode()
//                    + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getUserCode(), "null", 30, TimeUnit.SECONDS);
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_PASSWORD_ERROR.getCode(), ErrorCodeEnum.USER_PASSWORD_ERROR.getMessage());
//        }
//        user.setAppCode(userVo.getAppCode());
//        user.setFtyCode(userVo.getFtyCode());
////        // 统一查询系统参数 TODO
////        List<String> codes = new ArrayList<String>() {{
////            add(Constant.StringConstant.SYS_CODE_002.getName());
////            add(Constant.StringConstant.SYS_CODE_003.getName());
////            add(Constant.StringConstant.SYS_CODE_010.getName());
////        }};
////        JSONObject settingValues = getSetting(codes, user.getCpId());
////
////        // 系统参数中错误次数
////        int times = settingValues.getInteger(Constant.StringConstant.SYS_CODE_002.getName());
////        // 系统参数中锁定时长
////        int lockHours = settingValues.getInteger(Constant.StringConstant.SYS_CODE_003.getName());
////        // 密码有效期
////        String pwdValidDate = settingValues.getString(Constant.StringConstant.SYS_CODE_010.getName());
//        // 查询用户锁定状态
//        UserLocked userLocked = userLockedMapper.selectById(user.getUserId());
//        if (userLocked == null) {
//            userLocked = new UserLocked().setUserId(user.getUserId()).setIsLocked(false).setMissCount(0);
//            //保存
//            userLockedMapper.insert(userLocked);
//        }
//        //查询登录状态
//        if (userLocked.getIsLocked()) {
//            //锁定中
//            // TODO CR 220516 锁定时间+系统参数锁定时长<当前时间才解锁，1、时间不对，2、判断方向返了
//            // 2022-05-21 周兴 已修改 TODO
//            Integer lockHours = 3;
//            // 锁定时间 + 系统参数中锁定时间 < 当前时间 解锁
//            if (userLocked.getLockedTime().plusHours(lockHours).compareTo(LocalDateTime.now()) < 0) {
//            } else {
//                return ResponseResultUtil.error(ErrorCodeEnum.USER_IS_LOCKED.getCode(), ErrorCodeEnum.USER_IS_LOCKED.getMessage());
//            }
//        }
//        if (userMapper.encodePassword(userVo.getUserPwd(), user.getUserId()).equals(user.getUserPwd())) {
//            //密码正确
//            //清除锁定信息
//            userLockedMapper.unLockUser(user.getUserId());
//            //查询到用户信息后将数据放到缓存中，缓存过期时间为30分钟
//            stringRedisTemplate.opsForValue().set(Constant.RedisConstant.REDIS_LOGIN.getName() + userVo.getFtyCode() + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getAppCode()
//                    + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getUserCode(), "null", 30, TimeUnit.SECONDS);
//        } else {
//            //密码错误
//            // 增加锁定次数
//            userLockedMapper.addMissCount(user.getUserId());
//            // 获取系统参数默认密码
//            Map<String, Object> param = new HashMap<>();
//            param.put("code", Constant.StringConstant.SYS_CODE_002.getName());
//            param.put("ftyId", user.getFtyId());
//            String sysValue = commonMapper.getSettingValue(param);
//            Integer times = Integer.parseInt(sysValue);
//            // 判断是否需要锁定用户
//            int returnRows = 0;
//            if (times != 0 && userLocked.getMissCount() + 1 > times) {
//                returnRows = userLockedMapper.lockUser(user.getUserId());
//            }
//            //清理redis
//            authUtils.cleanLoginUser(Constant.RedisConstant.REDIS_LOGIN.getName() + userVo.getFtyCode() + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getAppCode()
//                    + Constant.StringConstant.SYSTEM_MAGIN_LINE.getName() + userVo.getUserCode());
//            return returnRows == 0 ? ResponseResultUtil.error(ErrorCodeEnum.USER_PASSWORD_ERROR.getCode(), ErrorCodeEnum.USER_PASSWORD_ERROR.getMessage())
//                    : ResponseResultUtil.error(ErrorCodeEnum.USER_IS_LOCKED.getCode(), ErrorCodeEnum.USER_IS_LOCKED.getMessage());
//        }
//        return ResponseResultUtil.success(new JSONObject() {{
//            put("user", user);
//        }});
    }

    /**
     * @desc : 登录，密码验证后
     * @author : 洪旭东
     * @date : 2022-06-09 14:09
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO loginAfterCheckPassword(UserResponse user, String accessToken) {
        return null;
//        // 存Redis
//        authUtils.saveUser(new UserVO().setUserId(user.getUserId()).setUserType(user.getUserType()).setUserCode(user.getUserCode())
//                .setUserName(user.getUserName()).setClientId(user.getClientId()).setFtyId(user.getFtyId()).setOrgId(user.getOrgId())
//                .setStaffId(user.getStaffId()).setAppCode(user.getAppCode()).setFtyCode(user.getFtyCode()));
//        userMapper.updateUserLogin(
//                new UserVO().setUserId(user.getUserId())
//                        .setIsLogin(true).setTokenKey(accessToken)
//                        .setTokenInvalidTime(LocalDateTime.ofEpochSecond((System.currentTimeMillis() + OauthConstants.EXPIRES_IN) / 1000,
//                                0, ZoneOffset.ofHours(8)))
//        );
//        // 获取浏览器标识
//        UserAgent userAgent = UserAgent.parseUserAgentString(httpServletRequest.getHeader("User-Agent"));
//
//        //登录日志
//        userMapper.insertUserLoginLog(new UserLoginLog().setUserId(user.getUserId())
//                .setLoginType(Constant.IntegerConstant.LOG_LOGIN_LOGIN.getValue()).setClientIp(httpServletRequest.getRemoteAddr())
//                .setClientInfo(userAgent.toString()).setAppCode(user.getAppCode()));
//        opInfoMapper.setOpInfo(user.getAppCode(), String.valueOf(user.getUserId()), user.getLang());
//        // TODO 系统参数
////        JSONObject settingValues = getSetting(codes, userVo.getCpId());
//        // 获取用户表格设置
//        Map userMap = new HashMap();
//        userMap.put("userId", user.getUserId());
//        userMap.put("appCode", user.getAppCode());
//
//        return ResponseResultUtil.success(new HashMap<String, Object>(16) {{
//            put("accessToken", accessToken);
//            put("user", user);
//            put("menu", commonMapper.getMenuByUser(user.getAppCode(), user.getUserId()));
//            put("function", (user.getRoleIds() != null && user.getRoleIds().indexOf(-1) >= 0)
//                    ? commonMapper.getUserFunctionAdmin(userMap) : commonMapper.getUserFunction(userMap));
//            put("userTableSetting", commonMapper.getUserTableInfo(userMap));
//        }});
    }

    /**
     * @desc : 退出登录
     * @author : 周兴
     * @date : 2023-01-06 09:03
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO logout() {
        // 获取浏览器标识
        UserAgent userAgent = UserAgent.parseUserAgentString(httpServletRequest.getHeader("User-Agent"));
        StaffEntity staff = authUtils.getStaff();
        String appCode = JwtUtil.getAppCode(httpServletRequest);
        String staffId = staff.getStaffId();
        // todo
//        // 用户
//        User user = super.selectObjectById(userId.toString());
//        //修改登录状态
//        userMapper.updateUserLogin(
//                new UserVO().setUserId(userId).setAppCode(u.getAppCode()).setIsLogin(false));
//        //记录登录日志
//        userMapper.insertUserLoginLog(new UserLoginLog().setUserId(user.getUserId())
//                .setLoginType(Constant.IntegerConstant.LOG_LOGIN_LOGOUT.getValue()).setClientIp(httpServletRequest.getRemoteAddr())
//                .setClientInfo(userAgent.toString()).setAppCode(u.getAppCode()));
        //清理redis
//        authUtils.cleanStaff();
//        authUtils.cleanLoginStaff();
        return ResponseResultUtil.success();
    }

    // region 私有方法

    /**
     * @desc : 检查应用代码
     * @author : 周兴
     * @date : 2023/1/5 10:36
     */
    private ResponseResultVO checkApp(UserVO userVO) {
        //应用
        List<Map<String, String>> application = commonMapper.getApplication();
        if (application.stream().noneMatch(a -> a.get("appCode").equals(userVO.getAppCode()))) {
            return ResponseResultUtil.error(ErrorCodeEnum.APP_NOT_EXIST.getCode(), ErrorCodeEnum.APP_NOT_EXIST.getMessage());
        }
        return null;
    }
    // endregion

    // region 修改密码

    /**
     * @desc : 修改密码
     * @author : 常皓宁
     * @date : 2023-01-31 10:15
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO updatePassword(UserVO userVO) {
        // todo
        return null ;
//        // 用户
//        UserVO userVo = authUtils.getUser();
//        // 查询当前用户信息
//        UserResponse user = userMapper.selectUserWithPwdById(userVo.getUserId());
//
//        if (!user.getUserPwd().equals(userMapper.encodePassword(userVO.getPassword(), userVo.getUserId()))) {
//            // 旧密码错误
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_PWD_ERROR.getCode(), ErrorCodeEnum.USER_PWD_ERROR.getMessage());
//        } else if (!userVO.getNewPassword().equals(userVO.getConfirmPassword())) {
//            // 确认密码不一致
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_PWD_NEW_AND_CONFIRM_DIFFERENT.getCode(),
//                    ErrorCodeEnum.USER_PWD_NEW_AND_CONFIRM_DIFFERENT.getMessage());
//        }
//        // 修改密码
//        userMapper.updatePassword(new UserVO()
//                .setUserId(userVo.getUserId())
//                .setPwdDate(LocalDateTime.now())
//                .setFlgInitPwd(Boolean.FALSE)
//                .setUserPwd(userMapper.encodePassword(userVO.getNewPassword(), userVo.getUserId())));
//        return ResponseResultUtil.success();
    }
    // endregion

    /**
     * @desc : 保存方法
     * @author : 姜宁
     * @date : 2023/1/9 10:49
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(com.dk.mdm.model.vo.core.UserVO userVO) {
        // 转化实体
        User user = userConvert.convertToPo(userVO);
        // 判断编码是否重复
        Long count = userMapper.selectUserByCode(user);
//        if (count > 0) {
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_CODE_EXISTS.getCode(),
//                    ErrorCodeEnum.USER_CODE_EXISTS.getMessage());
//        }
        // 获取用户Id
        Integer userId = userMapper.selectUserIdBySeq();
        // 获取初始密码
        Map<String, Object> param = new HashMap<>();
        param.put("code", Constant.StringConstant.SYS_CODE_001.getName());
        param.put("ftyId", user.getFtyId());
        String userPwd = commonMapper.getSettingValue(param);
//        if (userPwd == null || userPwd.equals("")) {
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_PWD_NOT_EXISTS.getCode(),
//                    ErrorCodeEnum.USER_PWD_NOT_EXISTS.getMessage());
//        }
        // md5加密
        String md5Pwd = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        // 密码加密
        user.setUserPwd(userMapper.encodePassword(md5Pwd, userId));
        List<Map<String, Object>> workTeamList = userVO.getWorkTeamList();
        // 绑定了工种则为班组
        if (!CollectionUtils.isEmpty(workTeamList) && workTeamList.size() > 0) {
            user.setUserType(Constant.IntegerConstant.USER_TYPE_WORK_TEAM.getValue());
        }
        user.setUserId(userId);
        // 保存用户信息
        super.insert(user);
        // 插入到班组表
        if (!CollectionUtils.isEmpty(workTeamList) && workTeamList.size() > 0) {
            // 转化实体
            WorkTeam workTeam = new WorkTeam();
            List<WorkTeam> workTeams = new ArrayList<WorkTeam>();
            for (int i = 0; workTeamList.size() > i; i++) {
                if (workTeamList.get(i).get("jobId") == null) {
                    continue;
                }
                workTeam = new WorkTeam();
                workTeam.setFtyId(user.getFtyId());
                workTeam.setUserId(user.getUserId());
                workTeam.setStaffId(Integer.parseInt(workTeamList.get(i).get("staffId").toString()));
                workTeam.setWtJobId(Integer.parseInt(workTeamList.get(i).get("jobId").toString()));
                workTeam.setStaffIds((List<Integer>) workTeamList.get(i).get("staffIds"));
                workTeam.setWtJobId(Integer.parseInt(workTeamList.get(i).get("jobId").toString()));
                workTeam.setRemarks((String) workTeamList.get(i).get("remarks"));
                workTeam.setDisplayNo(i + 1);
                workTeams.add(workTeam);
            }
            if (workTeams.size() > 0) {
                int result = userMapper.insertWorkTeamBatch(workTeams);
                if (result == 0) {
                    return ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
                }
            }
        }

        return ResponseResultUtil.success(user);
    }

    /**
     * @desc : 编辑方法
     * @author : 姜宁
     * @date : 2023/2/1 15:00
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> update(com.dk.mdm.model.vo.core.UserVO userVO) {
        // 转化实体
        User user = userConvert.convertToPo(userVO);
        // 判断编码是否重复
        Long count = userMapper.selectUserByCode(user);
//        if (count > 0) {
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_CODE_EXISTS.getCode(),
//                    ErrorCodeEnum.USER_CODE_EXISTS.getMessage());
//        }
        List<Map<String, Object>> workTeamList = userVO.getWorkTeamList();
        // 绑定了工种则为班组
        if (!CollectionUtils.isEmpty(workTeamList) && workTeamList.size() > 0) {
            user.setUserType(Constant.IntegerConstant.USER_TYPE_WORK_TEAM.getValue());
        } else {
            user.setUserType(Constant.IntegerConstant.USER_TYPE_CLERK.getValue());
        }
        // 编辑数据
        super.update(user);
        // 删除班组信息表
        userMapper.deleteWorkTeam(userVO);
        // 插入到班组表
        if (!CollectionUtils.isEmpty(workTeamList) && workTeamList.size() > 0) {
            // 转化实体
            WorkTeam workTeam = new WorkTeam();
            List<WorkTeam> workTeams = new ArrayList<WorkTeam>();
            for (int i = 0; workTeamList.size() > i; i++) {
                if (workTeamList.get(i).get("jobId") == null) {
                    continue;
                }
                workTeam = new WorkTeam();
                workTeam.setFtyId(user.getFtyId());
                workTeam.setUserId(user.getUserId());
                workTeam.setStaffId(Integer.parseInt(workTeamList.get(i).get("staffId").toString()));
                workTeam.setStaffIds((List<Integer>) workTeamList.get(i).get("staffIds"));
                workTeam.setWtJobId(Integer.parseInt(workTeamList.get(i).get("jobId").toString()));
                workTeam.setRemarks((String) workTeamList.get(i).get("remarks"));
                workTeam.setDisplayNo(i + 1);
                workTeams.add(workTeam);
            }
            if (workTeams.size() > 0) {
                int result = userMapper.insertWorkTeamBatch(workTeams);
                if (result == 0) {
                    return ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
                }
            }
        }

        //bug5155用户编辑后，如果角色增加了超级管理员，需要把t_user_right中对应的数据删除掉
        if (user.getRoleIds().contains(-1)) {
            // 删除用户权限
            userMapper.deleteUserRight(user.getUserId(), user.getFtyId());
        }

        return ResponseResultUtil.success();
    }

    /**
     * @desc : 重置密码
     * @author : 姜宁
     * @date : 2023/2/2 10:20
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> resetPassword(com.dk.mdm.model.vo.core.UserVO userVO) {
        // 获取系统参数默认密码
        Map<String, Object> param = new HashMap<>();
        param.put("code", Constant.StringConstant.SYS_CODE_001.getName());
        param.put("ftyId", userVO.getFtyId());
        String userPwd = commonMapper.getSettingValue(param);
//        if (userPwd == null || userPwd.equals("")) {
//            return ResponseResultUtil.error(ErrorCodeEnum.USER_PWD_NOT_EXISTS.getCode(),
//                    ErrorCodeEnum.USER_PWD_NOT_EXISTS.getMessage());
//        }
        //密码修改时间
        userVO.setPwdDate(LocalDateTime.now());
        //是否是初始密码
        userVO.setFlgInitPwd(Boolean.TRUE);
        // 初始密码md5加密
        String md5Pwd = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        List<Integer> userIdList = userVO.getUserIds();
        if (CollectionUtils.isEmpty(userIdList) || userIdList.size() == 0) {
            return ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
        }
        for (Integer integer : userIdList) {
            userVO.setUserId(integer);
            // 密码加密
            userVO.setUserPwd(userMapper.encodePassword(md5Pwd, userVO.getUserId()));
            // 更新密码
            userMapper.updateUsersPwd(userVO);
        }
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 解锁
     * @author : 姜宁
     * @date : 2023/2/2 11:36
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> unLock(com.dk.mdm.model.vo.core.UserVO userVO) {
        // 解锁
        userMapper.unLocks(userVO);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 获取用户权限
     * @author : 姜宁
     * @date : 2023/2/2 15:21
     */
    public ResponseResultVO<List<Map<String, String>>> getUserRight(Map<String, Object> param) {
        // 获取用户权限
        Map<String, List<Map<String, String>>> settingMap = userMapper.getUserRight(param);
        // 定义返回值
        List<Map> list =
                JSONArray.parseArray((((PGobject) settingMap.get("f_get_user_fun_for_edit")).getValue()), Map.class);
        List<Map<String, String>> userRightList = new ArrayList<>();
        // 返回空
        if (CollectionUtils.isEmpty(list) || list.size() == 0) {
            return ResponseResultUtil.success(userRightList);
        }
        for (Map item : list) {
            item.keySet().forEach(key-> userRightList.addAll((List<Map<String, String>>) item.get(key)));
        }
        return ResponseResultUtil.success(userRightList);
    }

    /**
     * @desc : 获取用户权限
     * @author : 姜宁
     * @date : 2023/2/2 15:21
     */
    public ResponseResultVO<List<Map<String, Object>>> getUserRightSelected(Map<String, Object> param) {
        // 获取已选的用户权限
        List<Map<String, Object>> list = userMapper.getUserRightSelected(param);
        return ResponseResultUtil.success(list);
    }

    /**
     * @desc : 通过id查询
     * @author : 姜宁
     * @date : 2023/2/3 13:09
     */
    public ResponseResultVO<UserResponse> selectById(Integer userID) {
        UserQuery userQuery = new UserQuery();
        userQuery.setUserId(userID);
        List<UserResponse> userList = userMapper.selectByCond(userQuery);
        if (CollectionUtils.isEmpty(userList)) {
            return ResponseResultUtil.error(ResponseCodeEnum.SELECT_NULL);
        } else {
            UserResponse t = userList.get(0);
            List<Map<String, Object>> workteam = userMapper.getUserWorkTeamById(userID);
            // 返回的staffList需要重新赋值
            if (!CollectionUtils.isEmpty(workteam)) {
                for (Map<String, Object> stringObjectMap : workteam) {
                    if (stringObjectMap.get("staffList") == null) {
                        continue;
                    }
                    String staffString = ((PGobject) stringObjectMap.get("staffList")).getValue();
                    JSONArray object = JSONArray.parseArray(staffString);
                    stringObjectMap.replace("staffList", object);
                }
            }
            t.setWorkTeamList(workteam);
            return ResponseResultUtil.success(t);
        }
    }

    /**
     * @desc : 保存用户权限
     * @author : 姜宁
     * @date : 2023/2/3 15:18
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> saveUserRight(List<UserRightVO> userRightList) {
        if (CollectionUtils.isEmpty(userRightList) || userRightList.size() == 0) {
            return ResponseResultUtil.error(ResponseCodeEnum.SELECT_NULL);
        }
        // 删除用户权限
        userMapper.deleteUserRight(userRightList.get(0).getUserId(), userRightList.get(0).getFtyId());
        // 重新分配权限
        List<UserRight> userRights = new ArrayList<UserRight>();
        // 转化实体
        for (UserRightVO userRightVO : userRightList) {
            if (userRightVO.getFunUuid().length() > 0) {
                UserRight userRight = userRightConvert.convertToPo(userRightVO);
                userRights.add(userRight);
            }
        }
        // 保存权限
        if (userRights.size() > 0) {
            userMapper.saveUserRight(userRights.stream().distinct().collect(Collectors.toList()));
        }

        //查询全部权限
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userRightList.get(0).getUserId());
        param.put("ftyId", userRightList.get(0).getFtyId());
        ResponseResultVO<List<Map<String, String>>> userRightRes = this.getUserRight(param);
        List<Map<String, String>> allRight = userRightRes.getData();
//        存入反权限
        List<UserRight> funUuidList = allRight.stream()
                .filter(f -> userRights.stream().map(UserRight::getFunUuid).noneMatch(m -> m.equals(f.get("funUuid"))))
                .filter(f -> f.get("funUuid") != null && !"".equals(f.get("funUuid")))
                .map(m -> new UserRight().setUserId(userRightList.get(0).getUserId())
                        .setFunUuid(m.get("funUuid"))
                        .setRightType(-1)
                        .setAppCode(m.get("appCode"))
                        .setFtyId(userRightList.get(0).getFtyId()))
                .distinct()
                .collect(Collectors.toList());
        if (funUuidList.size() > 0) {
            userMapper.saveUserRight(funUuidList);
        }

        // 更新用户权限 core.f_reset_user_fun
        boolean result = userMapper.resetUserFun(userRightList.get(0).getUserId());
        return result ? ResponseResultUtil.success(userMapper) :
                ResponseResultUtil.error(ResponseCodeEnum.INSERT_FAIL);
    }

    /**
     * @desc : 通过id查询班组信息
     * @author : 姜宁
     * @date : 2023/2/7 9:17
     */
    public ResponseResultVO<List<Map<String, Object>>> getWorkTeamByUserId(Integer userID) {
        // 通过id查询班组信息
        List<Map<String, Object>> list = userMapper.getWorkTeamByUserId(userID);
        return ResponseResultUtil.success(list);
    }

    /**
     * @desc : 批量启用用户
     * @author : 夏常明
     * @date : 2023/2/10 9:53
     */
    public ResponseResultVO<String> userEnable(List<UserVO> userVOList) {
        //启用成功用户信息
        String successMessage = "启用成功用户：";
        //启用失败用户信息
        String failMessage = "未启用用户：";
        //是否存在启用成功用户
        Boolean success = false;
        //是否存在未启用用户
        Boolean fail = false;
        // 通过id查询班组信息
        for (UserVO uservo :
                userVOList) {
            //已启用用户
            if (uservo.getFlgValid()) {
                failMessage = failMessage + " " + uservo.getUserName() + ",";
                fail = true;
            } else {
                uservo.setFlgValid(true);
                userMapper.updateEnable(uservo);
                successMessage = successMessage + " " + uservo.getUserName() + ",";
                success = true;
            }
        }
        if (!fail) {
            failMessage = failMessage + " " + "无";
        } else {
            failMessage = failMessage.substring(0, failMessage.length() - 1);
        }
        if (!success) {
            successMessage = successMessage + " " + "无";
        } else {
            successMessage = successMessage.substring(0, successMessage.length() - 1);
        }
        return ResponseResultUtil.success(successMessage + " </br>" + failMessage);
    }

    /**
     * @desc : 批量禁用用户
     * @author : 夏常明
     * @date : 2023/2/10 9:53
     */
    public ResponseResultVO<String> userDisable(List<UserVO> userVOList) {
        //禁用成功用户信息
        String successMessage = "禁用成功用户： ";
        //启用失败用户信息
        String failMessage = "未禁用用户： ";
        //是否存在启用成功用户
        Boolean success = false;
        //是否存在未启用用户
        Boolean fail = false;
        // 通过id查询班组信息
        for (UserVO uservo :
                userVOList) {
            //已禁用用用户
            if (!uservo.getFlgValid()) {
                failMessage = failMessage + " " + uservo.getUserName() + ",";
                fail = true;
            } else {
                uservo.setFlgValid(false);
                userMapper.updateEnable(uservo);
                successMessage = successMessage + " " + uservo.getUserName() + ",";
                success = true;
            }
        }

        //不存在未启用用户
        if (!fail) {
            failMessage = failMessage + " " + "无";
        } else {
            failMessage = failMessage.substring(0, failMessage.length() - 1);
        }
        //不存在启用用户
        if (!success) {
            successMessage = successMessage + " " + "无";
        } else {
            successMessage = successMessage.substring(0, successMessage.length() - 1);
        }
        return ResponseResultUtil.success(successMessage + "</br>" + failMessage);
    }

}

