package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.params.UserPushParam;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.PushUserTrack;
import com.qmth.teachcloud.common.entity.SysPrivilege;
import com.qmth.teachcloud.common.entity.SysRolePrivilege;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.userPush.SpecialPrivilegeEnum;
import com.qmth.teachcloud.common.enums.userPush.UserPushTrackEnum;
import com.qmth.teachcloud.common.mapper.PushUserTrackMapper;
import com.qmth.teachcloud.common.service.PushUserTrackService;
import com.qmth.teachcloud.common.service.SysPrivilegeService;
import com.qmth.teachcloud.common.service.SysRolePrivilegeService;
import com.qmth.teachcloud.common.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 用户推送轨迹表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-11-04
 */
@Service
public class PushUserTrackServiceImpl extends ServiceImpl<PushUserTrackMapper, PushUserTrack> implements PushUserTrackService {
    @Resource
    SysUserService sysUserService;
    @Resource
    SysPrivilegeService sysPrivilegeService;
    @Resource
    SysRolePrivilegeService sysRolePrivilegeService;


    @Transactional
    @Override
    public List<PushUserTrack> createPushTrackUser(Set<Long> dbRoleIdSet, Set<Long> currentRoleIdSet, Long userId, boolean enable,Long requestUserId) {
        List<PushUserTrack> pushUserTrackList = new ArrayList<>();
        SysUser currentUser = sysUserService.getById(userId);
        if (Objects.isNull(currentUser)) {
            throw ExceptionResultEnum.ERROR.exception("用户不存在");
        }
        // 查询该学校特殊权限id
        // 评卷员权限
        SysPrivilege marker = sysPrivilegeService.list(new QueryWrapper<SysPrivilege>().lambda()
                .eq(SysPrivilege::getUrl, SpecialPrivilegeEnum.MARKER.getId())).get(0);
        Long markerId = marker.getId();

        // 科组长权限
        SysPrivilege subjectHeader = sysPrivilegeService.list(new QueryWrapper<SysPrivilege>().lambda()
                .eq(SysPrivilege::getUrl, SpecialPrivilegeEnum.SUBJECT_HEADER.getId())).get(0);
        Long subjectHeaderId = subjectHeader.getId();
        if (currentRoleIdSet.size() > 0) {
            List<SysRolePrivilege> sysRolePrivilegeList = sysRolePrivilegeService.list(new QueryWrapper<SysRolePrivilege>().lambda().in(SysRolePrivilege::getRoleId, currentRoleIdSet));
            Set<Long> priIds = sysRolePrivilegeList.stream().map(SysRolePrivilege::getPrivilegeId).collect(Collectors.toSet());
            if (priIds.size() > 0) {
                PushUserTrack markerTrack = new PushUserTrack();
                PushUserTrack headerTrack = new PushUserTrack();
                // 直接查轨迹表的数据
                List<PushUserTrack> specialUserTrack = this.list(new QueryWrapper<PushUserTrack>().lambda().eq(PushUserTrack::getUserId, userId));
                if (specialUserTrack.size() > 0){
                    List<PushUserTrack> markerTrackList = specialUserTrack.stream().filter(e -> SpecialPrivilegeEnum.MARKER.equals(e.getIdentify())).sorted(Comparator.comparing(PushUserTrack::getCreateTime).reversed()).limit(1).collect(Collectors.toList());
                    List<PushUserTrack> headerTrackList = specialUserTrack.stream().filter(e -> SpecialPrivilegeEnum.SUBJECT_HEADER.equals(e.getIdentify())).sorted(Comparator.comparing(PushUserTrack::getCreateTime).reversed()).limit(1).collect(Collectors.toList());
                    if (markerTrackList.size() == 1){
                        markerTrack = markerTrackList.get(0);
                    }
                    if (headerTrackList.size() == 1){
                        headerTrack = headerTrackList.get(0);
                    }

                }

                markerTrack.setUserId(userId);
                markerTrack.setSchoolId(currentUser.getSchoolId());
                markerTrack.setIdentify(SpecialPrivilegeEnum.MARKER);


                headerTrack.setUserId(userId);
                headerTrack.setSchoolId(currentUser.getSchoolId());
                headerTrack.setIdentify(SpecialPrivilegeEnum.SUBJECT_HEADER);

                if (priIds.contains(markerId) && !priIds.contains(subjectHeaderId)) {

                    // 当前角色权限为评卷员权限
                    if (enable) {
                        markerTrack.setOperate(UserPushTrackEnum.BIND);
                    } else {
                        markerTrack.setOperate(UserPushTrackEnum.UNBIND);
                    }
                    headerTrack.setOperate(UserPushTrackEnum.UNBIND);
                } else if (!priIds.contains(markerId) && priIds.contains(subjectHeaderId)) {

                    // 当前角色权限为科组长权限
                    markerTrack.setOperate(UserPushTrackEnum.UNBIND);
                    if (enable) {
                        headerTrack.setOperate(UserPushTrackEnum.BIND);
                    } else {
                        headerTrack.setOperate(UserPushTrackEnum.UNBIND);
                    }
                } else if (priIds.contains(markerId) && priIds.contains(subjectHeaderId)) {

                    // 当前角色权限为复合权限
                    if (enable) {
                        markerTrack.setOperate(UserPushTrackEnum.BIND);
                        headerTrack.setOperate(UserPushTrackEnum.BIND);
                    } else {
                        markerTrack.setOperate(UserPushTrackEnum.UNBIND);
                        headerTrack.setOperate(UserPushTrackEnum.UNBIND);
                    }
                } else {
                    // 无特殊权限
                    if (dbRoleIdSet != null && dbRoleIdSet.size() > 0) {
                        // 可以获得原角色判断
                        List<SysRolePrivilege> beforeSysRolePrivilegeList = sysRolePrivilegeService.list(new QueryWrapper<SysRolePrivilege>().lambda().in(SysRolePrivilege::getRoleId, dbRoleIdSet));
                        Set<Long> beforePris = beforeSysRolePrivilegeList.stream().map(SysRolePrivilege::getPrivilegeId).collect(Collectors.toSet());
                        if (beforePris.contains(markerId) || beforePris.contains(subjectHeaderId)) {
                            // 如果该用户原先的角色且原先用户含有特殊角色，但新用户新角色一个都不含，要发送两个解绑
                            markerTrack.setOperate(UserPushTrackEnum.UNBIND);
                            headerTrack.setOperate(UserPushTrackEnum.UNBIND);
                        } else {
                            // 原先角色从没有过特殊权限，更新后的也没有（普通用户）
                            markerTrack = null;
                            headerTrack = null;
                        }
                    } else {
                        // 无法获取原用户表角色 -> 去轨迹表查询
                        List<PushUserTrack> specialUserCheck = this.list(new QueryWrapper<PushUserTrack>().lambda().eq(PushUserTrack::getUserId, userId));
                        if (specialUserCheck.size() > 0) {
                            // 该用户是特殊用户（就算现在不是曾经也是过）
                            markerTrack.setOperate(UserPushTrackEnum.UNBIND);
                            headerTrack.setOperate(UserPushTrackEnum.UNBIND);
                        } else {
                            // 原先角色从没有过特殊权限，更新后的也没有（普通用户）
                            markerTrack = null;
                            headerTrack = null;
                        }
                    }
                }
                if (Objects.nonNull(markerTrack)) {
                    if (SystemConstant.longNotNull(markerTrack.getId())){
                        // 更新
                        markerTrack.updateInfo(requestUserId);
                    }else {
                        // 新增
                        markerTrack.insertInfo(requestUserId);
                    }
                    pushUserTrackList.add(markerTrack);
                    this.saveOrUpdate(markerTrack);
                }
                if (Objects.nonNull(headerTrack)) {
                    if (SystemConstant.longNotNull(headerTrack.getId())){
                        // 更新
                        headerTrack.updateInfo(requestUserId);
                    }else {
                        // 新增
                        headerTrack.insertInfo(requestUserId);
                    }
                    pushUserTrackList.add(headerTrack);
                    this.saveOrUpdate(headerTrack);
                }
            }
        }
        return pushUserTrackList;
    }


    @Transactional
    @Override
    public List<UserPushParam> analyzeUserPushSpecialPrivilege(List<PushUserTrack> pushUserTrackList) {
        List<UserPushParam> userPushParamList = new ArrayList<>();
        if (pushUserTrackList != null && pushUserTrackList.size() > 0) {
            for (PushUserTrack pushUserTrack : pushUserTrackList) {
                Long userId = pushUserTrack.getUserId();
                SysUser currentUser = sysUserService.getById(userId);
                SpecialPrivilegeEnum identify = pushUserTrack.getIdentify();
                UserPushTrackEnum operate = pushUserTrack.getOperate();

                UserPushParam cell = new UserPushParam();
                cell.setUserId(userId);
                cell.setSchoolId(currentUser.getSchoolId());
                cell.setName(currentUser.getRealName());
                cell.setPassword("123456");
                cell.setRole(identify);
                cell.setAccount(identify.getPrefix() + currentUser.getLoginName());

                if (UserPushTrackEnum.BIND.equals(operate)) {
                    // 绑定
                    cell.setEnable(true);
                } else {
                    // 解绑
                    cell.setEnable(false);
                }
                userPushParamList.add(cell);
            }
        }
        return userPushParamList;
    }
}
