package weaver.interfaces.htsc.wpscenter.utils;

import net.sf.json.JSONObject;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class TokenUtil {
    private Logger log = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 接口权限范围 scope 预览
     */
    public static final String SCOPE_FILE_PREVIEW = "file_preview";

    /**
     * 接口权限范围 scope 编辑
     */
    public static final String SCOPE_FILE_EDIT = "file_edit";

    /**
     * 接口权限范围 scope 文档格式处理
     */
    public static final String SCOPE_FILE_FORMAT_CONTROL = "file_format_control";

    /**
     * 权限数据分隔符号
     */
    public static final String SCOPE_SEPARATOR = ",";

    /**
     * 接口权限范围默认值，全部权限 scope
     */
    public static final String SCOPE_DEFAULT = "file_preview,file_edit,file_format_control";

    public Logger getLog() {
        return log;
    }

    public TokenUtil setLog(Logger log) {
        this.log = log;
        return this;
    }

    /**
     * 获取默认的token值
     * @param user
     * @return
     */
    public String getToken(User user) {
        String scope = SCOPE_DEFAULT;
        Map<String, String> result = getToken(user, scope);
        return Tools.null2String(result.get("app_token"));
    }

    /**
     * 获取编辑服务的token值
     * @param user
     * @return
     */
    public String getEditToken(User user) {
        String scope = SCOPE_FILE_EDIT;
        Map<String, String> result = getToken(user, scope);
        return Tools.null2String(result.get("app_token"));
    }

    /**
     * 获取预览服务的token值
     * @param user
     * @return
     */
    public String getPreviewToken(User user) {
        String scope = SCOPE_FILE_PREVIEW;
        Map<String, String> result = getToken(user, scope);
        return Tools.null2String(result.get("app_token"));
    }

    /**
     * 获取文档处理的token值
     * @param user
     * @return
     */
    public String getFileFormatToken(User user) {
        String scope = SCOPE_FILE_FORMAT_CONTROL;
        Map<String, String> result = getToken(user, scope);
        return Tools.null2String(result.get("app_token"));
    }

    public Map<String, String> getToken(User user, String scope) {
        // http://10.10.27.103/open/auth/v1/app/inscope/token?app_id=AK20210414APYJFW&scope=file_preview,file_edit,file_format_control
        String tokenApi = Config.getAuthv1AppInscopeToken();
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> headers = new HashMap<String, String>();

        StringBuilder tokenRequestUrl = new StringBuilder(tokenApi);
        tokenRequestUrl.append("?app_id=").append(Config.getWpsDocCenterAppid())
                .append("&scope=").append(scope);

        if(Config.isLogInfo()) {
            log.info("user:[" + (null == user ? "-1" : user.getUID()) + "],tokenRequestUrl:" + tokenRequestUrl);
        }

        HttpUtil httpUtil = new HttpUtil(user);
        try {
            JSONObject responseJson = httpUtil.get(tokenRequestUrl.toString(), headers);

            if(Config.isLogInfo()) {
                log.info("user:[" + (null == user ? "-1" : user.getUID()) + "],responseJson:" + responseJson.toString());
            }

            String resultCode = Tools.getJsonData(responseJson, "code");
            result.put("code", resultCode);
            if("0".equals(resultCode)){
                JSONObject tokenJson = responseJson.getJSONObject("token");

                String app_token = Tools.getJsonData(tokenJson, "app_token");
                String expires_in = Tools.getJsonData(tokenJson, "expires_in");

                result.put("app_token", app_token);
                result.put("expires_in", expires_in);

            } else if(Tools.isEmptyOrNull(resultCode)){
                result.put("code", "-1");
                // 125325 未知的错误
                result.put("msg", SystemEnv.getHtmlLabelName(125325, Tools.getUserLanguageid(user)));
            } else {
                result.put("reponse", responseJson.toString());
                if(responseJson.containsKey("msg")) {
                    result.put("msg", Tools.getJsonData(responseJson, "msg"));
                } else {
                    // TODO 多语言处理 获取编辑地址失败
                    result.put("msg", "获取编辑地址失败");
                }
            }
        } catch (Exception e) {
            log.info("user:[" + (null == user ? "-1" : user.getUID()) + "],GET Token Exception:" + e.getMessage());
            log.error(e);
        }

        return result;
    }
}
