package com.ifavine.pay.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;


import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class BaseUtil {

    public static boolean isDouble(String str) {

        // Pattern pattern = Pattern.compile("^[-//+]?//d+(//.//d*)?|//.//d+$");
        Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]{2})?$");

        return pattern.matcher(str).matches();

    }

    public static boolean isNull(String s) {
        if ("".equals(s) || null == s) {
            return true;
        }
        return false;
    }

    public static boolean isChineseChar(String str) {
        if (str == null) {
            return false;
        }
        boolean temp = false;
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            temp = true;
        }
        return temp;
    }

    public static boolean isLetterStart(String fstrData) {
        char c = fstrData.charAt(0);
        if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isNumeric(String str) {
        if (isNull(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     *
     * @Name:isEmail
     * @Description:检测字符串是否符合邮箱规范
     * @param:@param email
     * @param:@return
     * @return:boolean
     */
    /**
     * 正则表达式验证是否是邮箱地址
     */
    public static boolean matcherEmail(String email) {
//		String check = "^([a-z0-9A-Z]+[_-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        String check = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
//		String check = "[\\w!#$%&'*+//=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+//=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        boolean isMatched = matcher.matches();
        return isMatched;
    }

    public static void setImageViewSrc(ImageView v, int imageId) {
        v.setVisibility(View.VISIBLE);
        v.setImageResource(imageId);
    }

    public static int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * @Name:wineTime
     * @Description:醒酒时间计算
     * @param:@param min 自然醒酒时间（分钟）
     * @param:@return 转换后的醒酒时间（秒）
     * @return:int
     * @throw
     * @Author:zhouJQ
     * @date:2014-11-17
     */
    public static int getWineTime(int sec) {
        int t = 0;
        // if (sec <= 24) {// 当时间小于最小醒酒时间时
        // t = 24;
        // } else if (sec > 1440) {
        // t = 1440;
        // } else {
        t = sec;
        // }
        return t;
    }

    /*
     * @Name:calculationMachineProgress
     *
     * @Description:计算工作进度处理
     *
     * @param:@param setTime 总时间
     *
     * @param:@param useTime 剩余时间
     *
     * @param:@return 已完成百分比
     *
     * @throw
     *
     * @Author:lzg
     *
     * @date:2015-1-9
     */
    public static int calculationMachineProgress(int setTime, int useTime,
                                                 int machineState) {
        double workTimebuf;
        double TimeSecondBuf;
        double Result;

        if (setTime > 5000) {
            workTimebuf = setTime / 100;
            TimeSecondBuf = useTime / 100;
        } else if (setTime > 500) {
            workTimebuf = setTime / 10;
            TimeSecondBuf = useTime / 10;
        } else {
            workTimebuf = setTime;
            TimeSecondBuf = useTime;
        }
        Result = (workTimebuf - TimeSecondBuf) * 100 / workTimebuf;

        switch (machineState) {
            // 停止
            case 1:
                Result = 0;
                break;
            // 运行
            case 3:
                if (useTime == setTime)
                    Result = 0;
                break;
            // 运行结束
            case 5:
                if (useTime == setTime)
                    Result = 100;
                break;
        }

        if (Result < 0) {
            Result = 0;
        }
        return (int) Result;
    }

    /**
     * @Name:zoomImg
     * @Description: 缩放图片
     * @param:@param bm
     * @param:@param newWidth
     * @param:@param newHeight
     * @param:@return
     * @return:Bitmap
     * @throw
     * @Author:zhouJQ
     * @date:2014-11-25
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        // 按最大尺寸缩放
        if (scaleHeight > scaleWidth) {
            matrix.postScale(scaleHeight, scaleHeight);
        } else {
            matrix.postScale(scaleWidth, scaleWidth);
        }
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return newbm;
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "[^a-zA-Z0-9_!~@$%^&*]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }


    /**
     * 用来判断服务是否运行
     *
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        try {
            ActivityManager activityManager = (ActivityManager) mContext
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                    .getRunningServices(200);
            if (!(serviceList.size() > 0)) {
                return false;
            }
            for (int i = 0; i < serviceList.size(); i++) {
                if (serviceList.get(i).service.getClassName().equals(className)) {
                    isRunning = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isRunning;
    }

    /**
     * 设置软件使用语言
     *
     * @param locale
     * @param context
     */
    public static void settingAppLanguage(Locale locale, Context context) {
        Resources resources = context.getResources();// 获得res资源对象
        Configuration config = resources.getConfiguration();// 获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
        config.locale = locale; // 语言
        resources.updateConfiguration(config, dm);
    }

    public static void hideKey(View tv, Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tv.getWindowToken(), 0);

    }

    public static String getCurrentTimeZone() {
        TimeZone tz = TimeZone.getDefault();
        return createGmtOffsetString(true, true, tz.getRawOffset());
    }

    public static String createGmtOffsetString(boolean includeGmt,
                                               boolean includeMinuteSeparator, int offsetMillis) {
        int offsetMinutes = offsetMillis / 60000;
        char sign = '+';
        if (offsetMinutes < 0) {
            sign = '-';
            offsetMinutes = -offsetMinutes;
        }
        StringBuilder builder = new StringBuilder(9);
        if (includeGmt) {
            builder.append("GMT");
        }
        builder.append(sign);
        appendNumber(builder, 2, offsetMinutes / 60);
        if (includeMinuteSeparator) {
            builder.append(':');
        }
        appendNumber(builder, 2, offsetMinutes % 60);
        return builder.toString();
    }

    private static void appendNumber(StringBuilder builder, int count, int value) {
        String string = Integer.toString(value);
        for (int i = 0; i < count - string.length(); i++) {
            builder.append('0');
        }
        builder.append(string);
    }

    public static void hideSoftKeyboard(Context context, View v) {
        // 隐藏输入法键盘
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }


    public static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }


    public static String getUserAgent() {
        String webAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.120 Mobile Safari/537.36";
        //  String webAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 NetType/%s";
        Locale locale = Locale.getDefault();
        StringBuffer buffer = new StringBuffer();
        // Add version
        final String version = Build.VERSION.RELEASE;
        if (version.length() > 0) {
            buffer.append(version);
        } else {
            // default to "1.0"
            buffer.append("1.0");
        }
        buffer.append("; ");
        final String language = locale.getLanguage();
        if (language != null) {
            buffer.append(language.toLowerCase());
            final String country = locale.getCountry();
            if (country != null) {
                buffer.append("-");
                buffer.append(country.toLowerCase());
            }
        } else {
            // default to "en"
            buffer.append("en");
        }
        // add the model for the release build
        if ("REL".equals(Build.VERSION.CODENAME)) {
            final String model = Build.MODEL;
            if (model.length() > 0) {
                buffer.append("; ");
                buffer.append(model);
            }
        }
        final String id = Build.ID;
        if (id.length() > 0) {
            buffer.append(" Build/");
            buffer.append(id);
        }
        String agent = String.format(webAgent, buffer, getNetworkType());
        Log.i("aaaaa", "agent:" + agent);
        return agent;
    }


    public static String getNetworkType() {
        String strNetworkType = "";
        ConnectivityManager manager = (ConnectivityManager) AppContext.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();
                // TD-SCDMA networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: // api<8 : replace by
                        // 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: // api<9 : replace by
                        // 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11 : replace by
                        // 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13 : replace by
                        // 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: // api<11 : replace by
                        // 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || _strSubTypeName.equalsIgnoreCase("WCDMA")
                                || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }
            }
        }
        return strNetworkType;
    }


    /**
     * 密码强度 1：弱 2:中 3:强
     */
    public static int checkPassword(String passwordStr) {
        String regexZ = "\\d*";
        String regexS = "[a-zA-Z]+";
        String regexT = "\\W+$";
        String regexZT = "\\D*";
        String regexST = "[\\d\\W]*";
        String regexZS = "\\w*";
        String regexZST = "[\\w\\W]*";
        if (passwordStr.matches(regexZ)) {
            return 1;
        }
        if (passwordStr.matches(regexS)) {
            return 1;
        }
        if (passwordStr.matches(regexT)) {
            return 1;
        }
        if (passwordStr.matches(regexZT)) {
            return 2;
        }
        if (passwordStr.matches(regexST)) {
            return 2;
        }
        if (passwordStr.matches(regexZS)) {
            return 2;
        }
        if (passwordStr.matches(regexZST)) {
            return 3;
        }
        return 1;
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


    /**
     * 关闭键盘
     *
     * @param context
     */
    public static void closeSoftKeyBoard(Activity context) {
        View view = context.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 打开键盘
     *
     * @param context
     */
    public static void openSoftKeyBoard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    public static String getDateFormat(String date, String inFormat, String OutFormat) {
        try {
            SimpleDateFormat in = new SimpleDateFormat(inFormat);
            Date d = in.parse(date);
            SimpleDateFormat out = new SimpleDateFormat(OutFormat);
            return out.format(d);
        } catch (Exception e) {

        }
        return null;
    }

    public static String getDateFormat(long date, String OutFormat) {
        try {
            Date d = new Date();
            d.setTime(date);
            SimpleDateFormat out = new SimpleDateFormat(OutFormat);
            return out.format(d);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 最大日期 当前日期加一年
     *
     * @return
     */
    public static String getMaxDateString() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1);
        Date date = calendar.getTime();
        String DATE_FORMAT1 = "yyyy-MM-dd HH:mm";
        SimpleDateFormat in = new SimpleDateFormat(DATE_FORMAT1);
        return in.format(date);
    }

    public static void searchBoxClearStatus(ImageView searchBoxClear, int count) {
        if (count == 0) {
            searchBoxClear.setVisibility(View.GONE);
        } else {
            searchBoxClear.setVisibility(View.VISIBLE);
        }
    }

    public static String getImageUrlFromHtmlStr(String str) {
        int index = str.indexOf("<img");
        if (index >= 0) {
            str = str.substring(index, str.length());
            int end = str.indexOf("/>");
            str = str.substring(0, end);
            int img = str.indexOf("src");
            String url = str.substring(img + 5, str.indexOf(".") + 4);
            TLog.log("aaa", "url:" + url);
            return Constants.IMAGE_URL + url;
        }
        return null;
    }


    public static String loadHtmlData(Activity activity, String fileName) {
        try {
            InputStream in = activity.getAssets().open(fileName);
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String str = "";
            String htmlData = null;
            while ((htmlData = br.readLine()) != null) {
                str = str + htmlData;
            }
            TLog.log("aaa", str);
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 截取 HTML 文本中的图片
     *
     * @param htmlStr
     * @return
     */
    public static List getImgStr(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List pics = new ArrayList();
        String regEx_img = "]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
