/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.bxzk.afxj.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.DrawableRes;
import androidx.annotation.StringRes;
import androidx.appcompat.content.res.AppCompatResources;

import com.google.gson.Gson;
import com.bxzk.afxj.R;
import com.bxzk.afxj.application.BApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.RequestBody;


/**通用操作类
 * @author Lemon
 * @use CommonUtil.xxxMethod(...);
 */
public class CommonUtil {
	private static final String TAG = "CommonUtil";

	public CommonUtil() {/* 不能实例化**/}

	//电话<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	/**打电话
	 * @param context
	 * @param phone
	 */
	public static void call(Activity context, String phone) {
		if (StringUtil.isNotEmpty(phone, true)) {
			Uri uri = Uri.parse("tel:" + phone.trim());
			Intent intent = new Intent(Intent.ACTION_CALL, uri);
			toActivity(context, intent);
			return;
		}
		showShortToast(context, "请先选择号码哦~");
	}

	//电话>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	//信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	/**发送信息，多号码
	 * @param context
	 * @param phoneList
	 */
	public static void toMessageChat(Activity context, List<String> phoneList){
		if (context == null || phoneList == null || phoneList.size() <= 0) {
			Log.e(TAG, "sendMessage context == null || phoneList == null || phoneList.size() <= 0 " +
					">> showShortToast(context, 请先选择号码哦~); return; ");
			showShortToast(context, "请先选择号码哦~");
			return;
		}

		String phones = "";
		for (int i = 0; i < phoneList.size(); i++) {
			phones += phoneList.get(i) + ";";
		}
		toMessageChat(context, phones);
	}
	/**发送信息，单个号码
	 * @param context
	 * @param phone
	 */
	public static void toMessageChat(Activity context, String phone){
		if (context == null || StringUtil.isNotEmpty(phone, true) == false) {
			Log.e(TAG, "sendMessage  context == null || StringUtil.isNotEmpty(phone, true) == false) >> return;");
			return;
		}

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.putExtra("address", phone);
		intent.setType("vnd.android-dir/mms-sms");
		toActivity(context, intent);

	}

