package com.tuoheng.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.common.common.BaseQuery;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.system.dto.RoleMenuDto;
import com.tuoheng.system.entity.Menu;
import com.tuoheng.system.entity.Role;
import com.tuoheng.system.entity.RoleMenu;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.mapper.RoleMapper;
import com.tuoheng.system.mapper.RoleMenuMapper;
import com.tuoheng.system.query.RoleQuery;
import com.tuoheng.system.service.IMenuService;
import com.tuoheng.system.service.IRoleMenuService;
import com.tuoheng.system.service.IRoleService;
import com.tuoheng.system.service.ITenantService;
import com.tuoheng.system.vo.role.RoleListVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author 拓恒
 * @since 2020-10-31
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private ITenantService tenantService;
    /**
     * 获取角色列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {

        RoleQuery roleQuery = (RoleQuery) query;
        // 查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 角色名称
        if (!StringUtils.isEmpty(roleQuery.getName())) {
            queryWrapper.like("name", roleQuery.getName());
        }
        queryWrapper.eq("tenant_id", tenantService.getCurrentTenantId());
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");

        // 查询分页数据
        IPage<Role> page = new Page<>(roleQuery.getPage(), roleQuery.getLimit());
        IPage<Role> pageData = roleMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            RoleListVo roleListVo = Convert.convert(RoleListVo.class, x);
            // TODO...
            return roleListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取角色列表
     *
     * @return
     */
    @Override
    public JsonResult getRoleList() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("mark", 1);
        queryWrapper.eq("tenant_id", tenantService.getCurrentTenantId());
        queryWrapper.orderByAsc("sort");
        return JsonResult.success(list(queryWrapper));
    }

    /**
     * 获取菜单列表
     *
     * @param roleId 角色ID
     * @return
     */
    @Override
    public JsonResult getMenuList(Integer roleId) {
        List<Menu> menuList = menuService.getMenuAll();
        if (!menuList.isEmpty()) {
            // 获取角色菜单列表
            QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", roleId);
            queryWrapper.select("menu_id");
            List<RoleMenu> roleMenuList = roleMenuMapper.selectList(queryWrapper);
            List<Integer> menuIds = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
            menuList.forEach(item -> {
                if (menuIds.contains(item.getId())) {
                    item.setChecked(true);
                    item.setOpen(true);
                }
            });
        }
        return JsonResult.success(menuList);
    }

    /**
     * 保存角色菜单权限数据
     *
     * @param roleMenuDto 角色菜单Dto
     * @return
     */
    @Override
    public JsonResult savePermission(RoleMenuDto roleMenuDto) {
        // 角色ID校验
        if (StringUtils.isNull(roleMenuDto.getRoleId())) {
            return JsonResult.error("角色ID不能位空");
        }
        // 同步删除角色菜单关系数据
        roleMenuService.deleteRoleMenus(roleMenuDto.getRoleId());
        // 插入新的角色菜单关系数据
        List<RoleMenu> roleMenuList = new ArrayList<>();
        if (roleMenuDto.getMenuIds().length > 0) {
            for (Integer menuId : roleMenuDto.getMenuIds()) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleMenuDto.getRoleId());
                roleMenu.setMenuId(Integer.valueOf(menuId));
                roleMenuList.add(roleMenu);
            }
        }
        // 批量插入角色菜单关系数据
        roleMenuService.saveBatch(roleMenuList);
        return JsonResult.success("权限保存成功");
    }
}
