package cn.muchinfo.rma.view.autoWidget.utils;

import android.content.Context;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * 工具类
 */
public class NumberUtils {

    /**
     * 汉字
     */
    public static String[] CN_CHARS = new String[]{"零", "一", "二", "三", "四",
            "五", "六", "七", "八", "九"};
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String roundNum(int string, int num) {
        return roundNum(String.valueOf(string), num);
    }

    public static String roundNum(double string, int num) {
        return roundNum(String.valueOf(string), num);
    }

    public static int power(int a, int b) {
        int power = 1;
        for (int c = 0; c < b; c++)
            power *= a;
        return power;
    }

    public static String getDisCount(String num){
        String str = "";
        if (num.contains("百")){
            str = "十";
        }else {
             if (num.startsWith("十")){
                 str = num.replace("十","一");
             }else {
                 str = num.replace("十","");
             }
        }
        return str;
    }


    /**
     * @param num 小数位数
     * @return
     */
    public static String getZeroPatternString(int num) {
        StringBuilder retString = new StringBuilder();
        double max = num > 8 ? 8 : num;// 最大就8位
        for (int i = 0; i < max + 1/*小数点钱也算一位，所以最终计算出来的需要加1*/; i++) {
            if (i == 1) {
                retString.append(".");
            }
            retString.append("0");
        }
        return retString.toString();
    }


    /**
     * double类型失真
     */
    public static String doubleDistortion(String value) {
        // 1.99999999999994
        // 2.00000000000002
        // 1.099999999998
        // 1.10000000000001
        // 处理以上4种异常失真 不管是哪种失真，用四舍五入的方式处理就OK了，
        String tem = roundNoNum(value, 8);// 把这个tem后面的0全部去掉就OK了，基本能解决，不管是数量还是价格，基本不可能出现7位小数位数
        if (tem.contains(".")) {
            tem = tem.replaceAll("0+?$", "");// 去掉尾部连续的0
            if (tem.endsWith(".")) {// 上面去掉结尾的0时，会出现 3.的情况，
                tem = tem.substring(0, tem.length() - 1);
            }
        }
        return tem;
    }


    /**
     * 四舍五入保留小数点后两位
     *
     * @param string
     * @param num    预留小数位
     * @return
     */
    public static String roundNoNum(String string, int num) {
        if ("".equals(string)) {
            return string;
        }
        if ("null".equals(string)) {
            return "0";
        }
        String s = getZeroPatternString(num);
        DecimalFormat decimalFormat = new DecimalFormat(s);
        return decimalFormat.format(Double.parseDouble(string));
    }


    public static String setScale(String string , int num){
        double f = Double.valueOf(string);
        BigDecimal b = new BigDecimal(f);
        double f1 = b.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(f1);
    }

    /**
     * 四舍五入保留小数点后两位
     *
     * @param string
     * @param num    预留小数位
     * @return
     */
    public static String roundNum(String string, int num) {
        if ("".equals(string)) {
            return string;
        }
        if (!isNumeric(string)) {
            return string;
        }

        String s = getZeroPatternString(num);
        DecimalFormat decimalFormat = new DecimalFormat(s);
        return decimalFormat.format(Double.parseDouble(string));
    }

    public static String getDecimalPlace(int place) {
        if (place == 1) {
            return "999999999.9";
        } else if (place == 2) {
            return "999999999.99";
        } else if (place == 3) {
            return "999999999.999";
        } else if (place == 4) {
            return "999999999.9999";
        } else if (place == 5) {
            return "999999999.99999";
        } else if (place == 6) {
            return "999999999.999999";
        } else if (place == 7) {
            return "999999999.9999999";
        } else {
            return "999999999";
        }
    }

    /**
     * 四舍五入保留小数点后两位
     *
     * @param string
     * @param num    预留小数位
     * @return
     */
    public static String roundDownNum(String string, int num) {
        if ("".equals(string)) {
            return string;
        }
        if (!isNumeric(string)) {
            return string;
        }

        String s = getZeroPatternString(num);
        DecimalFormat decimalFormat = new DecimalFormat(s);
        decimalFormat.setRoundingMode(RoundingMode.DOWN);
        return decimalFormat.format(Double.parseDouble(string));
    }

    /**
     * 将金额数字格式化
     */
    public static String formatSum(String amount) {
        Double ss;
        DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
        String returnString;
        if (amount.isEmpty()) {
            returnString = "0.0";
        } else  if(Double.valueOf(amount) < 1){
            returnString = setScale(amount,2);
        }else {
            returnString = decimalFormat.format(Double.valueOf(amount));
        }

        return returnString;
    }

