package com.weaver.seconddev.njwebservice.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Component
public class CommonUtils {

    private final static Logger log = LoggerFactory.getLogger(CommonUtils.class);

    public static JSONObject toJSON(String data){
        if(!StringUtils.isEmpty(data)){
            try {
                return JSONObject.parseObject(data);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return null;
    }

    public static Long getJSONLong(JSONObject json,String key){
        if(json != null && json.containsKey(key)){
            try {
                return json.getLong(key);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return null;
    }

    public static Integer getJSONInteger(JSONObject json,String key){
        if(json != null && json.containsKey(key)){
            try {
                return json.getInteger(key);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return -1;
    }

    public static String getJSONString(JSONObject json,String key){
        if(json != null && json.containsKey(key)){
            try {
                return null2String(json.getString(key));
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return "";
    }

    public static JSONObject getJSONObject(JSONObject json,String key){
        if(json != null && json.containsKey(key)){
            try {
                return json.getJSONObject(key);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return null;
    }

    public static JSONArray getJSONArray(JSONObject json, String key){
        if(json != null && json.containsKey(key)){
            try {
                return json.getJSONArray(key);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return null;
    }

    public static JSONObject getJSONObject(JSONArray json, int idx){
        if(json != null && json.size() > idx){
            try {
                return json.getJSONObject(idx);
            }catch (Throwable t){
                log.error(t.getMessage(),t);
            }
        }
        return null;
    }

    public static String mapToStrData(Map<String, Object> para){
        if(para != null) {
            return JSONObject.toJSON(para).toString();
        }
        return "";
    }

    public static void strToLongList(List<Long> list,String strs){
        strToLongList(list,strs,true);
    }

    public static void strToLongList(List<Long> list,String strs,boolean isDist){
        if(list == null){
            return;
        }
        if(StringUtils.isEmpty(strs)){
            return;
        }

        String[] strList = StringUtils.split(strs, ",");
        for(String str:strList){
            if(StringUtils.isEmpty(str)){
                continue;
            }

            long id = getLongValue(str);
            if(id > 0l && (isDist == false || !list.contains(id))){
                list.add(id);
            }
        }
    }

    public static long getLongValue(Object v){
        return getLongValue(null2String(v));
    }

    public static long getLongValue(String v) {
        return getLongValue(v, -1);
    }

    public static long getLongValue(String v, long def) {
        try {
            return Long.parseLong(v);
        } catch (Exception ex) {
            return def;
        }
    }

    public static int getIntValue(Object o){
        return getIntValue(null2String(o));
    }

    public static int getIntValue(String s){
        return getIntValue(s,-1);
    }

    public static int getIntValue(String s, int def){
        try {
            return NumberUtils.toInt(s);
        } catch (Exception ex) {
            return def;
        }

    }

    public static String null2String(Object s) {
        return s == null ? "" : s.toString();
    }

    public static String null2String(Object s, String def) {
        return s == null ? (def == null ? "" : def) : s.toString();
    }


    public static String stringReplace(String sou, String s1, String s2) {
        //int idx = sou.indexOf(s1);
        //if (idx < 0) {
        //    return sou;
        //}
        //return sou.substring(0, idx) + s2 + StringReplace(sou.substring(idx + s1.length()), s1, s2);
        sou = null2String(sou);
        s1 = null2String(s1);
        s2 = null2String(s2);
        try{
            sou = sou.replace(s1, s2);
        }catch(Exception e){
            //System.out.println(e);//将未知异常打印出来，便于检查错误。
        }
        return sou;
    }

    /**
     * 替换特殊字符
     *
     * @param s 要替换特殊的字符串
     * @return 替换完成的字符串
     */
    public static String toScreen(String s) {
        char c[] = s.toCharArray();
        char ch;
        int i = 0;
        StringBuffer buf = new StringBuffer();

        while (i < c.length) {
            ch = c[i++];

            if (ch == '\r')
                buf.append("");
            else if (ch == '\n')
                buf.append("");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

    /**
     * 替换特殊字符
     *
     * @param s 要替换特殊的字符串
     * @return 替换完成的字符串
     */
    public static String toExcel(String s) {
        if (s == null) return "";
        //因本方法会将字符串 &符号转换，故先将欧元符号转义符转换为其Unicode码
        s = s.replaceAll("&euro;", "\u20AC");
        String str = toScreen(s);
        str = stringReplace(str, "&ang;", "∠");
        str = stringReplace(str, "&phi;", "φ");
        str = stringReplace(str, "&quot;", "\"");
        str = stringReplace(str, "&nbsp", "%nbsp");
        //str=Util.StringReplace(str,"'","‘");
        str = stringReplace(str, "&lt;", "<");
        str = stringReplace(str, "&gt;", ">");
        str = stringReplace(str, "&dt;&at;", "<br>");
        str = stringReplace(str, "&", "&amp;");
        str = stringReplace(str, "<br>", "&dt;&at;");
        if ("&dt;&at;".equals(str)) {
            str = "";
        }
        //在方法最后，又将欧元符号置换为转义符
        str = str.replaceAll("\u20AC", "&euro;");
        return str;
    }

    public static String delHtml(final String inputString) {
        String htmlStr =  toExcel(inputString); // 含html标签的字符串

        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;

        try {
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

            String regEx_script = "<[/s]*?script[^>]*?>[/s/S]*?<[/s]*?//[/s]*?script[/s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[/s/S]*?<//script>

            p_script = java.util.regex.Pattern.compile(regEx_script, java.util.regex.Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_html = java.util.regex.Pattern.compile(regEx_html, java.util.regex.Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return htmlToTxt(textStr).trim();// 返回文本字符串
    }

    /**
     * 删除字符串中的html格式
     *
     * @param input
     * @return
     */
    public static String htmlToTxt(String input) {
        if (input == null || input.trim().equals("")) {
            return "";
        }
        // 去掉所有html元素,
        String str = input.replaceAll("<[a-zA-Z]+[1-9]?[^><]*>", "");
        return str;
    }


    //==new=

    public static int getIntValue(Object s, int def){
        return getIntValue(null2String(s));
    }

    public static List<Long> strToLongList(String strs){
        List<Long> list = new ArrayList<Long>();
        strToLongList(list,strs,true);
        return list;
    }


    public static int dateInterval(String fromdate, String todate) {
        Calendar fromcalendar = getCalendar(fromdate);
        Calendar tocalendar = getCalendar(todate);

        if (fromcalendar == null || tocalendar == null)
            return 0;

        return (int) ((tocalendar.getTimeInMillis() - fromcalendar.getTimeInMillis()) / 3600 / 24 / 1000);
    }

    /**
     * @param datetime - 给定的日期时间，格式为 '2004-05-12 12:00:23'  或者 '2004-05-12'
     * @return 返回给定日历， 如果格式不正确，返回null
     */
    public static Calendar getCalendar(String datetime) {
        int datetimelength = datetime.length() ;

        switch(datetimelength) {
            case 19 :
                return getCalendar(datetime , "yyyy'-'MM'-'dd' 'HH:mm:ss") ;
            case 10 :
                return getCalendar(datetime , "yyyy'-'MM'-'dd") ;
            default :
                return null ;
        }

    }


    /**
     * @param datetime - 给定的日期时间
     * @param formart - 给定的日期时间的格式
     * @return 返回给定日历， 如果格式不正确，返回null
     */
    public static Calendar getCalendar(String datetime, String formart) {
        SimpleDateFormat SDF = new SimpleDateFormat(formart) ;

        Calendar calendar = Calendar.getInstance() ;
        try {
            calendar.setTime(SDF.parse(datetime)) ;
        } catch (ParseException e) {
            return null ;
        }

        return calendar ;
    }

    /**
     * @return 返回当前时间字符，格式为 yyyy'-'MM'-'dd
     *
     * 返回当前时间字符，默认格式为yyyy'-'MM'-'dd
     *
     * 如 2004-09-07
     */
    public static String getCurrentDateString() {
        String timestrformart = "yyyy'-'MM'-'dd" ;
        SimpleDateFormat SDF = new SimpleDateFormat(timestrformart) ;
        Calendar calendar = Calendar.getInstance() ;

        return SDF.format(calendar.getTime()) ;
    }

    public static String getMessage(String msgMode,String key,String val){
        key = null2String(key).trim();
        val = null2String(val).trim();
        msgMode = null2String(msgMode).trim();
        if(!"".equals(msgMode) && !"".equals(key)) {
            msgMode = msgMode.replaceAll(key, val);
        }
        return msgMode;
    }

    public static List<Long> tranStrToLongList(Object idListObj){
        List<Long> docIds = new ArrayList<Long>();
        if(idListObj != null) {
            try {
                JSONArray idObjs = JSONArray.parseArray(null2String(idListObj));
                for (Object idObj : idObjs) {
                    long id = getLongValue(idObj);
                    if (id > 0l) {
                        docIds.add(id);
                    }
                }
            } catch (Exception e) {
                log.error("trans error :{}", idListObj);
                log.error(e.getMessage(), e);
            }
        }
        return docIds;
    }
}
