package jnpf.attendance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.attendance.mapper.AttendanceApprovalSettingMapper;
import jnpf.attendance.mapper.AttendanceGroupMapper;
import jnpf.attendance.mapper.AttendanceManagerPermissionMapper;
import jnpf.attendance.mapper.PermissionDictMapper;
import jnpf.attendance.service.*;
import jnpf.attendance.service.handle.notice.AttendanceNoticeHandler;
import jnpf.base.ActionResult;
import jnpf.constants.AttendancePermissionConstant;
import jnpf.entity.*;
import jnpf.enums.attendance.ApprovalPermissionTypeEnum;
import jnpf.enums.attendance.ApprovalSettingTypeEnum;
import jnpf.enums.attendance.AttendanceNoticeEnum;
import jnpf.enums.attendance.PermissionTypeEnum;
import jnpf.exception.HandleException;
import jnpf.model.attendance.dto.BatchSaveGroupAdmin;
import jnpf.model.attendance.dto.GroupFilterDto;
import jnpf.model.attendance.dto.SaveGroupAdmin;
import jnpf.model.attendance.dto.SaveSuperAdminDto;
import jnpf.model.attendance.model.AdminUpdateNoticeModel;
import jnpf.model.attendance.vo.*;
import jnpf.model.attendance.vo.attendance.UserPermissions;
import jnpf.model.attendance.vo.permission.ActionPermissionVo;
import jnpf.model.attendance.vo.permission.ApprovalSettingVo;
import jnpf.model.attendance.vo.permission.AttendanceTeamSetVo;
import jnpf.model.attendance.vo.permission.ConfigPermissionVo;
import jnpf.model.attendance.vo.permission.app.ManagerPermissionVo;
import jnpf.model.authority.vo.role.FtbPermissionPositionMenuVO;
import jnpf.permission.V2UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.vo.v2.user.UserBoundInfoVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.*;
import jnpf.util.attendance.PermissionUtil;
import jnpf.util.mapper.MybatisUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

@Service
public class AttendanceSuperAdminServiceImpl implements AttendanceSuperAdminService {
    private final List<String> managerEmbodyPermissions = List.of("成员管理", "余额管理", "权限设置", "排班", "绑定组织", "锁定");
    @Resource
    private V2UserApi v2UserApi;
    @Resource
    private UserProvider userProvider;
    @Resource
    private PermissionDictMapper permissionDictMapper;
    @Resource
    private AttendanceGroupMapper attendanceGroupMapper;
    @Resource
    private AttendanceGroupService attendanceGroupService;
    @Resource
    private AttendanceShiftSettingService shiftSettingService;
    @Autowired
    private AttendanceNoticeHandler attendanceNoticeHandler;
    @Autowired
    private AttendanceUserSettingService attendanceUserSettingService;
    @Resource
    private AttendanceApprovalSettingMapper attendanceApprovalSettingMapper;
    @Resource
    private AttendanceManagerPermissionMapper attendanceManagerPermissionMapper;
    @Resource
    private AttendanceUserService attendanceUserService;

    @NotNull
    private static List<String> getLevelIds(List<String> levelCodeList) {
        List<String> groupIdList = new ArrayList<>();
        levelCodeList.forEach(levelCode -> {
            String[] split = levelCode.split("#");
            CollectionUtil.addAll(groupIdList, split);
        });

        groupIdList.remove(0);
        return groupIdList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SaveSuperAdminDto saveSuperAdminDto) throws HandleException {
        /* 删除所有考勤组超级管理员*/
        UpdateWrapper<AttendanceManagerPermission> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.lambda()
                .eq(AttendanceManagerPermission::getType, PermissionTypeEnum.SUPER_ADMIN.getCode());
        attendanceManagerPermissionMapper.delete(deleteWrapper);
        for (String userId : saveSuperAdminDto.getUserIds()) {
            AttendanceManagerPermission managerPermission = new AttendanceManagerPermission();
            managerPermission.setType(0);
            managerPermission.setId(RandomUtil.uuId());
            managerPermission.setUserId(userId);
            managerPermission.setCreatorTime(new Date());
            managerPermission.setCreatorUserId(UserProvider.getLoginUserId());
            attendanceManagerPermissionMapper.insert(managerPermission);
        }
    }

    @Override
    public void delete(List<String> userIds) {
        LambdaUpdateWrapper<AttendanceManagerPermission> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(AttendanceManagerPermission::getUserId, userIds)
                .eq(AttendanceManagerPermission::getType, PermissionTypeEnum.SUPER_ADMIN.getCode());
        attendanceManagerPermissionMapper.delete(updateWrapper);
    }

    /**
     * 获取考勤组超级管理员列表
     *
     * @return List<AttendanceUserVo>
     */
    @Override
    public List<AttendanceUserVo> querySuperAdmin(String name) {
        QueryWrapper<AttendanceManagerPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceManagerPermission::getType, PermissionTypeEnum.SUPER_ADMIN.getCode())
                .eq(AttendanceManagerPermission::getDeleteMark, 0);

