package com.mortals.xhx.base.framework.config;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;

import cn.hutool.setting.Setting;
import cn.hutool.setting.SettingUtil;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.mortals.framework.util.StringUtils;

@Configuration
@CommonsLog
public class InterceptorConfig {
    /**
     * cookie的密钥
     */
    @Value("${cookie.key}")
    private String securityKey;

    /**
     * 不需要登录的URL地址，多个用逗号分隔
     */
    @Value("${application.auth.unloginUrl}")
    private String uncheckLoginUrl;

    /**
     * 不需要鉴权的URL地址，多个用逗号分隔
     */
    @Value("${application.auth.uncheckUrl}")
    private String uncheckAuthUrl;
    @Setter
    @Getter
    private Setting baseInfoSetting;
    @Setter
    @Getter
    private Setting sqclInfoSetting;

    private Set<String> uncheckLoginUrls = new HashSet<>();

    private Set<String> uncheckAuthUrls = new HashSet<>();
    /**
     * 有后缀占位符的不检验地址，如/spi/user/*
     */
    private Set<String> uncheckAuthUrlsSuffix = new HashSet<>();

    public String getSecurityKey() {
        return securityKey;
    }

    public Set<String> getUncheckLoginUrls() {
        return uncheckLoginUrls;
    }

    public Set<String> getUncheckAuthUrls() {
        return uncheckAuthUrls;
    }

    /**
     * 校验地址是否需要权限
     *
     * @param url
     * @return true：需要，false：不需要
     */
    public boolean needCheckAuth(String url) {
        if (uncheckAuthUrls.contains(url)) {
            return false;
        }
        for (String regexUrl : uncheckAuthUrlsSuffix) {// 支持*结尾
            if (url.startsWith(regexUrl)) {
                return false;
            }
        }
        return true;
    }

    @PostConstruct
    public void convert() {
        uncheckLoginUrls.clear();
        uncheckLoginUrls.addAll(StringUtils.converStr2Set(uncheckLoginUrl));

        uncheckAuthUrls.clear();
        uncheckAuthUrls.addAll(StringUtils.converStr2Set(uncheckAuthUrl));

        uncheckAuthUrlsSuffix.clear();
        for (String url : uncheckAuthUrls) {
            int index = url.indexOf("*");// 支持*结尾
            if (index != -1) {
                uncheckAuthUrlsSuffix.add(url.substring(0, index));
            }
        }


        //加载配置文件
        Setting baseinfo = SettingUtil.get("baseinfo");
        this.setBaseInfoSetting(baseinfo);
       // log.info("baseinfo:"+ JSON.toJSONString(baseinfo));

        Setting sqclinfo = SettingUtil.get("sqclinfo");
        this.setSqclInfoSetting(sqclinfo);

    }

}