    /**
     * 根据 年、月 获取对应的月份 的 天数
     */
    public static int getDaysByYearMonth(int year, int month) {

        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }


    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.equals("") || str.equals("null");
    }

    /**
     * 获取当前的时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return sdf.format(new Date());
    }

    /**
     * 获取当前的时间 yyyy-MM-dd
     *
     * @return
     */
    public static String getCurrentTimeYMD() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        return sdf.format(new Date());
    }

    public static String getCurrentTimeyyyyMMdd() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
        return sdf.format(new Date());
    }

    public static boolean isIDCard(String idCard) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("(^\\d{18}$)|(^\\d{15}$)");
            Matcher m = p.matcher(idCard);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isTelePhoneNoLong(String telephone) {
        return telephone.length() >= 11 && telephone.length() <= 13;
    }


    public static boolean isTelePhoneNo(String telephone) {
        return telephone.length() >= 12 && telephone.length() <= 13;
//        boolean flag = false;
//        try {
//            Pattern p = Pattern.compile("^([0-9])?[0-9]{7,8}$");
//            Matcher m = p.matcher(telephone);
//            flag = m.matches();
//        } catch (Exception e) {
//            flag = false;
//        }
//        return flag;
    }

    public static String formatMoney(String value, String defaultValue) {
        if (value == null || value.isEmpty() || "null".equals(value)) return defaultValue;
        return roundNum(value, 2);
    }

    public static String formatMoney(String value) {
        return formatMoney(value, "--");
    }

    /**
     * 匹配是否为数字
     *
     * @param str 可能为中文，也可能是-19162431.1254，不使用BigDecimal的话，变成-1.91624311254E7
     * @return
     */
    public static boolean isNumeric(String str) {
        // 该正则表达式可以匹配所有的数字 包括负数
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }

        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 判断小数位
     *
     * @param param
     * @return
     */
    public static int checkDecimalPlace(String param) {
        if (param == null || param.equals("")) {
            return 0;
        }
        BigDecimal bd = new BigDecimal(param);
        String[] ss = bd.toString().split("\\.");
        if (ss.length <= 1) {
            return 0;
        }
        return ss[1].length();
    }


    public static String percentFormat(Double param) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);//设置保留小数位
        return nf.format(param);

    }

    public static String percentFormat(Double param, int digit) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(digit);//设置保留小数位
        return nf.format(param);

    }

//    /**
//     * 1、万以下的成交额直接显示（数值+股）；
//     * 2、万以上~亿以下的成交额单位显示为万股；
//     * 3、亿以上~万亿以下的成交额单位显示为亿股；
//     * 4、万亿以上的交易额单位显示为万亿股
//     *
//     * @param volume
//     * @return
//     */
//    public static String volumeShort(String volume, boolean isFuture) {
////        100000000
//        if (volume == null || "".equals(volume) || !WordUtil.isNumber(volume)) {
//            return volume;
//        }
//        long wy = 1000000000000L;
//        long yy = 100000000L;
//        long yw = 10000L;
//        double _volume = Double.parseDouble(volume);
//        if (_volume >= wy) {// 大于万亿
//            return Utils.roundNum(_volume / wy, 2) +
//                    (isFuture ? PolApplication.getInstance().getString(R.string.wy) : PolApplication.getInstance().getString(R.string.wyg));
//        } else if (_volume >= yy && _volume < wy) {// 大於 yy 小于 wy
//            return Utils.roundNum(_volume / yy, 2) +
//                    (isFuture ? PolApplication.getInstance().getString(R.string.yy) : PolApplication.getInstance().getString(R.string.yyg));
//        } else if (_volume >= yw && _volume < yy) {// 大于万 小于亿
//            return Utils.roundNum(_volume / yw, 2) +
//                    (isFuture ? PolApplication.getInstance().getString(R.string.w) : PolApplication.getInstance().getString(R.string.wg));
//        }
//        return volume + (isFuture ? "" : PolApplication.getInstance().getString(R.string.mtp_g));
//    }

