package com.tuoheng.admin.service.system.permissions;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.admin.entity.dto.RolePermissionDto;
import com.tuoheng.admin.entity.domain.Menu;
import com.tuoheng.admin.entity.domain.OpPermissions;
import com.tuoheng.admin.entity.domain.OpRolePermission;
import com.tuoheng.admin.entity.domain.RoleMenu;
import com.tuoheng.admin.mapper.MenuMapper;
import com.tuoheng.admin.mapper.OpPermissionsMapper;
import com.tuoheng.admin.mapper.OpRolePermissionMapper;
import com.tuoheng.admin.mapper.RoleMenuMapper;
import com.tuoheng.admin.entity.query.RoleClientQuery;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Author ChengWang
 * @Date 2022/12/16
 */

@Service
@Slf4j
public class OpPermissionsServiceImpl extends ServiceImpl<OpPermissionsMapper, OpPermissions> implements OpPermissionsService{

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private OpPermissionsMapper opPermissionsMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private OpRolePermissionMapper opRolePermissionMapper;

    @Override
    public JsonResult getRolePermissionByRoleId(RoleClientQuery query) {
        RolePermissionDto rolePermissionDto = new RolePermissionDto();
        //根据角色id查询出对应的菜单列表 -> 无父级
        List<Menu> opMenusDtoList = menuMapper.getOpMenusByRoleId(query.getRoleId(), query.getClientId());
        for (Menu opMenusDto : opMenusDtoList) {
            //根据父级id查询出对应所属的菜单
            extracted(query, opMenusDto);
        }
        rolePermissionDto.setRoleId(query.getRoleId())
                .setOpMenusList(opMenusDtoList)
                //根据角色id查询出对应的权限集合
                .setPermissionsList(opPermissionsMapper.getOpPermissionsByRoleId(query.getRoleId(), query.getClientId()));
        return JsonResult.success(rolePermissionDto);
    }

    @Override
    @Transactional(readOnly = true)
    public JsonResult getRoleIdListByApiUrl(String apiUrl) {
        //根据接口url查询出所属的角色
        List<Integer> roleIdsByApiUrl = opPermissionsMapper.getRoleIdsByApiUrl(apiUrl);
        return JsonResult.success(roleIdsByApiUrl);
    }

    @Override
    public JsonResult edit(OpPermissions opPermissions) {
        Integer opPermissionsId = opPermissions.getId();
        //添加
        if (null == opPermissionsId) {
            //默认
            opPermissions.setCreateUser(CurrentUserUtil.getUserId());
            opPermissions.setCreateTime(DateUtils.now());
            opPermissionsMapper.insert(opPermissions);
            //添加对应创建权限时的关联关系 只给超管对应角色进行添加对应关联关系
            OpRolePermission opRolePermission = new OpRolePermission();
            opRolePermission.setRoleId(1);
            opRolePermission.setPermissionId(opPermissions.getId());
            opRolePermissionMapper.insert(opRolePermission);
        } else {
            opPermissions.setUpdateUser(CurrentUserUtil.getUserId());
            opPermissions.setUpdateTime(DateUtils.now());
            opPermissionsMapper.updateById(opPermissions);
        }
        return JsonResult.success();
    }


    /**
     * 封装方法 递归菜单 层级
     *
     * @param query
     * @param item
     */
    private void extracted(RoleClientQuery query, Menu item) {
        List<Menu> list = menuMapper.getChildrenMenuByPid(item.getId(), query.getClientId());
        if (StringUtils.isNotEmpty(list)) {
            QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", query.getRoleId());
            queryWrapper.select("menu_id");
            List<RoleMenu> roleMenuList = roleMenuMapper.selectList(queryWrapper);
            List<Integer> menuIds = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
            List<Menu> collect = list.stream().map(t -> {
                if (menuIds.contains(t.getId())) {
                    t.setChecked(true);
                    t.setOpen(true);
                }
                extracted(query, t);
                return t;
            }).filter(t -> t.isChecked() == true).collect(Collectors.toList());
            item.setChildren(collect);
        }
    }

}
