package com.enterprise.manage.core.freemarker;

import com.enterprise.manage.modules.system.domain.po.Menu;
import com.enterprise.manage.modules.system.domain.po.User;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Permission Tag (权限标签)
 *
 * @author PeiZhi Guo
 * 2021-3-22 15:02
 */
@Component
public abstract class PermissionTag extends SecureTag {
    private String getName(Map params) {
        return super.getParam(params, "name");
    }

    @Override
    public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
        String p = getName(params);

        boolean show = showTagBody(p);
        if (show) {
            super.renderBody(env, body);
        }
    }

    @Override
    protected void verifyParameters(Map params) throws TemplateException {
        String permission = getName(params);

        if (permission == null || permission.length() == 0) {
            throw new TemplateModelException("The 'name' tag attribute must be set.");
        }
    }

    protected boolean isPermitted(String p) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        for (Menu sysMenu : user.getMenuList()) {
            if (p.equals(sysMenu.getCode())) {
                return true;
            }
        }
        return false;
    }

    protected abstract boolean showTagBody(String p);
}
