package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.session.UserElement;
import com.community.huiju.common.BaseController;
import com.community.huiju.constant.Header;
import com.community.huiju.constant.RequestURI;
import com.community.huiju.constant.Status;
import com.community.huiju.dao.*;
import com.community.huiju.dto.MenuDTO;
import com.community.huiju.dto.RoleDTO;
import com.community.huiju.model.*;
import com.community.huiju.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 角色业务
 *
 * @author weiximei
 */
@Service("iRoleService")
@Slf4j
public class RoleService  extends BaseController implements IRoleService {

    @Autowired
    private ToSysMenuMapper toSysMenuMapper;

    @Autowired
    private ToSysRoleMapper toSysRoleMapper;

    @Autowired
    private ToSysRoleMenuMapper toSysRoleMenuMapper;

    @Autowired
    private ToSysUserRoleMapper toSysUserRoleMapper;

    @Autowired
    private ToUserMapper toUserMapper;

    @Autowired
    private TpSysRoleMapper tpSysRoleMapper;

    @Autowired
    private TpSysMenuMapper tpSysMenuMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public List<RoleDTO> getWebOperateUserRoleByUserId(Integer userId) {
        List<ToSysRole> roles = toSysRoleMapper.selectRoleByUserId(userId);
        List<RoleDTO> roleDTOList = roles.stream()
                .map(e-> new RoleDTO(e.getId(),e.getRoleName()))
                .collect(Collectors.toList());
        return roleDTOList;
    }

    @Override
    public List<RoleDTO> getWebPropertyUserRoleUserId(Integer userId) {
        List<TpSysRole> roles = tpSysRoleMapper.selectRoleByUserId(userId);
        List<RoleDTO> roleDTOList = roles.stream()
                .map(e-> new RoleDTO(e.getId(),e.getRoleName()))
                .collect(Collectors.toList());
        return roleDTOList;
    }

    @Override
    public List<RoleDTO> getAppUserRoleByUserId(Integer userId) {
        List<TaSysRole> roles = taSysRoleMapper.selectRoleByUserId(userId);
        List<RoleDTO> roleDTOList = roles.stream()
                .map(e-> new RoleDTO(e.getId(),e.getRoleName()))
                .collect(Collectors.toList());
        return roleDTOList;
    }

    @Override
    public List<MenuDTO> getWebOperateMenuUrlByRoleId(Integer roleId) {
        List<ToSysMenu> toSysMenus = toSysMenuMapper.selectByRoleId(roleId);
        List<MenuDTO> menuList = toSysMenus.stream().map(e -> new MenuDTO(e.getMenuUrl())).collect(Collectors.toList());
        return menuList;
    }

    @Override
    public List<MenuDTO> getWebPropertyMenuUrlRoleId(Integer roleId) {
        List<TpSysMenu> toSysMenus = tpSysMenuMapper.selectByRoleId(roleId);
        List<MenuDTO> menuList = toSysMenus.stream().map(e -> new MenuDTO(e.getMenuUrl())).collect(Collectors.toList());
        return menuList;
    }

    @Override
    public List<MenuDTO> getAppMenuUrlByRoleId(Integer roleId) {
        return null;
    }

    @Override
    public boolean hasPermission(HttpServletRequest request) {
        boolean hasPermission = false;
        // 根据URL判断是访问哪一个端
        String requestURI = request.getRequestURI();
        String token = request.getHeader(Header.REQUEST_X_AUTH_TOKEN.getValue());
        log.info("获取的token: {}", token);

        if (antPathMatcher.match(RequestURI.APP_API.getUrl(), requestURI)) {
            UserElement appElement = (UserElement) request.getSession().getAttribute(Constant.APP_USER_SESSION);
            if (null != appElement) {
                // 这里先默认放行
                hasPermission = true;
            }

        } else if (antPathMatcher.match(RequestURI.OPERATE_API.getUrl(), requestURI)) {
            UserElement webOperateElement = (UserElement) request.getSession().getAttribute(Constant.WEB_USER_SESSION);
            if (null != webOperateElement) {
                List<RoleDTO> roleDTOS = getWebOperateUserRoleByUserId(webOperateElement.getId());
                hasPermission = hasMenuUrl(roleDTOS, RequestURI.OPERATE_API.getUrl(), requestURI);
            }
        } else if (antPathMatcher.match(RequestURI.PROPERTY_API.getUrl(), requestURI)) {
            UserElement webPropertyElement = (UserElement) request.getSession().getAttribute(Constant.WEB_USER_SESSION);
            if (null != webPropertyElement) {
                List<RoleDTO> roleDTOS = getWebPropertyUserRoleUserId(webPropertyElement.getId());
                hasPermission = hasMenuUrl(roleDTOS, RequestURI.PROPERTY_API.getUrl(), requestURI);
            }
        }

        return hasPermission;
    }

    /**
     * 判断是否有这个 url
     * @param roleDTOS 角色集合
     * @param apiUrl 是 物业端/运营端/APP端 {@link RequestURI}
     * @param requestURI 请求的url
     * @return
     */
    private boolean hasMenuUrl(List<RoleDTO> roleDTOS, String apiUrl, String requestURI){

        boolean hasMenuUrl = false;
        for (RoleDTO role : roleDTOS) {
            // 是 物业端/运营端/APP端
            List<MenuDTO> urlList = antPathMatcher.match(RequestURI.OPERATE_API.getUrl(), requestURI)
                    ? getWebOperateMenuUrlByRoleId(role.getId()) : antPathMatcher.match(RequestURI.PROPERTY_API.getUrl(), requestURI)
                    ? getWebPropertyMenuUrlRoleId(role.getId())  : antPathMatcher.match(RequestURI.APP_API.getUrl(), requestURI)
                    ? Collections.EMPTY_LIST : Collections.EMPTY_LIST;

            for (MenuDTO menu : urlList) {
                if (antPathMatcher.match(menu.getMenuUrl(), requestURI)) {
                    hasMenuUrl = true;
                }
            }

        }

        return hasMenuUrl;
    }

}
