package com.wb.permission.domain;

import cn.hutool.core.util.ObjectUtil;
import com.ag.base.DefaultBussniessImpl;
import com.ag.base.IRedisService;
import com.ag.util.StrUtil;
import com.wb.permission.pojo.WbMenu;
import com.wb.permission.pojo.WbRoleResource;
import com.wb.permission.pojo.WbUserRole;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangxh on 2022/4/29.
 */
@Service
public class RoleByRedisService {
    @Autowired
    private IRedisService redisService;
    @Autowired
    private DefaultBussniessImpl bizDao;

    /**
     * 记录每个登录用户不可访问的菜单
     * 存储模式：userName->,菜单id1,菜单id2,菜单id3,
     */
    public void putRole(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request){

        String sql = "select wu.USER_NAME USER_ID, wur.ROLE_ID from wb_user wu ,wb_user_role wur where wu.USER_ID =wur.USER_ID ";
        String userId = jsonObject.has("userId")?jsonObject.getString("userId"):null;
        if (StrUtil.isNotEmpty(userId)){
            sql += " and wu.USER_name='"+userId+"'";
        }
        //List<WbUser> users = bizDao.findAll(WbUser.class);
        //每个用户拥有的角色
        List<WbUserRole> userRoles = bizDao.list(sql, WbUserRole.class);

        /*userRoles.forEach(x-> {
            if(StrUtil.isEmpty(x.getTenancyId())){
                x.setTenancyId("default");
            }
        });
        Map<String, List<WbUserRole>> roleMap = userRoles.stream().collect(Collectors.groupingBy(WbUserRole::getTenancyId));
        */
        //List<WbRole> roles = bizDao.findAll(WbRole.class);
        //权限表
        List<WbRoleResource> roleResources = bizDao.findAll(WbRoleResource.class);
        //菜单表
        List<WbMenu> menus = bizDao.findAll(WbMenu.class);
        menus.removeIf(x->StrUtil.isEmpty(x.getMenuUrl()));
        Map<String, String> userMap = new HashMap<>();
        for (WbUserRole userRole : userRoles){
            String resourceId = userMap.getOrDefault(userRole.getUserId(), ",");
            for (WbRoleResource resource : roleResources){
                if (ObjectUtil.equal(userRole.getRoleId(), resource.getRoleId())
                        && !resourceId.contains(","+resource.getMenuId()+",")){
                    resourceId = StrUtil.join(resourceId, resource.getMenuId(), ",");
                }
            }
            userMap.put(userRole.getUserId(), resourceId);
        }
        for (WbMenu menu : menus) {
            String menuUrl = menu.getMenuUrl();
            if (menuUrl.contains("m?xwl=")) {
                menuUrl = menuUrl.replace("m?xwl=", "");
            }
            if (!menuUrl.endsWith(".xwl")) {
                menuUrl += ".xwl";
            }
            menu.setMenuUrl(menuUrl);
        }
        //记录权限菜单允许访问的url
        for (Map.Entry<String, String> entry : userMap.entrySet()){
            String urls = ",", key = entry.getKey(), val = entry.getValue();
            for (WbMenu menu : menus){
                if (val.contains(","+menu.getMenuId()+",")){
                    urls = StrUtil.join(urls, menu.getMenuUrl(), ",");
                }
            }
            userMap.put(key, urls);
        }
        //记录权限菜单允许访问的url
        for (Map.Entry<String, String> entry : userMap.entrySet()){
            String urls = ",", key = entry.getKey(), val = entry.getValue();
            for (WbMenu menu : menus){
                //菜单url不在允许访问的url中，记录下来
                if (!val.contains(","+menu.getMenuUrl()+",")){
                    urls = StrUtil.join(urls, menu.getMenuUrl(), ",");
                }
            }
            userMap.put(key, urls);
        }

        for (Map.Entry<String, String> entry : userMap.entrySet()){
            redisService.putCustomizeKey("userRoles_"+entry.getKey(), entry.getValue());
        }


    }

    public boolean isRole(String userName, String url){
        String resourceUrl = redisService.getCustomizeKey("userRoles_"+userName);
        return !resourceUrl.contains(","+url+",");
    }
}