//    /**
//     * 1、万以下的成交额直接显示（数值）；
//     * 2、万以上~亿以下的成交额单位显示为万；
//     * 3、亿以上~万亿以下的成交额单位显示为亿；
//     * 4、万亿以上的交易额单位显示为万亿
//     *
//     * @param turnover
//     * @return
//     */
//    public static String turnoverShort(String turnover) {
//        if (turnover == null || "".equals(turnover) || !WordUtil.isNumber(turnover)) {
//            return turnover;
//        }
//        long wy = 1000000000000L;
//        long yy = 100000000L;
//        long yw = 10000L;
//        long mw = 1000L;
//        double _volume = Double.parseDouble(turnover);
//        if (_volume >= wy) {// 大于万亿
//            return Utils.roundNum(_volume / wy, 2) + PolApplication.getInstance().getString(R.string.wy);
//        } else if (_volume >= yy && _volume < wy) {// 大於 yy 小于 wy
//            return Utils.roundNum(_volume / yy, 2) + PolApplication.getInstance().getString(R.string.yy);
//        } else if (_volume >= yw && _volume < yy) {// 大于万 小于亿
//            return Utils.roundNum(_volume / yw, 2) + PolApplication.getInstance().getString(R.string.w);
//        } else if (_volume < yw && _volume >= mw) {
//            return Utils.roundNum(_volume / yw, 2) + PolApplication.getInstance().getString(R.string.w);
//        }
//        return turnover;
//    }

    /**
     * 获取对应的currencyID的英文名称
     *
     * @param currencyID
     * @return
     */
    public static String getCurrencyName(int currencyID) {
        if (currencyID == 1) {
            return "CNY";
        } else if (currencyID == 2) {
            return "USD";
        } else if (currencyID == 4) {
            return "HKD";
        } else if (currencyID == 5) {
            return "EUR";
        } else if (currencyID == 6) {
            return "GBP";
        } else if (currencyID == 11) {
            return "NIS";
        }
        return "";
    }

    /**
     * 获取对应的currencyID的中文名称
     *
     * @param currencyID
     * @return
     */
    public static String getCurrencyChineseName(int currencyID) {
        if (currencyID == 1) {
            return "人民币";
        } else if (currencyID == 2) {
            return "美元";
        } else if (currencyID == 4) {
            return "港币";
        } else if (currencyID == 5) {
            return "欧元";
        } else if (currencyID == 6) {
            return "英镑";
        } else if (currencyID == 11) {
            return "新锡克尔";
        }
        return "";
    }

    public static String getCurrencyIDByName(String currencyName) {
        if ("人民币".equals(currencyName)) {
            return "CNY";
        } else if ("美元".equals(currencyName)) {
            return "USD";
        } else if ("港币".equals(currencyName)) {
            return "HKD";
        } else if ("欧元".equals(currencyName)) {
            return "EUR";
        } else if ("英镑".equals(currencyName)) {
            return "GBP";
        } else if ("新锡克尔".equals(currencyName)) {
            return "NIS";
        }
        return "";
    }

    public static String getNoScience(Double amount) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        return nf.format(amount);
    }

    /**
     *
     * @param noSavePass  保存密码为1，不保存密码为0
     * @param key
     * @param datas
     */
    public static void putHashMapData(int noSavePass, String key, Map<String, String> datas) {
        Map<String, String> oldMap = getHashMapData(key);
//        datas.putAll(oldMap);
        if (noSavePass == 1){
            oldMap.putAll(datas);
        }else {
            oldMap.putAll(datas);
//             for (String keys : datas.keySet()){//这点暂时这么做，有可能后面还会改回来
//                 if (!oldMap.containsKey(keys)){
//                     oldMap.putAll(datas);
//                 }
//             }
        }

        JSONArray mJsonArray = new JSONArray();
        Iterator<Map.Entry<String, String>> iterator = oldMap.entrySet().iterator();

        JSONObject object = new JSONObject();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {

            }
        }
        mJsonArray.put(object);

        SPUtils.getInstance().put(key,mJsonArray.toString());
    }

    public static Map<String, String> getHashMapData(String key) {

        Map<String, String> datas = new HashMap<>();

        String result = SPUtils.getInstance().getString(key);
        try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                JSONObject itemObject = array.getJSONObject(i);
                JSONArray names = itemObject.names();
                if (names != null) {
                    for (int j = 0; j < names.length(); j++) {
                        String name = names.getString(j);
                        String value = itemObject.getString(name);
                        datas.put(name, value);
                    }
                }
            }
        } catch (JSONException e) {

        }

        return datas;
    }

    public static void removeAccountHashMapData(String key, String account){
        Map<String, String> oldMap = getHashMapData(key);
        Map<String, String> newMap = new HashMap<>();
        for (String keys : oldMap.keySet()){
            if (!keys.equals(account)){
                newMap.put(keys,oldMap.get(keys));
            }
        }

        JSONArray mJsonArray = new JSONArray();
        Iterator<Map.Entry<String, String>> iterator = newMap.entrySet().iterator();

        JSONObject object = new JSONObject();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {

            }
        }
        mJsonArray.put(object);

        SPUtils.getInstance().put(key,mJsonArray.toString());
    }


    /**
     * 获取外网IP地址
     */
//    public static void GetNetIp(){
//        String IP = "";
//        URL infoUrl = null;
//        InputStream inStream = null;
//        try {
//            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
//            URLConnection connection = infoUrl.openConnection();
//            HttpURLConnection httpConnection = (HttpURLConnection) connection;
//            int responseCode = httpConnection.getResponseCode();
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                inStream = httpConnection.getInputStream();
//                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
//                StringBuilder strber = new StringBuilder();
//                while ((IP = reader.readLine()) != null)
//                    strber.append(IP + "\n");
//                inStream.close();
//                // 从反馈的结果中提取出IP地址
//                int start = strber.indexOf("{");
//                int end = strber.indexOf("}");
//                String json = strber.substring(start, end + 1);
//                if (json != null) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(json);
//                        IP = jsonObject.optString("cip");
//                        SPUtils.getInstance().put(Constent.COMMONIP,IP);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    public static String getCommonIp(){
//        String IP = "";
//        String saveIp = SPUtils.getInstance().getString(Constent.COMMONIP);
//        if (saveIp.isEmpty()){
//            IP = NetworkUtils.getIPAddress(true);
//        }else {
//            IP = saveIp;
//        }
//        return IP;
//    }


}
