package com.chexiang.myhome.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * des:常用方法集合
 * Created by liyayu on 2016/4/5.
 */
public class NormalUtil {
    /**
     * 判断String是否空
     */
    public static boolean isNull(String s) {
//        if (null == result || "".equals(result)) {
//            return true;
//        } else {
//            return false;
//        }
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }

    /**
     * 判断是否相等
     */
    public static boolean isEquals(String str, String str2) {
        return str.equals(str2);
    }

    /**
     * 字符串进行加密
     */
    public static String encryptionParams(String params) throws NoSuchAlgorithmException {
        String signature = null;
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(params.getBytes());
        byte[] temp = md5.digest();
//        signature = hexDigits(temp).toUpperCase();
        signature = toHex(temp).toUpperCase();
        return signature;
    }

    /**
     * 转换大写
     */
    public static String toHex(byte hash[]) {
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if (((int) hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String SignatureHexMd5(String strObj) {
        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            byte[] arr = md.digest(strObj.getBytes());
            for (int i = 0; i < arr.length; ++i) {
                sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
                        3));
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 验证是否是中文
     *
     * @param str
     * @return
     */
    public static boolean isChinese(String str) {
        String check = "^[\u4e00-\u9fa5]+$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * dp转换为px
     *
     * @param context
     * @param dp
     * @return
     */
    public static int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * px转化为dp
     *
     * @param context
     * @param px
     * @return
     */
    public static int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 判断邮箱格式
     */
    public static boolean isEmail(String str) {
        String check = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断是否存在SD卡
     *
     * @return
     */
    public static boolean hasSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }

    /**
     * 判断是否是正确的手机号
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "^1\\d{10}$";
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 验证手机电话号码
     * <p>
     * 手机号码 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通:130,131,132,152,155,156,185,186 电信:133,1349,153,180,189
     *
     * @return
     */
    public static boolean checkMobilephone(String mobilephone) {
        String cm = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";// 中国移动正则
        String cu = "^1(3[0-2]|5[256]|8[56])\\d{8}$";// 中国联通正则
        String ct = "^1((33|53|8[09])[0-9]|349)\\d{7}$";// 中国电信正则
        if (Pattern.matches(cm, mobilephone) || Pattern.matches(cu, mobilephone) || Pattern.matches(ct, mobilephone)) {
            return true;
        }
        return false;
    }

    /**
     * 获得网络连接是否可用
     *
     * @return
     */
    public static boolean getNetWorkStatus(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return (info != null && info.isAvailable());
    }

    /**
     * 获取当前时间戳
     */
    public static String nowDateToMs() {
        String nowTime = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        nowTime = formatter.format(curDate);
        return nowTime;
    }

    /**
     * 获取当前时间戳
     */
    public static String getNowString() {
        String nowTime = null;
        SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        nowTime = formatter.format(curDate);
        return nowTime;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static String msToDate(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);
        String time = f.format(date);
        return time;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static String msToDate2(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = f.format(date);
        return time;
    }

    /**
     * 把毫秒格式化成时分输出
     *
     * @param ms
     * @throws Exception
     */
    public static String msToTime(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("HH小时mm分钟", Locale.CHINA);
        String time = f.format(date);
        return time;
    }

    /**
     * 4舍五入
     */
    public static int floatToInt(float f) {
        int i = 0;
        if (f > 0) //正数
            i = (int) (f * 10 + 5) / 10;
        else if (f < 0) //负数
            i = (int) (f * 10 - 5) / 10;
        else i = 0;

        return i;
    }

    /**
     * 4舍五入
     */
    public static String meterToKm(Long i) {
        double d = i / 1000d;
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(d);
    }

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    public static String date2date(String date) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date d = null;
        long l = 0;
        try {
            d = dft.parse(date);
            l = d.getTime();
        } catch (ParseException e) {

            e.printStackTrace();
        }

        Date new_date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("MM月dd日 \nHH:mm ", Locale.CHINA);
        String time = f.format(new_date);
        return time;
    }

    public static String date2flydate(String date) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date d = null;
        long l = 0;
        try {
            d = dft.parse(date);
            l = d.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Date new_date = new Date(l + 1000 * 60 * 15);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = f.format(new_date);
        return time;
    }

    public static String SetPhoneStar(String pNumber) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(pNumber) && pNumber.length() > 6) {

            for (int i = 0; i < pNumber.length(); i++) {
                char c = pNumber.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    public static void switchKeybord(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //保留两位小数点
    public static String keep2point(double d) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(d);
    }

    /*
     * 保留两位小数
     */
    public static String keep2Decimal(String string) {
        if (null != string && !"".equals(string)) {
            //构造以字符串内容为值的BigDecimal类型的变量bd
            BigDecimal bd = new BigDecimal(string);
            //设置小数位数,第一个变量是小数位数,第二个变量是取舍方法(四舍五入)
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            return bd.toString();
        }
        return "";
    }

    public static String getVersionName(Context context) {
        String versionName = null;
        try {
            // 获取软件版本名称,对应AndroidManifest.xml下android:versionCode
            versionName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static Boolean hasNew(String get, String now) {
        String s1 = get.replace(".", "");
        String s2 = now.replace(".", "");
        int i1 = 0;
        int i2 = 0;
        try {
            i1 = Integer.parseInt(s1);
            i2 = Integer.parseInt(s2);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return i1 > i2;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static String msToYear(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String time = f.format(date);
//        int h = 0;
//        try {
//            h = Integer.parseInt(time);
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
        return time;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static int msToHour(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("HH", Locale.CHINA);
        String time = f.format(date);
        int h = 0;
        try {
            h = Integer.parseInt(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return h;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static int msToMinute(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("mm", Locale.CHINA);
        String time = f.format(date);
        int h = 0;
        try {
            h = Integer.parseInt(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return h;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @throws Exception
     */
    public static String toCurrentDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String time = f.format(date);
        return time;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param ms
     * @throws Exception
     */
    public static String msToData(long ms) {
        long l = ms;
        Date date = new Date(l);
        SimpleDateFormat f = new SimpleDateFormat("MM月dd日", Locale.CHINA);
        String time = f.format(date);
        return time;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param data
     * @throws Exception
     */
    public static long dataToMs(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        long millionSeconds = 0;//毫秒
        try {
            millionSeconds = sdf.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return millionSeconds;
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @param data
     * @throws Exception
     */
    public static String dataTodata2(String data) {
        String year = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        year = formatter.format(curDate);
        String month = data.substring(0, 2);
        String day = data.substring(3, 5);
        return year + "-" + month + "-" + day;
    }

    public static String getLocalIpAddressV4() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    //if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress()))  //这里做了一步IPv4的判定
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        ip = inetAddress.getHostAddress().toString();
                        return ip;
                    }
                }
            }
        } catch (SocketException e) {
//            Log.i("SocketException--->", ""+e.getLocalizedMessage());
            return "ip is error";
        }
        return ip;
    }

    public static String GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        HttpURLConnection httpConnection = null;
        try {
            infoUrl = new URL("http://www.cmyip.com/");
//			infoUrl = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=myip");
            URLConnection connection = infoUrl.openConnection();
            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();
                String line = null;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("php?ip=");
                if (start == 0) {
                    line = NormalUtil.getLocalIpAddressV4();
                } else {
                    int end = strber.indexOf("\"", start + 1);
                    line = strber.substring(start + 7, end);
                }
//				line = "jahsdbfljhasbdlgjhbalekrjaljbrgakehj";
//                sharedPreferences1.edit().putString("netip", line).commit();
                return line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

    public static String getDate(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return sdf.format(new Date(timestamp * 1000));
    }

    /**
     * 把毫秒格式化成日期输出
     *
     * @throws Exception
     */
    public static String sToRestTime(long s) {
        s = (long) s / 1000;
        int hour = 0;
        int min = 0;
        String time = "";
        if (s >= 60 * 60) {
            hour = (int) s / 3600;
            min = (int) (s - hour * 3600) / 60;
            time = hour + "小时" + min + "分钟";
        } else {
            min = (int) s / 60;
            time = min + "分钟";
        }
        return time;
    }

    /*
    * 日历控件日期转化格式
    * */
    public static String generateCalenderData(int year, int monthOfYear, int dayOfMonth) {
        int m = monthOfYear + 1;
        String mou = "", day = "";
        if (m < 10) {
            mou = "0";
        }
        if (dayOfMonth < 10) {
            day = "0";
        }
        String ymd = year + "-" + mou + m + "-" + day + dayOfMonth;
//        String ymd = year+"/"+(monthOfYear+1)+"/"+dayOfMonth;
        return ymd;
    }
    /*
     * 日历控件日期转化格式
     * */
    public static String generatePickedData(String year, String monthOfYear, String dayOfMonth) {

        return year + "-" + monthOfYear + "-" + dayOfMonth;
    }
    /*
    * 复制文本
    * */
    public static void doCopy(Context context, String s) {
        //获取剪贴板管理器:
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", s);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.showToast(context, "已成功复制到剪贴板");
    }

    public static int editToInt(TextView editText) {
        String s = editText.getText().toString().trim();
        if (s.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(s);
        }
    }

    public static int stringToInt(String s) {
        if (StringUtils.isEmpty(s)) {
            return 0;
        } else {
            return Integer.parseInt(s);
        }
    }
//    public static double moneyEditToDouble(EditText editText) {
//        NormalUtil.keepEditTwoPoint(editText);
//        String s = editText.getText().toString().trim();
//        if (StringUtils.isEmpty(s)) {
//            return 0;
//        } else {
//            return Double.parseDouble(s);
//        }
//    }
    public static double editToDouble(TextView editText) {
        String s = editText.getText().toString().trim();
        if (StringUtils.isEmpty(s)) {
            return 0;
        } else {
            return Double.parseDouble(s);
        }
    }
    public static double stringToDouble(String s) {
        if (StringUtils.isEmpty(s)) {
            return 0;
        } else {
            return Double.parseDouble(s);
        }
    }
    //设置金额输入小数点后2位有效
    public static void keepEditTwoPoint(EditText editText) {
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int mlength = dest.toString().substring(index).length();
                    if (mlength == 3) {
                        return "";
                    }
                }
                return null;
            }
        }});
    }

    public static void setDrawleft(Context context,TextView view, int id) {
        Drawable drawable_n = context.getResources().getDrawable(id);
        if (drawable_n !=null){
            drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());  //此为必须写的
            view.setCompoundDrawables(drawable_n, null, null, null);
        }
    }

    // 仅包含中文、数字和英文
    public static boolean isNormalString(String s) {
        return Pattern.compile("^[\\u4E00-\\u9FA5A-Za-z0-9]+$").matcher(s).matches();
    }
}