/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sifang.modules.sys.common.utils;

import com.jfinal.kit.StrKit;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 * @version 2019-11-15
 */
public class StringUtil extends org.apache.commons.lang3.StringUtils {

    public static String lowerFirst(String str){
        if(StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0,1).toLowerCase() + str.substring(1);
        }
    }

    public static String upperFirst(String str){
        if(StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0,1).toUpperCase() + str.substring(1);
        }
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)){
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * @param str 目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 缩略字符串（替换html）
     * @param str 目标字符串
     * @param length 截取长度
     * @return
     */
    public static String rabbr(String str, int length) {
        return abbr(replaceHtml(str), length);
    }


    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val){
        if (val == null){
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val){
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val){
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val){
        return toLong(val).intValue();
    }

    /**
     * 获得i18n字符串
     */
    public static String getMessage(String code, Object[] args) {
        LocaleResolver localLocaleResolver = SpringContextHolder.getBean(LocaleResolver.class);
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Locale localLocale = localLocaleResolver.resolveLocale(request);
        return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request){
        String remoteAddr = request.getHeader("X-Real-IP");
        if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        }else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        }else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 将字符串list集合组合成IN操作符对应的值。
     * @param strings 字符串集合
     * @return 返回生成的IN操作符的值，该值可能为empty
     * */
    public static String arrangeString2INValue(List<String> strings)
    {
        String in = "";
        if(strings != null)
        {
            for(String string : strings)
            {
                if(in.isEmpty())
                    in += "'" + string + "'";
                else
                    in += ",'" + string + "'";
            }
        }
        return in;
    }

    public static String joinNonBlank(String... val) {
        StringBuilder sb = new StringBuilder();
        for (String v : val) {
            if (StringUtils.isNotBlank(v)) {
                sb.append(v);
            }
        }
        return sb.toString();
    }

    public static String joinInSql(String[] els) {
        if (els == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String el : els) {
            if(isNotBlank(el)) {
                sb.append("'").append(el).append("'");
                sb.append(",");
            }
        }
        String ret = sb.toString();
        if (ret.endsWith(",")) {
            ret = ret.substring(0, ret.length() - 1);
        }
        return ret;
    }

    public static String joinInSql(List<String> els) {
        if (els == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String el : els) {
            if(isNotBlank(el)) {
                sb.append("'").append(el).append("'");
                sb.append(",");
            }
        }
        String ret = sb.toString();
        if (ret.endsWith(",")) {
            ret = ret.substring(0, ret.length() - 1);
        }
        return ret;
    }

    public static String convertBackSlant(String str){
        return str.replaceAll("\\\\", "/");
    }

    public static String appendMultiString(String oldRelate, String... newRelate) {
        StringBuilder builder = new StringBuilder();
        for (String relate : newRelate) {
            builder.append(",").append(relate);
        }
        if (StrKit.isBlank(oldRelate)) {
            return builder.toString().substring(1);
        }
        return oldRelate + builder.toString();
    }

    public static boolean checkParamValid(Object param) {
        String str = (String) param;
        return str != null && !StrKit.isBlank(str.trim());
    }

    public static boolean equalsAny(String val, String... str) {
        if (str.length == 0) {
            return true;
        }
        if (val == null) {
            throw new IllegalArgumentException("invalid param val");
        }
        for (String s : str) {
            if (val.equals(s)) {
                return true;
            }
        }
        return false;
    }
}