	//信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	/**分享信息 
	 * @param context
	 * @param toShare
	 */
	public static void shareInfo(Activity context, String toShare) {
		if (context == null || StringUtil.isNotEmpty(toShare, true) == false) {
			Log.e(TAG, "shareInfo  context == null || StringUtil.isNotEmpty(toShare, true) == false >> return;");
			return;
		}

		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "选择分享方式");
		intent.putExtra(Intent.EXTRA_TEXT, toShare.trim());
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		toActivity(context, intent, -1);
	}

	/**发送邮件
	 * @param context
	 * @param emailAddress
	 */
	public static void sendEmail(Activity context, String emailAddress) {
		if (context == null || StringUtil.isNotEmpty(emailAddress, true) == false) {
			Log.e(TAG, "sendEmail  context == null || StringUtil.isNotEmpty(emailAddress, true) == false >> return;");
			return;
		}

		Intent intent = new Intent(Intent.ACTION_SENDTO);
		intent.setData(Uri.parse("mailto:"+ emailAddress));//缺少"mailto:"前缀导致找不到应用崩溃
		intent.putExtra(Intent.EXTRA_TEXT, "内容");  //最近在MIUI7上无内容导致无法跳到编辑邮箱界面
		toActivity(context, intent, -1);
	}

	/**打开网站
	 * @param context
	 * @param webSite
	 */
	public static void openWebSite(Activity context, String webSite) {
		if (context == null || StringUtil.isNotEmpty(webSite, true) == false) {
			Log.e(TAG, "openWebSite  context == null || StringUtil.isNotEmpty(webSite, true) == false >> return;");
			return;
		}

		toActivity(context, new Intent(Intent.ACTION_VIEW, Uri.parse(StringUtil.getCorrectUrl(webSite))));
	}

	/**复制文字 
	 * @param context
	 * @param value
	 */
	public static void copyText(Context context, String value) {
		if (context == null || StringUtil.isNotEmpty(value, true) == false) {
			Log.e(TAG, "copyText  context == null || StringUtil.isNotEmpty(value, true) == false >> return;");
			return;
		}

		ClipData cD = ClipData.newPlainText("simple text", value);
		ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		clipboardManager.setPrimaryClip(cD);
		ToastUtils.showToast(context, "复制成功");
	}


	//启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	/**打开新的Activity，向左滑入效果
	 * @param intent
	 */
	public static void toActivity(final Activity context, final Intent intent) {
		toActivity(context, intent, true);
	}
	/**打开新的Activity
	 * @param intent
	 * @param showAnimation
	 */
	public static void toActivity(final Activity context, final Intent intent, final boolean showAnimation) {
		toActivity(context, intent, -1, showAnimation);
	}
	/**打开新的Activity，向左滑入效果
	 * @param intent
	 * @param requestCode
	 */
	public static void toActivity(final Activity context, final Intent intent, final int requestCode) {
		toActivity(context, intent, requestCode, true);
	}
	/**打开新的Activity
	 * @param intent
	 * @param requestCode
	 * @param showAnimation
	 */
	public static void toActivity(final Activity context, final Intent intent, final int requestCode, final boolean showAnimation) {
		if (context == null || intent == null) {
			return;
		}
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {

				if (requestCode < 0) {
					context.startActivity(intent);
				} else {
					context.startActivityForResult(intent, requestCode);
				}
				if (showAnimation) {
					context.overridePendingTransition(R.anim.right_push_in, R.anim.hold);
				} else {
					context.overridePendingTransition(R.anim.null_anim, R.anim.null_anim);
				}
			}
		});
	}
	//启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


	//显示与关闭进度弹窗方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	private static ProgressDialog progressDialog = null;

	/**展示加载进度条,无标题
	 * @param stringResId
	 */
	public static void showProgressDialog(Activity context, int stringResId){
		try {
			showProgressDialog(context, null, context.getResources().getString(stringResId));
		} catch (Exception e) {
			Log.e(TAG, "showProgressDialog  showProgressDialog(Context context, null, context.getResources().getString(stringResId));");
		}
	}
	/**展示加载进度条,无标题
	 * @param dialogMessage
	 */
	public void showProgressDialog(Activity context, String dialogMessage){
		showProgressDialog(context, null, dialogMessage);
	}
	/**展示加载进度条
	 * @param dialogTitle Title 标题
	 * @param dialogMessage Message 信息
	 */
	public static void showProgressDialog(final Activity context, final String dialogTitle, final String dialogMessage){
		if (context == null) {
			return;
		}
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {

				if (progressDialog == null) {
					progressDialog = new ProgressDialog(context);
				}
				if(progressDialog.isShowing() == true) {
					progressDialog.dismiss();
				}
				if (dialogTitle != null && ! "".equals(dialogTitle.trim())) {
					progressDialog.setTitle(dialogTitle);
				}
				if (dialogMessage != null && ! "".equals(dialogMessage.trim())) {
					progressDialog.setMessage(dialogMessage);
				}
				progressDialog.setCanceledOnTouchOutside(false);
				progressDialog.show();
			}
		});
	}


	/** 隐藏加载进度
	 */
	public static void dismissProgressDialog(Activity context) {
		if(context == null || progressDialog == null || progressDialog.isShowing() == false){
			return;
		}
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				progressDialog.dismiss();
			}
		});
	}
	//显示与关闭进度弹窗方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	//show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	/**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
	 * @param context
	 * @param stringResId
	 */
	public static void showShortToast(final Context context, int stringResId) {
		try {
			showShortToast(context, context.getResources().getString(stringResId));
		} catch (Exception e) {
			Log.e(TAG, "showShortToast  context.getResources().getString(resId) >>  catch (Exception e) {" + e.getMessage());
		}
	}
	/**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
	 * @param string
	 */
	public static void showShortToast(final Context context, final String string) {
		showShortToast(context, string, false);
	}
	/**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
	 * @param string
	 * @param isForceDismissProgressDialog
	 */
	public static void showShortToast(final Context context, final String string, final boolean isForceDismissProgressDialog) {
		if (context == null) {
			return;
		}
		Toast.makeText(context, "" + string, Toast.LENGTH_SHORT).show();
	}
	//show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>




	/**将图片改为圆角类型
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}


	/**保存照片到SD卡上面
	 * @param path
	 * @param photoName
	 * @param formSuffix
	 * @param photoBitmap
	 */
	public static String savePhotoToSDCard(String path, String photoName, String formSuffix, Bitmap photoBitmap) {
		if (photoBitmap == null || StringUtil.isNotEmpty(path, true) == false
				|| StringUtil.isNotEmpty(StringUtil.getTrimedString(photoName)
						+ StringUtil.getTrimedString(formSuffix), true) == false) {
			Log.e(TAG, "savePhotoToSDCard photoBitmap == null || StringUtil.isNotEmpty(path, true) == false" +
					"|| StringUtil.isNotEmpty(photoName, true) == false) >> return null" );
			return null;
		}

		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File photoFile = new File(path, photoName + "." + formSuffix); // 在指定路径下创建文件
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
						fileOutputStream)) {
					fileOutputStream.flush();
					Log.i(TAG, "savePhotoToSDCard<<<<<<<<<<<<<<\n" + photoFile.getAbsolutePath() + "\n>>>>>>>>> succeed!");
				}
			} catch (FileNotFoundException e) {
				Log.e(TAG, "savePhotoToSDCard catch (FileNotFoundException e) {\n " + e.getMessage());
				photoFile.delete();
				//				e.printStackTrace();
			} catch (IOException e) {
				Log.e(TAG, "savePhotoToSDCard catch (IOException e) {\n " + e.getMessage());
				photoFile.delete();
				//				e.printStackTrace();
			} finally {
				try {
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
				} catch (IOException e) {
					Log.e(TAG, "savePhotoToSDCard } catch (IOException e) {\n " + e.getMessage());
					//					e.printStackTrace();
				}
			}

			return photoFile.getAbsolutePath();
		}

		return null;
	}



	/**
	 * 检测网络是否可用
	 *
	 * @param context
	 * @return
	 */
	public static boolean isNetWorkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}

		return false;
	}

	public static Long getNumber(String _s) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(_s);
		return Long.valueOf(m.replaceAll("").trim());
	}

	/**
	 * 检测Sdcard是否存在
	 *
	 * @return
	 */
	public static boolean isExitsSdcard() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	/**获取顶层 Activity
	 * @param context
	 * @return
	 */
	public static String getTopActivity(Context context) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		@SuppressWarnings("deprecation")
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

		return runningTaskInfos == null ? "" : runningTaskInfos.get(0).topActivity.getClassName();
	}


	/**检查是否有位置权限
	 * @param context
	 * @return
	 */
	public static boolean isHaveLocationPermission(Context context){
		return isHavePermission(context, "android.permission.ACCESS_COARSE_LOCATION") || isHavePermission(context, "android.permission.ACCESS_FINE_LOCATION");
	}
	/**检查是否有权限
	 * @param context
	 * @param name
	 * @return
	 */
	public static boolean isHavePermission(Context context, String name){
		try {
			return PackageManager.PERMISSION_GRANTED == context.getPackageManager().checkPermission(name, context.getPackageName());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}


	/*
	* 从资源文件中读取
	* */
	public static String getAssertJson(String fileName,Context context) {
		//将json数据变成字符串
		StringBuilder stringBuilder = new StringBuilder();
		try {
			//获取assets资源管理器
			AssetManager assetManager = context.getAssets();
			//通过管理器打开文件并读取
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					assetManager.open(fileName)));
			String line;
			while ((line = bf.readLine()) != null) {
				stringBuilder.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}

/*
* 格式化string
* */
	public static String getResourceStr(@StringRes int id, Object... args) {
		String temp4 = BApplication.getContext().getResources().getString(id);
		String total = String.format(temp4,  args);
		return total;
	}

	public static String getResourceStr(@StringRes int id) {
		String temp4 = BApplication.getContext().getResources().getString(id);
		return temp4;
	}



	//retrofit 参数
	public static RequestBody getRequestBody(Object bean) {
		Gson gson = new Gson();
		String s = gson.toJson(bean);
		Log.e("HttpJson:" +s);
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),s);
		return  requestBody;
	}


 	public static RequestBody getRequestBody1(String s ) {
		Log.e("HttpJson:" +s);
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),s);
		return  requestBody;
	}

	public static void setDarkStatusIcon(boolean bDark,Activity activity) {
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
			View decorView = activity.getWindow().getDecorView();
			if(decorView != null){
				int vis = decorView.getSystemUiVisibility();
				if(bDark){
					vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
				} else{
					vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
				}
				decorView.setSystemUiVisibility(vis);
			}
		}
	}

	//textview 的draw属性
	public static void setTvDrawable(TextView textView, Context context, @DrawableRes int resId) {
		Drawable drawable = AppCompatResources.getDrawable(context, resId);
		drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
		textView.setCompoundDrawables(null,drawable,null,null);
	}


	public static void setTvDrawableLeft(TextView textView, Context context,  int resId) {

		if(resId <= 0) {
			textView.setCompoundDrawables(null,null,null,null);

		}else {
			Drawable drawable = AppCompatResources.getDrawable(context, resId);
			drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
			textView.setCompoundDrawables(drawable,null,null,null);

		}
	}


	public static int getStateBarHeight(Context ctx){
		int result = 0;
		int resourceId = ctx.getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = ctx.getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}
	public static String parseDate(long times) {
		long ms = times * 1000 - TimeZone.getDefault().getRawOffset();
		SimpleDateFormat formatter = new SimpleDateFormat("DD天 HH:mm:ss");
		return formatter.format(ms);
	}


	/**
	 * 获取渠道号 (对应Manifest.xml里配置友盟的 UMENG_CHANNEL 的值)
	 * @param context
	 * @return
	 */
	public static String getChannel(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(),   PackageManager.GET_META_DATA);
			return appInfo.metaData.getString("UMENG_CHANNEL");
		} catch (PackageManager.NameNotFoundException ignored) {
		}
		return "";
	}


	@SuppressLint("MissingPermission")
	public static String getIMEI(Context context) {
		String imei;
		try {
			TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			imei = telephonyManager.getDeviceId();
		} catch (Exception e) {
			imei = "";
		}
		return imei;
	}

}