package com.yutou.bilibili.Tools;

import com.alibaba.fastjson.JSONArray;
import com.yutou.bilibili.Services.IUserService;
import com.yutou.bilibili.mybatis.dao.PermissionDao;
import com.yutou.bilibili.mybatis.model.Permission;
import com.yutou.bilibili.mybatis.model.PermissionExample;
import com.yutou.bilibili.mybatis.model.UUser;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class ServiceTools implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;
    @Resource
    IUserService userService;
    @Resource
    PermissionDao permissionDao;

    public static ServiceTools getInstance() {
        ServiceTools tools=new ServiceTools();
        tools.userService=getBean(IUserService.class);
        tools.permissionDao=getBean(PermissionDao.class);
        return tools;
    }


    public boolean auth(HttpServletRequest request, String uname, String path) {
        UUser user = userService.getUser(uname);
        String tmp = request.getRequestURI();
        String url = null;
        try {
            url = tmp.split(tmp.split("/")[tmp.split("/").length - 1])[0];
        } catch (Exception e) {
            com.yutou.bilibili.Tools.Log.e(e);
            com.yutou.bilibili.Tools.Log.i("无权限请求:" + tmp);
            return false;
        }
        JSONArray powers = JSONArray.parseArray(user.getPower());
        if (powers.toJavaList(Integer.class).contains(-1)) {
            return true;
        } else {
            PermissionExample pExample = new PermissionExample();
            pExample.createCriteria().andUrlEqualTo(url);
            List<Permission> permissions = permissionDao.selectByExample(pExample);
            if (permissions != null && permissions.size() > 0) {
                if (powers.toJavaList(Integer.class).contains(permissions.get(0).getId())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ServiceTools.applicationContext == null) {
            ServiceTools.applicationContext = applicationContext;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}