        List<AttendanceManagerPermission> superAdminList = attendanceManagerPermissionMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(superAdminList)) {
            return new ArrayList<>();
        }
        List<UserBoundVO> userList = v2UserApi.userListAndCopy(superAdminList.stream().map(AttendanceManagerPermission::getUserId).collect(Collectors.toList()), false, null);
        return JsonUtil.getJsonToList(userList, AttendanceUserVo.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addGroupAdmin(SaveGroupAdmin saveGroupAdmin) throws Exception {
        ParamUtil.checkParam(saveGroupAdmin);
        List<String> permissionIds = saveGroupAdmin.getPermissionIds();
        QueryWrapper<PermissionDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(PermissionDict::getId, permissionIds);
        List<PermissionDict> permissionList = permissionDictMapper.selectList(queryWrapper);
        Map<String, Integer> map = new HashMap<>();
        permissionList.forEach(permission -> {
            map.put(permission.getId(), permission.getModuleType());
        });
        permissionIds.forEach(id -> {
            save(id, saveGroupAdmin.getGroupId(), saveGroupAdmin.getUserId(), map.get(id));
        });
        //执行消息提醒
        AttendanceGroupVo groupVo = attendanceGroupMapper.getGroupBindingOrg(saveGroupAdmin.getGroupId());
        if (Objects.isNull(groupVo)) {
            throw new HandleException("未查询到考勤组信息");
        }
        AdminUpdateNoticeModel updateNoticeModel = new AdminUpdateNoticeModel();
        updateNoticeModel.setUserIds(List.of(saveGroupAdmin.getUserId()));
        updateNoticeModel.setType(1);
        updateNoticeModel.setGroupName(groupVo.getGroupName());
        List<PermissionDict> currentAuthorityList = permissionList.stream().filter(item -> item.getModuleType().equals(1)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(currentAuthorityList)) {
            updateNoticeModel.setCurrentAuthority(currentAuthorityList.stream().map(PermissionDict::getName).collect(Collectors.joining(",")));
        }
        List<PermissionDict> sonAuthorityList = permissionList.stream().filter(item -> item.getModuleType().equals(2)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(sonAuthorityList)) {
            updateNoticeModel.setSonAuthority(sonAuthorityList.stream().map(PermissionDict::getName).collect(Collectors.joining(",")));
        }
        updateNoticeModel.setTenantId(userProvider.get().getTenantId());
        updateNoticeModel.setAttendanceNoticeEnum(AttendanceNoticeEnum.ADMINISTRATOR_CHANGE);
        updateNoticeModel.setGroupId(saveGroupAdmin.getGroupId());
        attendanceNoticeHandler.send(updateNoticeModel);
    }

    @Override
    public void batchAddGroupAdmin(BatchSaveGroupAdmin batchSaveGroupAdmin) {
        /* 先查询权限*/
        List<String> permissionIds = batchSaveGroupAdmin.getPermissionIds();
        QueryWrapper<PermissionDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(PermissionDict::getId, permissionIds);
        List<PermissionDict> permissionList = permissionDictMapper.selectList(queryWrapper);
        Map<String, Integer> typeMap = new HashMap<>();
        for (PermissionDict permissionDict : permissionList) {
            typeMap.put(permissionDict.getId(), permissionDict.getModuleType());
        }

        /* 先通过考勤组id和用户id批量删除该组的管理员*/
        String groupId = batchSaveGroupAdmin.getGroupId();
        List<String> userIds = batchSaveGroupAdmin.getUserIds();
        UpdateWrapper<AttendanceManagerPermission> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.lambda()
                .eq(AttendanceManagerPermission::getGroupId, groupId)
                .in(AttendanceManagerPermission::getUserId, userIds);
        attendanceManagerPermissionMapper.delete(deleteWrapper);
        /* 批量入库*/
        batchSaveGroupAdmin.getUserIds().forEach(userId -> {
            List<AttendanceManagerPermission> attendanceManagerPermissionList = new ArrayList<>();
            permissionIds.forEach(pId -> {
                AttendanceManagerPermission insert = new AttendanceManagerPermission();
                insert.setId(RandomUtil.uuId());
                insert.setGroupId(batchSaveGroupAdmin.getGroupId());
                insert.setUserId(userId);
                insert.setPermissionId(pId);
                insert.setType(typeMap.get(pId));
                insert.setCreatorUserId(UserProvider.getLoginUserId());
                insert.setCreatorTime(new Date());
                attendanceManagerPermissionList.add(insert);
            });
            attendanceManagerPermissionMapper.batchSaveGroupAdmin(attendanceManagerPermissionList);
        });
        //执行消息提醒
        AttendanceGroupVo groupVo = attendanceGroupMapper.getGroupBindingOrg(batchSaveGroupAdmin.getGroupId());
        if (Objects.isNull(groupVo)) {
            return;
        }
        AdminUpdateNoticeModel updateNoticeModel = new AdminUpdateNoticeModel();
        updateNoticeModel.setUserIds(batchSaveGroupAdmin.getUserIds());
        updateNoticeModel.setType(1);
        updateNoticeModel.setGroupName(groupVo.getGroupName());
        List<PermissionDict> currentAuthorityList = permissionList.stream().filter(item -> item.getModuleType().equals(1)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(currentAuthorityList)) {
            updateNoticeModel.setCurrentAuthority(currentAuthorityList.stream().map(PermissionDict::getName).collect(Collectors.joining(",")));
        }
        List<PermissionDict> sonAuthorityList = permissionList.stream().filter(item -> item.getModuleType().equals(2)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(sonAuthorityList)) {
            updateNoticeModel.setSonAuthority(sonAuthorityList.stream().map(PermissionDict::getName).collect(Collectors.joining(",")));
        }
        updateNoticeModel.setTenantId(userProvider.get().getTenantId());
        updateNoticeModel.setAttendanceNoticeEnum(AttendanceNoticeEnum.ADMINISTRATOR_CHANGE);
        updateNoticeModel.setGroupId(batchSaveGroupAdmin.getGroupId());
        attendanceNoticeHandler.send(updateNoticeModel);
    }

    @Override
    public void updateGroupAdmin(SaveGroupAdmin saveGroupAdmin) {
        /* 先删除该管理员在该考勤组下的所有权限*/
        UpdateWrapper<AttendanceManagerPermission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(AttendanceManagerPermission::getGroupId, saveGroupAdmin.getGroupId())
                .eq(AttendanceManagerPermission::getUserId, saveGroupAdmin.getUserId());
        attendanceManagerPermissionMapper.delete(updateWrapper);
        saveGroupAdmin.getPermissionIds().forEach(id -> {
            PermissionDict permissionDict = permissionDictMapper.selectById(id);
            save(id, saveGroupAdmin.getGroupId(), saveGroupAdmin.getUserId(), permissionDict.getModuleType());
        });
    }

    /**
     * 删除考勤组管理员
     */
    @Override
    public void deleteGroupAdmin(SaveGroupAdmin saveGroupAdmin) {
        UpdateWrapper<AttendanceManagerPermission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(AttendanceManagerPermission::getGroupId, saveGroupAdmin.getGroupId())
                .eq(AttendanceManagerPermission::getUserId, saveGroupAdmin.getUserId());
        attendanceManagerPermissionMapper.delete(updateWrapper);
        //执行消息提醒
        AttendanceGroupVo groupVo = attendanceGroupMapper.getGroupBindingOrg(saveGroupAdmin.getGroupId());
        if (Objects.isNull(groupVo)) {
            return;
        }
        AdminUpdateNoticeModel updateNoticeModel = new AdminUpdateNoticeModel();
        updateNoticeModel.setUserIds(List.of(saveGroupAdmin.getUserId()));
        updateNoticeModel.setType(2);
        updateNoticeModel.setGroupName(groupVo.getGroupName());
        updateNoticeModel.setTenantId(userProvider.get().getTenantId());
        updateNoticeModel.setGroupId(saveGroupAdmin.getGroupId());
        updateNoticeModel.setAttendanceNoticeEnum(AttendanceNoticeEnum.ADMINISTRATOR_CHANGE);
        attendanceNoticeHandler.send(updateNoticeModel);
    }

    /**
     * 查看考勤组下管理员列表
     *
     * @param groupId 考勤组
     * @return List<AttendanceGroupAdminVo>
     */
    @Override
    public Map<String, Object> listGroupAdmin(String groupId) {
        Map<String, Object> dataMap = new HashMap<>();

        /* 获取审批设置信息*/
        List<AttendanceApprovalSetting> approvalSettings = MybatisUtil.findListByFiled(attendanceApprovalSettingMapper, AttendanceApprovalSetting::getGroupId, groupId, false);
        // 处理新增的外出的初始化
        List<Integer> typeList = approvalSettings.stream().map(AttendanceApprovalSetting::getType).collect(Collectors.toList());
        if (!typeList.contains(ApprovalSettingTypeEnum.GO_OUT.getCode())) {
            AttendanceApprovalSetting attendanceApprovalSetting = new AttendanceApprovalSetting(groupId, ApprovalSettingTypeEnum.GO_OUT.getCode(), ApprovalPermissionTypeEnum.SUPERIOR.getCode());
            approvalSettings.add(attendanceApprovalSetting);
        }
        // 出差审批的初始化
        if (!typeList.contains(ApprovalSettingTypeEnum.BUSINESS_TRIP.getCode())) {
            AttendanceApprovalSetting attendanceApprovalSetting = new AttendanceApprovalSetting(groupId, ApprovalSettingTypeEnum.BUSINESS_TRIP.getCode(), ApprovalPermissionTypeEnum.SUPERIOR.getCode());
            approvalSettings.add(attendanceApprovalSetting);
        }
        approvalSettings = approvalSettings.stream().sorted(comparing(AttendanceApprovalSetting::getType)).collect(Collectors.toList());
        dataMap.put("approvalSettings", approvalSettings);

        List<AttendanceGroupAdminVo> voList = attendanceManagerPermissionMapper.queryGroupUser(groupId);
        if (CollUtil.isEmpty(voList)) {
            voList = new ArrayList<>();
        }
        // 自己组的管理员
        List<String> userIds;
        userIds = voList.stream().map(AttendanceGroupAdminVo::getUserId).collect(Collectors.toList());
        //过滤出当前时间在本组的借调人员
        List<AttendanceGroupUser> selfUsersBeLongToGroup = attendanceUserService.getSelfUsersBeLongToGroup(groupId);
        // 借调用户集合
        List<String> selfCollect;
        if (null != selfUsersBeLongToGroup && !selfUsersBeLongToGroup.isEmpty()) {
            selfCollect = selfUsersBeLongToGroup.stream().map(AttendanceGroupUser::getUserId).collect(Collectors.toList());
            List<AttendanceGroupAdminVo> finalVoList = voList;
            selfUsersBeLongToGroup.forEach(v -> {
                // 当用户是当前借调组的管理员，同时也是用户所属考勤组的管理员， 那么只展示当前借调考勤组的权限信息
                if (!userIds.contains(v.getUserId())) {
                    AttendanceGroupAdminVo vo = attendanceManagerPermissionMapper.queryGroupUserPermissionByUserId(v.getUserId(), v.getGroupId());
                    if (null != vo && StringUtil.isNotEmpty(vo.getUserId())) {
                        vo.setSelfGroupId(v.getGroupId());
                        // 是管理员添加到里面
                        finalVoList.add(vo);
                    }
                }
            });
        } else {
            selfCollect = null;
        }
        if (CollectionUtil.isEmpty(voList)) {
            return dataMap;
        }
        // 处理可能同时是两个组的管理员情况
        ActionResult<List<UserBoundVO>> userVoList = v2UserApi.getAllUserInfoBatch(voList.stream().map(AttendanceGroupAdminVo::getUserId).collect(Collectors.toList()), null);

        if (200 != userVoList.getCode() || CollectionUtil.isEmpty(userVoList.getData())) {
            return dataMap;
        }
        Map<String, List<UserBoundVO>> listMap = userVoList.getData().stream().collect(Collectors.groupingBy(UserBoundVO::getId));
        voList.forEach(vo -> {
            List<UserBoundVO> list = listMap.get(vo.getUserId());
            if (CollectionUtil.isNotEmpty(list)) {
                if (!userIds.contains(vo.getUserId()) && null != selfCollect && selfCollect.contains(vo.getUserId())) {
                    // 查出借调过来的管理员 ，且在名字后拼接（临时借调）
                    vo.setRealName(CollectionUtil.get(list, 0).getUserName() + "(临时借调)");
                } else {
                    vo.setRealName(CollectionUtil.get(list, 0).getUserName());
                }

            }
        });

        dataMap.put("managerList", voList);

        return dataMap;
    }

    /**
     * 获取管理员，包含当前组管理员、上级子组权限管理员、超级管理员，超级管理员groupId为-1
     *
     * @param groupIds 管理员id集合
     * @return Map<String, List < String>> key为 groupId value为管理员userId集合
     */
    @Override
    public Map<String, List<String>> queryUserForCurrAndUpChildAndSuper(List<String> groupIds) {
        List<AttendancePermissionVo> attendancePermissionVos = attendanceManagerPermissionMapper.queryUserForCurrAndUpChildAndSuper(groupIds);
        return attendancePermissionVos.stream().collect(Collectors.groupingBy(AttendancePermissionVo::getGroupId, Collectors.mapping(AttendancePermissionVo::getUserId, Collectors.toList())));
    }

    /**
     * 根据指定权限获取管理员，包含当前组管理员、上级子组权限管理员、超级管理员，超级管理员groupId为-1
     *
     * @param groupIds 管理员id集合
     * @return Map<String, List < String>> key为 groupId value为管理员userId集合
     */
    @Override
    public Map<String, List<String>> queryPermissionBySpecify(List<String> groupIds, List<String> parentCodes, List<String> childCodes) {
        List<AttendancePermissionVo> attendancePermissionVos = attendanceManagerPermissionMapper.queryPermissionBySpecify(groupIds, parentCodes, childCodes);
        return attendancePermissionVos.stream().collect(Collectors.groupingBy(AttendancePermissionVo::getGroupId, Collectors.mapping(AttendancePermissionVo::getUserId, Collectors.toList())));
    }

    /**
     * 获取当前登录用户权限
     *
     * @param groupId 考勤组id
     * @return CurUserPermissionVo
     */
    @Override
    public CurUserPermissionVo getByUserId(String groupId) {


        String loginUserId = UserProvider.getLoginUserId();
        CurUserPermissionVo curUserPermissionVo = new CurUserPermissionVo();
        Boolean sysAdmin = userProvider.get().getIsAdministrator();
        curUserPermissionVo.setIsAdmin(false);
        /* 考勤组超级管理员 && 系统超级管理员*/
        if (!isSuperAdmin(loginUserId) && !sysAdmin) {

            List<PermissionDict> curPermissions = attendanceManagerPermissionMapper.getByUserId(UserProvider.getLoginUserId(), PermissionTypeEnum.CUR.getCode(), PermissionTypeEnum.CUR.getCode(), groupId);
//            List<PermissionDict> childPermissions = attendanceManagerPermissionMapper.getByUserId(UserProvider.getLoginUserId(), PermissionTypeEnum.CHILD.getCode(), PermissionTypeEnum.CHILD.getCode(), groupId);
            curUserPermissionVo.setCurPermissions(curPermissions);
//            curUserPermissionVo.setChildPermissions(childPermissions);
            return curUserPermissionVo;
        }
        /* 考勤超级管理员*/
        curUserPermissionVo.setIsAdmin(true);
        Set<String> permissionTemplate = PermissionUtil.getPermissionTemplate(
                AttendancePermissionConstant.BALANCE_MANAGER,
                AttendancePermissionConstant.USER_MANAGER,
                AttendancePermissionConstant.ATTENDANCE_CONFIGURATION,
                AttendancePermissionConstant.PERMISSION_CONFIGURATION
        );
        curUserPermissionVo.setGroupPermissions(permissionTemplate);
        /* 查询当前组权限*/
        QueryWrapper<PermissionDict> curGroupPermissionQuery = new QueryWrapper<>();
        curGroupPermissionQuery.lambda()
                .eq(PermissionDict::getModuleType, PermissionTypeEnum.CUR.getCode())
                .eq(PermissionDict::getDeleteMark, 0);
        List<PermissionDict> curPermissions = permissionDictMapper.selectList(curGroupPermissionQuery);
        curUserPermissionVo.setCurPermissions(curPermissions);
        /* 子考勤组权限*/
//        QueryWrapper<PermissionDict> childGroupPermissionQuery = new QueryWrapper<>();
//        childGroupPermissionQuery.lambda()
//                .eq(PermissionDict::getModuleType, PermissionTypeEnum.CHILD.getCode())
//                .eq(PermissionDict::getDeleteMark, 0);
//        List<PermissionDict> childPermissions = permissionDictMapper.selectList(childGroupPermissionQuery);
//        curUserPermissionVo.setChildPermissions(childPermissions);
        return curUserPermissionVo;
    }

    @Override
    public Boolean isSuperAdmin(String userId) {
        QueryWrapper<AttendanceManagerPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceManagerPermission::getType, PermissionTypeEnum.SUPER_ADMIN.getCode())
                .eq(AttendanceManagerPermission::getUserId, userId)
                .eq(AttendanceManagerPermission::getDeleteMark, 0);
        AttendanceManagerPermission admin = attendanceManagerPermissionMapper.selectOne(queryWrapper);
        return admin != null;
    }

    @Override
    public AttendanceManagerDetailVo adminDetail(String groupId, String userId) {
        QueryWrapper<AttendanceManagerPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceManagerPermission::getGroupId, groupId)
                .eq(AttendanceManagerPermission::getUserId, userId);
        List<AttendanceManagerPermission> permissionList = attendanceManagerPermissionMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(permissionList)) {
            return new AttendanceManagerDetailVo();
        }
        List<String> permissionIds = permissionList.stream().map(AttendanceManagerPermission::getPermissionId).collect(Collectors.toList());
        AttendanceManagerDetailVo attendanceManagerDetailVo = new AttendanceManagerDetailVo();
        attendanceManagerDetailVo.setUserId(userId);
