package com.njcn.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.user.enums.UserResponseEnum;
import com.njcn.user.mapper.RoleComponentMapper;
import com.njcn.user.mapper.RoleFunctionMapper;
import com.njcn.user.mapper.RoleMapper;
import com.njcn.user.mapper.UserRoleMapper;
import com.njcn.user.pojo.constant.RoleType;
import com.njcn.user.pojo.param.RoleParam;
import com.njcn.user.pojo.po.Role;
import com.njcn.user.pojo.po.RoleComponent;
import com.njcn.user.pojo.po.RoleFunction;
import com.njcn.user.pojo.po.UserRole;
import com.njcn.user.pojo.vo.RoleVO;
import com.njcn.user.service.IRoleService;
import com.njcn.user.service.IUserRoleService;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2021-12-13
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final IUserRoleService userRoleService;

    private final UserRoleMapper userRoleMapper;

    private final RoleFunctionMapper roleFunctionMapper;

    private final RoleComponentMapper roleComponentMapper;

    @Override
    public List<String> getRoleNameByUserId(String id) {
        List<UserRole> userRoles = userRoleService.getUserRoleByUserId(id);
        if (CollectionUtils.isEmpty(userRoles)) {
            return new ArrayList<>();
        }
        List<Role> roles = this.lambdaQuery()
                .select(Role::getCode)
                .eq(Role::getState, DataStateEnum.ENABLE.getCode())
                .in(Role::getId, userRoles.stream()
                        .map(UserRole::getRoleId)
                        .collect(Collectors.toList())
                ).list();
        return roles
                .stream()
                .map(Role::getCode)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getNameByUserId(String id) {
        List<UserRole> userRoles = userRoleService.getUserRoleByUserId(id);
        if (CollectionUtils.isEmpty(userRoles)) {
            return new ArrayList<>();
        }
        List<Role> roles = this.lambdaQuery()
                .select(Role::getName)
                .eq(Role::getState, DataStateEnum.ENABLE.getCode())
                .in(Role::getId, userRoles.stream()
                        .map(UserRole::getRoleId)
                        .collect(Collectors.toList())
                ).list();
        return roles
                .stream()
                .map(Role::getName)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getIdByUserId(String id) {
        return userRoleService.getUserRoleByUserId(id).stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> getCodeByList(List<String> list) {
        return this.lambdaQuery().in(Role::getId, list).list().stream().map(Role::getCode).distinct().collect(Collectors.toList());
    }

    @Override
    public Page<RoleVO> listRole(RoleParam.QueryParam queryParam) {
        QueryWrapper<RoleVO> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(queryParam)) {
            //查询参数不为空，进行条件填充
            if (StrUtil.isNotBlank(queryParam.getSearchValue())) {
                //部门根据名称模糊查询
                queryWrapper
                        .and(param -> param.like("sys_role.name", queryParam.getSearchValue()));
            }
        }
        queryWrapper.ne("sys_role.state", DataStateEnum.DELETED.getCode());
        if (queryParam.getType().equals(0)) {
            queryWrapper.in("sys_role.type", queryParam.getType(), 1);
        } else if (queryParam.getType().equals(1)) {
            queryWrapper.eq("sys_role.type", 2);
        }
        //初始化分页数据
        return this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper);
    }

    @Override
    public List<Role> selectRoleDetail(Integer id) {
        List<Integer> role = new ArrayList<>();
        role.add(RoleType.USER);
        role.add(RoleType.APP);
        if (Objects.equals(id, RoleType.SUPER_ADMINISTRATOR)) {
            role.add(RoleType.ADMINISTRATOR);
        }
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("sys_role.state", DataStateEnum.DELETED.getCode());
        queryWrapper.in("sys_role.type", role).orderByAsc("sys_role.type");
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean addRole(RoleParam roleParam) {
        checkDicDataCode(roleParam, false);
        Role role = new Role();
        BeanUtil.copyProperties(roleParam, role);
        //默认为正常状态
        role.setState(DataStateEnum.ENABLE.getCode());
        return this.save(role);
    }

    @Override
    public boolean updateRole(RoleParam.RoleUpdateParam updateParam) {
        checkDicDataCode(updateParam, true);
        Role role = new Role();
        BeanUtil.copyProperties(updateParam, role);
        return this.updateById(role);
    }

    @Override
    public boolean deleteRole(List<String> ids) {
        // 删除角色和用户的绑定
        this.baseMapper.deleteUserRole(ids);
        // 删除角色和资源的绑定
        this.baseMapper.deleteFunctionRole(ids);
        // 删除角色和组件的绑定
        this.baseMapper.deleteComponentRole(ids);
        return this.lambdaUpdate().set(Role::getState, DataStateEnum.DELETED.getCode()).in(Role::getId, ids).update();
    }

    @Override
    public Boolean selectRelevance(List<String> ids) {
        // 判断角色是否和用户绑定
        List<UserRole> userRoleList = this.userRoleMapper.selectUserRole(ids);
        // 判断角色是否和资源绑定
        List<RoleFunction> roleFunctionList = this.roleFunctionMapper.selectRoleFunction(ids);
        // 判断角色是否和组件绑定
        List<RoleComponent> roleComponentList = this.roleComponentMapper.selectRoleComponet(ids);
        if (!userRoleList.isEmpty() || !roleComponentList.isEmpty() || !roleFunctionList.isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    public Role getRoleByCode(String code) {
        return this.lambdaQuery().eq(Role::getCode, code).eq(Role::getState, 1).one();
    }

    @Override
    public List<Role> allRoleList() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("sys_role.state", DataStateEnum.DELETED.getCode());
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 角色类型 0:超级管理员；1:管理员；2:普通用户
     */
    @Override
    public List<Role> simpleList() {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Role::getId, Role::getName).eq(Role::getState, DataStateEnum.ENABLE.getCode()).eq(Role::getType, 2);
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 校验参数，检查是否存在相同编码的角色代码
     */
    private void checkDicDataCode(RoleParam roleParam, boolean isExcludeSelf) {
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper
                .eq(Role::getName, roleParam.getName())
                .eq(Role::getState, DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            if (roleParam instanceof RoleParam.RoleUpdateParam) {
                roleLambdaQueryWrapper.ne(Role::getId, ((RoleParam.RoleUpdateParam) roleParam).getId());
            }
        }
        int countByAccount = this.count(roleLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new BusinessException(UserResponseEnum.ROLE_NAME_REPEAT);
        }
    }
}
