package com.ywt.service;


import com.ywt.core.MGRightTypeDef;
import com.ywt.core.utils.Checker;
import com.ywt.domain.entity.center.MGAdminsRepository;
import com.ywt.domain.entity.center.MgAdminMenusView;
import com.ywt.domain.entity.center.MgAdminRightView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class AuthService {

    @Autowired
    private MGAdminsRepository mgAdminsRepository;

    @Autowired
    private MgRightCacheService mgRightCacheService;

    @Autowired
    private UserService userService;

    /**
     * 判断是否有权限
     *
     * @param menuCode
     * @param rightCode
     * @param types     1 : 菜单；2 : 权限点, 4: 登录状态
     * @return
     */
    public boolean hasRight(String[] menuCode, String[] rightCode, int types) {

        int adminId = userService.getAdminId();
        List<MgAdminRightView> mgAdminRightViewList = mgRightCacheService.getRightListHigh();
        List<MgAdminMenusView> mgAdminMenusViewList = mgRightCacheService.getMenusListHigh();

        if ((types & MGRightTypeDef.Logined) == MGRightTypeDef.Logined) {
            return true;
        }

        // 判断权限点
        if (!Checker.isNone(rightCode) && ((types & MGRightTypeDef.Right) == MGRightTypeDef.Right)) {
            List<MgAdminRightView> rightViewList = mgAdminRightViewList.stream().filter(p -> p.getAdminId() == adminId).collect(Collectors.toList());
            for (String codeStr : rightCode) {
                MgAdminRightView reightView= rightViewList.stream().filter(p -> Checker.getStringValue(p.getRightCode()).equals(codeStr)).findFirst().orElse(null);
                if (reightView != null) {
                    return true;
                }
            }
            return false;
        }

        // 判断菜单点
        if (!Checker.isNone(menuCode) && ((types & MGRightTypeDef.Menu) == MGRightTypeDef.Menu)) {
            List<MgAdminMenusView> menusViewList = mgAdminMenusViewList.stream().filter(p -> p.getAdminId() == adminId).collect(Collectors.toList());
            for (String codeStr : menuCode) {
                MgAdminMenusView reightView= menusViewList.stream().filter(p -> Checker.getStringValue(p.getMenuCode()).equals(codeStr)).findFirst().orElse(null);
                if (reightView != null) {
                    return true;
                }
            }
            return false;
        }

        return true;
    }

}