//        UserEntity userEntity = userApi.getInfoById(userId);
        ActionResult<UserBoundInfoVO> usersBound = v2UserApi.getUsersBound(userId, null);
        if (200 == usersBound.getCode() && null != usersBound.getData()) {
            attendanceManagerDetailVo.setRealName(usersBound.getData().getUserName());
        }
        attendanceManagerDetailVo.setPermissionIds(permissionIds);
        return attendanceManagerDetailVo;
    }

    @Override
    public CurUserPermissionVo queryPermissionByUserId(String userId, List<String> levelCodeList, String permissionName) {
        List<String> groupIdList = getLevelIds(levelCodeList);
        /* 根据考勤组id集合查询管理员权限*/
        if (CollectionUtil.isEmpty(groupIdList)) {
            return new CurUserPermissionVo();
        }
        /* 循环查找我管理的父考勤组子集权限 */
        for (String groupId : groupIdList) {
            CurUserPermissionVo permissionVo = attendanceManagerPermissionMapper.queryByGroupId(groupId, userId, permissionName);
            if (permissionVo != null) {
                return permissionVo;
            }
        }

        return new CurUserPermissionVo();
    }

    @Override
    public Boolean isViewPermission(String groupId) {
        String loginUserId = UserProvider.getLoginUserId();
        Boolean superAdmin = isSuperAdmin(loginUserId);
        Boolean sysAdmin = userProvider.get().getIsAdministrator();
        if (superAdmin || sysAdmin) {
            return true;
        }
        // v1.8.1 获取当前考勤组的管理员列表
//        Boolean x = getManager(groupId, loginUserId);
        if (Boolean.TRUE.equals(getManagerView(groupId, loginUserId, false))) {
            return true;
        }
        // 不是当前考勤组的管理员，那么验证是否是上级的管理员且具备查看权限
        AttendanceGroup attendanceGroup = attendanceGroupMapper.selectById(groupId);
        List<String> levelCodeList = new ArrayList<>();
        levelCodeList.add(attendanceGroup.getLevelCode());
        List<String> levelIds = getLevelIds(levelCodeList);
        if (CollectionUtil.isEmpty(levelIds)) {
            return false;
        }
        boolean x = false;
        for (String levelId : levelIds) {
            if (Boolean.TRUE.equals(getManagerView(levelId, loginUserId, true))) {
                x = true;
                break;
            }
        }
        return x;
        // 当前考勤组的权限列表
//        List<PermissionDict> permissionDictList = getPermissions(groupId);
//        if (CollectionUtil.isNotEmpty(permissionDictList)) {
//            /** 判断是否有查看权限*/
//            List<String> pList = permissionDictList.stream().map(PermissionDict::getName).collect(Collectors.toList());
//            return pList.contains(AttendancePermissionConstant.VIEW);
//        }
//        /** 如果没有继续向上查找*/
//
//        CurUserPermissionVo curUserPermissionVo = queryPermissionByUserId(loginUserId, levelCodeList, null);
//        if (curUserPermissionVo == null || StrUtil.isBlank(curUserPermissionVo.getAllPermissions())) {
//            return false;
//        }
//
//        return curUserPermissionVo.getAllPermissions().contains(AttendancePermissionConstant.VIEW);
    }

    @NotNull
    private Boolean getManagerView(String groupId, String loginUserId, boolean child) {
        Map<String, Object> stringObjectMap = listGroupAdmin(groupId);
        List<AttendanceGroupAdminVo> managerList = JsonUtil.getJsonToList(stringObjectMap.get("managerList"), AttendanceGroupAdminVo.class);
        if (CollectionUtil.isEmpty(managerList)) {
            return false;
        }
        AttendanceGroupAdminVo attendanceGroupAdminVo = managerList.stream().filter(item -> item.getUserId().equals(loginUserId)).findFirst().orElse(null);
        if (child) {
            return null != attendanceGroupAdminVo && attendanceGroupAdminVo.getChildPermissionJson().contains(AttendancePermissionConstant.VIEW);
        } else {
            return null != attendanceGroupAdminVo && attendanceGroupAdminVo.getCurPermissionJson().contains(AttendancePermissionConstant.VIEW);
        }
    }

    /**
     * 获取考勤组权限
     *
     * @param groupId     考勤组
     * @param loginUserId 用户
     */
    private String getManagerDetail(String groupId, String loginUserId) {
        Map<String, Object> stringObjectMap = listGroupAdmin(groupId);
        List<AttendanceGroupAdminVo> managerList = JsonUtil.getJsonToList(stringObjectMap.get("managerList"), AttendanceGroupAdminVo.class);
        if (CollectionUtil.isEmpty(managerList)) {
            return null;
        }
        AttendanceGroupAdminVo attendanceGroupAdminVo = managerList.stream().filter(item -> item.getUserId().equals(loginUserId)).findFirst().orElse(null);
        if (null == attendanceGroupAdminVo) {
            return null;
        }
        return attendanceGroupAdminVo.getChildPermissionJson();
    }

    @Override
    public ActionPermissionVo getActionPermission(String groupId) {
        Boolean sysAdmin = userProvider.get().getIsAdministrator();
        String loginUserId = UserProvider.getLoginUserId();
        Boolean superAdmin = isSuperAdmin(loginUserId);
        if (superAdmin || sysAdmin) {
            /* 系统超级管路||考勤超级管理员*/
            ActionPermissionVo actionPermissionVo = new ActionPermissionVo();
            actionPermissionVo.setPermissionConfig(true);
            actionPermissionVo.setBalanceManager(true);
            actionPermissionVo.setUserManager(true);
            actionPermissionVo.setScheduling(true);
            actionPermissionVo.setAttendanceResult(true);
            actionPermissionVo.setBindingOrg(true);
            actionPermissionVo.setLock(true);
            /* 自定义考勤配置权限*/
            ConfigPermissionVo configPermissionVo = new ConfigPermissionVo();
            configPermissionVo.setBase(true);
            configPermissionVo.setAttendancePoints(true);
            configPermissionVo.setAttendanceClass(true);
            configPermissionVo.setLeaveType(true);
            configPermissionVo.setFestival(true);
            configPermissionVo.setHoliday(true);
            actionPermissionVo.setConfigPermissionVo(configPermissionVo);
            return actionPermissionVo;
        }


        UserPermissions permissionsNew = getPermissionsNew(groupId);
        if (permissionsNew.isParent()) {
            return getActionPermission(permissionsNew.getPermissions(), PermissionTypeEnum.CUR.getCode());
        } else {
            return getActionPermission(permissionsNew.getPermissions(), PermissionTypeEnum.CHILD.getCode());
        }

//        List<PermissionDict> permissions = getPermissions(groupId);
//        if (CollectionUtil.isEmpty(permissions)) {
//            /** 如果没有权限则继续找是否是上级考勤组管理员有子考勤组的操作权限*/
//            AttendanceGroup group = attendanceGroupMapper.selectById(groupId);
//            List<String> levelCodeList = new ArrayList<>();
//            levelCodeList.add(group.getLevelCode());
//            CurUserPermissionVo curUserPermissionVo = this.queryPermissionByUserId(loginUserId, levelCodeList, null);
////        List<String> parentGroupPermissions = curUserPermissionVos.stream().map(CurUserPermissionVo::getAllPermissions).collect(Collectors.toList());
//            ActionPermissionVo actionPermission = getActionPermission(curUserPermissionVo.getAllPermissions(), PermissionTypeEnum.CHILD.getCode());
//            return actionPermission;
//        }
//        ActionPermissionVo actionPermission = getActionPermission(CollectionUtil.join(permissions, ","), PermissionTypeEnum.CUR.getCode());
//        return actionPermission;

    }

    /**
     * 是否有全局设置的权限
     *
     * @return Boolean
     */
    @Override
    public Boolean isGlobalSetting() {
        String loginUserId = UserProvider.getLoginUserId();
        Boolean superAdmin = isSuperAdmin(loginUserId);
        Boolean sysAdmin = userProvider.get().getIsAdministrator();
        return superAdmin || sysAdmin;
    }

    /**
     * 是否是考勤组管理员
     *
     * @return Boolean
     */
    @Override
    public ManagerPermissionVo isManager() {
        String loginUserId = UserProvider.getLoginUserId();
        Boolean superAdmin = isSuperAdmin(loginUserId);
        Boolean sysAdmin = userProvider.get().getIsAdministrator();
        ManagerPermissionVo permissionVo = new ManagerPermissionVo();
        if (sysAdmin || superAdmin) {
            permissionVo.setIsManager(true);
            permissionVo.setScheduling(true);
            permissionVo.setUserManager(true);
            return permissionVo;
        }

        /* 获取当前考勤组权限*/
        QueryWrapper<AttendanceManagerPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceManagerPermission::getDeleteMark, 0)
                .eq(AttendanceManagerPermission::getUserId, loginUserId);
        List<AttendanceManagerPermission> attendanceManagerPermissionList = attendanceManagerPermissionMapper.selectList(queryWrapper);

        permissionVo.setIsManager(CollectionUtil.isNotEmpty(attendanceManagerPermissionList));
        /* 是否有排班权限*/
        if (CollectionUtil.isEmpty(attendanceManagerPermissionList)) {
            permissionVo.setScheduling(false);
            permissionVo.setUserManager(false);
            return permissionVo;
        }
        List<String> permissionIds = attendanceManagerPermissionList.stream().map(AttendanceManagerPermission::getPermissionId).collect(Collectors.toList());
        QueryWrapper<PermissionDict> permissionDictQueryWrapper = new QueryWrapper<>();
        permissionDictQueryWrapper.lambda()
                .in(PermissionDict::getId, permissionIds)
                .eq(PermissionDict::getDeleteMark, 0);
        List<PermissionDict> permissionDictList = permissionDictMapper.selectList(permissionDictQueryWrapper);
        if (CollectionUtil.isNotEmpty(permissionDictList)) {
            /* 如果你是管理员并且有排班权限*/
            List<String> permissionNames = permissionDictList.stream().map(PermissionDict::getName).collect(Collectors.toList());
            permissionVo.setScheduling(permissionNames.contains(AttendancePermissionConstant.SCHEDULING)
                    || permissionNames.contains(AttendancePermissionConstant.MANAGER));

            permissionVo.setUserManager(permissionNames.contains(AttendancePermissionConstant.USER_MANAGER)
                    || permissionNames.contains(AttendancePermissionConstant.MANAGER));

            return permissionVo;
        }
        return permissionVo;
    }

    /**
     * 获取考勤组审批设置
     *
     * @param groupId 考勤组id
     * @param type    审批类型 1.常规补卡审批 2.调整出勤结果审批 3.外勤审批 4.请假审批 5.加班审批
     * @return ApprovalSettingVo
     */
    @Override
    public ApprovalSettingVo getApprovalSettingInfo(String groupId, Integer type) {
        QueryWrapper<AttendanceApprovalSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceApprovalSetting::getGroupId, groupId)
                .eq(AttendanceApprovalSetting::getType, type);
        AttendanceApprovalSetting attendanceApprovalSetting = attendanceApprovalSettingMapper.selectOne(queryWrapper);
        return JsonUtil.getJsonToBean(attendanceApprovalSetting, ApprovalSettingVo.class);
    }

    /**
     * 根据用户id集合查询所属的权限-查询所有权限
     * @param userIds 用户id集合
     * @return FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO
     */
    @Override
    public List<FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO> queryPermissionListByUserIds(List<String> userIds) {
        //查看所有权限
        QueryWrapper<PermissionDict> permissionDictQueryWrapper = new QueryWrapper<>();
        List<PermissionDict> permissionDictList = permissionDictMapper.selectList(permissionDictQueryWrapper);
        //过滤当前考勤组和子考勤组权限
        permissionDictList = permissionDictList.stream().filter(permission -> !"0".equals(permission.getParent())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(permissionDictList)) {
            return new ArrayList<>();
        }

        //顶级权限
        List<String> permissionIdList = permissionDictList.stream().map(PermissionDict::getId).collect(Collectors.toList());
        List<PermissionDict> rootPermissionList = permissionDictList.stream().filter(permission -> {
            return !permissionIdList.contains(permission.getParent());
        }).collect(Collectors.toList());

        Map<String, List<PermissionDict>> permissionGroupMap = rootPermissionList.stream().collect(Collectors.groupingBy(PermissionDict::getName));


        //管理权限
        PermissionDict managerPermission = permissionDictList.stream().filter(permission -> permission.getName().equals(AttendancePermissionConstant.MANAGER)).findFirst().get();

        // 所属权限查询
        QueryWrapper<AttendanceManagerPermission> managerPermissionQueryWrapper = new QueryWrapper<>();
        managerPermissionQueryWrapper.lambda()
                .in(AttendanceManagerPermission::getUserId, userIds)
                .ne(AttendanceManagerPermission::getType, 0);
        List<AttendanceManagerPermission> attendanceManagerPermissionList = attendanceManagerPermissionMapper.selectList(managerPermissionQueryWrapper);
        if (CollectionUtil.isEmpty(attendanceManagerPermissionList)) {
            return new ArrayList<>();
        }
        List<String> managerPermissionIdList = attendanceManagerPermissionList.stream().map(AttendanceManagerPermission::getPermissionId).collect(Collectors.toList());
        List<FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO> voList = new ArrayList<>();

        Set<String> permissionKeys = permissionGroupMap.keySet();
        for (String permissionKey : permissionKeys) {
            FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO vo = new FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO();
            List<PermissionDict> permissionDicts = permissionGroupMap.get(permissionKey);
            PermissionDict permissionDict = permissionDicts.get(0);
            vo.setMenuName(permissionDict.getName());
            List<PermissionDict> childPermissionList = permissionDictList.stream().filter(permission -> {
                return permission.getParent().equals(permissionDict.getId());
            }).collect(Collectors.toList());
            boolean hasChild = CollectionUtil.isNotEmpty(childPermissionList);
            if (hasChild) {
                //获取该配置的子权限
                List<PermissionDict> chilList = permissionDictList.stream().filter(permission -> {
                    return permission.getParent().equals(permissionDict.getId());
                }).collect(Collectors.toList());
                List<FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO> childVoList = new ArrayList<>();
                for (PermissionDict dict : chilList) {
                    FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO childVo = new FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO();
                    childVo.setMenuName(dict.getName());
                    childVo.setParentId(permissionDict.getId());
                    childVo.setChecked(managerPermissionIdList.contains(dict.getId()) || managerPermissionIdList.contains(managerPermission.getId()));
                    childVoList.add(childVo);
                }
                vo.setChildrenList(childVoList);
                long count = childVoList.stream().filter(FtbPermissionPositionMenuVO.FtbPermissionPositionMenuInnerVO::getChecked).count();
                vo.setChecked(count > 0);
                voList.add(vo);
                continue;
            }
            List<String> hasPermissionIds = permissionDicts.stream().map(PermissionDict::getId).collect(Collectors.toList());
            Collection<String> intersection = CollectionUtil.intersection(managerPermissionIdList, hasPermissionIds);
            vo.setChecked(CollectionUtil.isNotEmpty(intersection));
            if (managerEmbodyPermissions.contains(permissionDict.getName()) && managerPermissionIdList.contains(managerPermission.getId())) {
                vo.setChecked(true);
            }
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public AttendanceTeamSetVo getTeamSet(GroupFilterDto dto) {
        AttendanceGroup attendanceGroup = attendanceGroupService.getById(dto.getGroupId());
        Assert.notNull(attendanceGroup, "考勤组不存在");
        AttendanceTeamSetVo teamSet = AttendanceTeamSetVo.builder().build();
        //获取考勤组负责人
        teamSet.setManagerId(attendanceGroup.getManagerId());
        UserEntity managerUserInfo = v2UserApi.getEntityByUserId(attendanceGroup.getManagerId());
        teamSet.setManagerName(Objects.nonNull(managerUserInfo) ? managerUserInfo.getRealName() : "");
        //获取考勤组班制类型
        AttendanceShiftSettingVo shiftSettingVo = shiftSettingService.findByGroupId(dto.getGroupId());
        if (Objects.nonNull(shiftSettingVo)) {
            teamSet.setSystemType(shiftSettingVo.getSystemType());
        }
        //获取考勤组月报通知
        teamSet.setMonthNotice(attendanceGroup.getMonthlyReportNotice());
        return teamSet;
    }

    @Override
    @Transactional
    public Boolean setMonthNotice(GroupFilterDto dto) {
        AttendanceGroup attendanceGroup = attendanceGroupService.getById(dto.getGroupId());
        Assert.notNull(attendanceGroup, "考勤组不存在");
        attendanceGroup.setMonthlyReportNotice(attendanceGroup.getMonthlyReportNotice().equals(1) ? 0 : 1);
        return attendanceGroupService.updateById(attendanceGroup);
    }

    private ActionPermissionVo getActionPermission(String permissionNames, Integer type) {
        if (StrUtil.isBlank(permissionNames)) {
            return new ActionPermissionVo();
        }
        ActionPermissionVo actionPermissionVo = new ActionPermissionVo();
        if (PermissionTypeEnum.CUR.getCode().equals(type)) {
            /* 当前考勤组*/
            actionPermissionVo.setBalanceManager(permissionNames.contains(AttendancePermissionConstant.BALANCE_MANAGER));
            actionPermissionVo.setUserManager(permissionNames.contains(AttendancePermissionConstant.USER_MANAGER));
            actionPermissionVo.setScheduling(permissionNames.contains(AttendancePermissionConstant.SCHEDULING));
            actionPermissionVo.setAttendanceResult(permissionNames.contains(AttendancePermissionConstant.ATTENDANCE_RESULT));
            actionPermissionVo.setPermissionConfig(permissionNames.contains(AttendancePermissionConstant.PERMISSION_CONFIGURATION));
            actionPermissionVo.setLock(permissionNames.contains(AttendancePermissionConstant.PERMISSION_LOCKED));
            actionPermissionVo.setBindingOrg(permissionNames.contains(AttendancePermissionConstant.BINDING_ORG));

            /* 自定义考勤组配置*/
            ConfigPermissionVo configPermissionVo = new ConfigPermissionVo();
            configPermissionVo.setBase(permissionNames.contains(AttendancePermissionConstant.BASE));
            configPermissionVo.setAttendancePoints(permissionNames.contains(AttendancePermissionConstant.ATTENDANCE_POINTS));
            configPermissionVo.setAttendanceClass(permissionNames.contains(AttendancePermissionConstant.ATTENDANCE_CLASS));
            configPermissionVo.setLeaveType(permissionNames.contains(AttendancePermissionConstant.LEAVE_TYPE));
            configPermissionVo.setFestival(permissionNames.contains(AttendancePermissionConstant.FESTIVAL));
            configPermissionVo.setHoliday(permissionNames.contains(AttendancePermissionConstant.HOLIDAY));
            actionPermissionVo.setConfigPermissionVo(configPermissionVo);

            return actionPermissionVo;
        }
        /* 子考勤组*/
        if (permissionNames.contains(AttendancePermissionConstant.MANAGER)) {
//            actionPermissionVo.setAttendanceResult(true);
            actionPermissionVo.setPermissionConfig(true);
            actionPermissionVo.setUserManager(true);
            actionPermissionVo.setBalanceManager(true);
            actionPermissionVo.setScheduling(true);
            actionPermissionVo.setBindingOrg(true);
            actionPermissionVo.setLock(true);
            ConfigPermissionVo configPermissionVo = new ConfigPermissionVo();
            configPermissionVo.setBase(true);
            configPermissionVo.setAttendancePoints(true);
            configPermissionVo.setAttendanceClass(true);
            configPermissionVo.setLeaveType(true);
            configPermissionVo.setFestival(true);
            configPermissionVo.setHoliday(true);
            actionPermissionVo.setConfigPermissionVo(configPermissionVo);
        }

        actionPermissionVo.setAttendanceResult(permissionNames.contains(AttendancePermissionConstant.CHILD_ADJUST_ATTENDANCE_RESULTS));
        return actionPermissionVo;
    }

    private UserPermissions getPermissionsNew(String groupId) {
        UserPermissions userPermissions = new UserPermissions();
        Map<String, Object> stringObjectMap = listGroupAdmin(groupId);
        List<AttendanceGroupAdminVo> managerList = JsonUtil.getJsonToList(stringObjectMap.get("managerList"), AttendanceGroupAdminVo.class);
        if (!CollectionUtil.isEmpty(managerList)) {
            AttendanceGroupAdminVo attendanceGroupAdminVo = managerList.stream().filter(item -> item.getUserId().equals(UserProvider.getLoginUserId())).findFirst().orElse(null);
            if (null != attendanceGroupAdminVo) {
                userPermissions.setParent(true);
                userPermissions.setPermissions(attendanceGroupAdminVo.getCurPermissionJson());
                // 是当前考勤组管理员 返回本组权限
                return userPermissions;
            }
        }
        // 不是本组管理员，查看是否是上级的管理员且具有子集管理权限
        AttendanceGroup attendanceGroup = attendanceGroupMapper.selectById(groupId);
        List<String> levelCodeList = new ArrayList<>();
        levelCodeList.add(attendanceGroup.getLevelCode());
        List<String> levelIds = getLevelIds(levelCodeList);
        if (!CollectionUtil.isEmpty(levelIds)) {
            for (String levelId : levelIds) {
                // 子集权限集合
                String managerDetail = getManagerDetail(levelId, UserProvider.getLoginUserId());
                if (null != managerDetail) {
                    userPermissions.setPermissions(managerDetail);
                    return userPermissions;
                }
            }
        }
        return userPermissions;
    }

    /**
     * 考勤组管理员权限入库
     *
     * @param permissionId 权限id
     * @param groupId      考勤组id
     * @param userId       用户id
     * @param type         权限类型 1.当前考勤组 2.子考勤组
     */
    private void save(String permissionId, String groupId, String userId, Integer type) {
        QueryWrapper<AttendanceManagerPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AttendanceManagerPermission::getDeleteMark, 0)
                .eq(AttendanceManagerPermission::getGroupId, groupId)
                .eq(AttendanceManagerPermission::getPermissionId, permissionId)
                .eq(AttendanceManagerPermission::getType, type)
                .eq(AttendanceManagerPermission::getUserId, userId);
        AttendanceManagerPermission attendanceManagerPermission = attendanceManagerPermissionMapper.selectOne(queryWrapper);
        if (attendanceManagerPermission == null) {
            AttendanceManagerPermission insert = new AttendanceManagerPermission();
            insert.setId(RandomUtil.uuId());
            insert.setGroupId(groupId);
            insert.setUserId(userId);
            insert.setPermissionId(permissionId);
            insert.setType(type);
            insert.setCreatorUserId(UserProvider.getLoginUserId());
            insert.setCreatorTime(new Date());
            attendanceManagerPermissionMapper.insert(insert);
        }
    }

}
