package com.hzs.system.sys.provider;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.system.sys.SysRoleMenuColumn;
import com.hzs.system.sys.IMenuColumnServiceApi;
import com.hzs.system.sys.service.ISysRoleMenuColumnService;
import com.hzs.system.sys.service.ISysUserMenuService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @Description: 菜单列服务
 * @Author: jiang chao
 * @Time: 2023/6/8 11:23
 * @Classname: MenuColumnServiceProvider
 * @PackageName: com.hzs.system.sys.provider
 */
@DubboService
public class MenuColumnServiceProvider implements IMenuColumnServiceApi {

    @Autowired
    private ISysRoleMenuColumnService iSysRoleMenuColumnService;
    @Autowired
    private ISysUserMenuService iSysUserMenuService;

    @Autowired
    private RedisService redisService;

    @Override
    public R<Map<String, Integer>> queryMenuColumn(String perms, Long userId) {
        // 列权限map（key: 列名，value: 是否显示（0=显示））
        Map<String, Integer> columnMap = new HashMap<>();

        List<SysRoleMenuColumn> columnList = iSysRoleMenuColumnService.queryMenuColumn(perms, userId);
        if (CollectionUtil.isNotEmpty(columnList)) {
            for (SysRoleMenuColumn sysRoleMenuColumn : columnList) {
                columnMap.put(sysRoleMenuColumn.getMenuColumn(), sysRoleMenuColumn.getShowFlag());
            }
        }
        return R.ok(columnMap);
    }

    @Override
    public R<?> checkMenuPerms(List<String> permList, Long userId) {
        if (CollectionUtil.isEmpty(permList)) {
            // 没有权限，直接返回成功
            return R.ok();
        }

        // 缓存key值
        String cacheKey = CacheConstants.MANAGE_ACCESS_PERMISSIONS + userId;
        List<String> dataList = redisService.getCacheObject(cacheKey);
        if (CollectionUtil.isEmpty(dataList)) {
            dataList = iSysUserMenuService.listMenuPerms(userId);
            redisService.setCacheObject(cacheKey, dataList);
        }

        if (dataList.containsAll(permList)) {
            // 有权限，返回成功
            return R.ok();
        }
        return R.fail();
    }

}
