package com.fxy.baselibrary.base;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.util.RxTool;
import com.jaeger.library.StatusBarUtil;
import com.fxy.baselibrary.R;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.language.LanguageObservable;
import com.fxy.baselibrary.language.other.MultiLanguageUtil;
import com.fxy.baselibrary.pagemanager.MyPageListener;
import com.fxy.baselibrary.pagemanager.MyPageManager;
import com.fxy.baselibrary.tddialog.TDialog;
import com.fxy.baselibrary.tddialog.base.BindViewHolder;
import com.fxy.baselibrary.tddialog.listener.OnViewClickListener;
import com.fxy.baselibrary.util.AppManager;
import com.fxy.baselibrary.util.HideUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.baselibrary.views.MarqueeTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import es.dmoral.toasty.Toasty;
import io.realm.Realm;
import me.yokeyword.fragmentation.SupportActivity;

/**
 * 项目名称：FingerShipWork
 * 类描述：最基本的BaseActivity
 * 创建人：admin
 * 创建时间：2017/8/15 16:54
 * 修改人：COMP-021-2006
 * 修改时间：2017/8/15 16:54
 * 修改备注：
 */

public abstract class BaseActivity extends SupportActivity implements Observer {

    //	protected NetUtil netUtil;
    private static final int titleMaxLength = 11;
    protected RelativeLayout tb_rl;
    protected RelativeLayout rl_top;
    // 左侧
    protected ImageView tb_iv_left;
    protected TextView tb_tv_left;
    // 右侧
    protected TextView tb_tv_right;
    protected ImageView tb_iv_right;
    // 标题
    protected TextView tb_tv_title;
    protected LinearLayout contentLayout;
    protected AppCompatEditText editText;
    protected SearchView mSearchView;
    protected Dialog loadDialog;
    protected TDialog backDialog;
    protected boolean isShowBackDialog = false;
    //    protected ImmersionBar mImmersionBar;
    protected Realm mRealm;
    protected static final int REQUESTCODE_CAMERA = 5001 ;
    protected static final int GET_IMAGE_BY_CAMERA = 5002 ;
    //记录
    MyPageManager pageStateManager;
    /**
     * 在使用自定义toolbar时候的根布局 =toolBarView+childView
     */
    private View baseView;
    private InputMethodManager inputMethodManager;
    private TextView txt_content;

    protected JSONObject limitRepeatObj = new JSONObject();
    /**
     * 播放器引用
     */
    private MediaPlayer mediaPlayer = null;

    /**
     * 页面跳转
     */
    protected static void intent2Page(Activity act, Class<?> act2, boolean isFinish) {
        intent2Page(act, act2, isFinish, null);
    }

    /**
     * 页面跳转
     * @param isFinish 是否关闭act界面
     */
    protected static void intent2Page(Activity act, Class<?> act2, boolean isFinish, Bundle bundle) {
        Intent missionIntent = new Intent(act, act2);
        if (bundle != null) {
            missionIntent.putExtras(bundle);
        }
        act.startActivity(missionIntent);
        if (isFinish) {
            act.finish();
        }
    }

    /**
     *
     * @param act
     * @param act2
     * @param bundle 跳转带的参数
     * @param requestCode 返回code
     */
    protected void intentPageResult(Activity act, Class<?> act2, Bundle bundle, int requestCode) {

        //这个相当于一个信使，this是当前页面，
        //第二个参数是要跳转的页面
        //这里的intent需要跳转页面，所以需要参数。。。在不需要跳转页面的时候，，不需要参数的。这个类也可以用作其他用途
        Intent missionIntent = new Intent(act, act2);
        if (bundle != null) {
            missionIntent.putExtras(bundle);
        }
        //第二个参数只是请求的一个标志，如果不需要返回值，也就不需要这个方法了
        //有可能这个页面会有很多个其他的请求，所有请求都会通过下面那个onActivityResult方法来获得那个页面返回的值
        //所以这个表示，就在获取返回值的时候，用于判断，以对应正确的请求
        startActivityForResult(missionIntent, requestCode);
    }


    /**
     * 播放音效
     * @param musicId
     */
    public void playMusic(int musicId) {
        if(isPlayMusic()) {
            mediaPlayer = MediaPlayer.create(this, musicId);
            mediaPlayer.setVolume(1.0f, 1.0f);//调试声音最大
            mediaPlayer.start();

            // 播放完成可以释放资源 执行这个回调
            mediaPlayer.setOnCompletionListener(mCompletionListener);
        }
    }
    protected MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            releaseMediaPlayer(mediaPlayer);
        }
    };

    /**
     * 释放播放器资源
     */
    protected void releaseMediaPlayer(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            //关键语句
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }
    public void customPlayMusic(String voice){

        try {
            //判断是否需要本地播放
            if(!voice.contains("http")){
                int resourceId = RxTool.getResIdByName(this,voice,"raw");
                playMusic(resourceId);
                return;
            }

            //自定义播放
            AssetFileDescriptor fd = getAssets().openFd(voice);
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (IOException e) {
            //XLog.e(e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 初始化多语言(处理高版本多语言问题)
     * @param context
     */
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(MultiLanguageUtil.getInstance().setConfiguration(context));
    }

    /**
     * 页面跳转
     */
    protected static void intent2Page(Activity act, Class<?> act2, Bundle bundle) {
        intent2Page(act, act2, false, bundle);
    }

    /**
     * 页面跳转
     */
    protected static void intent2Page(Activity act, Class<?> act2) {
        intent2Page(act, act2, false, null);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 注册自定义PDA扫描广播
        Intent intent = new Intent ("ACTION_BAR_SCANCFG");
        intent.putExtra("EXTRA_SCAN_MODE", 3);//API输出模式
        intent.putExtra("EXTRA_SCAN_AUTOENT", 0);//关闭自动换行
        this.sendBroadcast(intent);

        LanguageObservable.getInstance().addObserver(this);
        AppManager.getAppManager().addActivity(this);
        if (openEventBus()) {
            EventBus.getDefault().register(this);
        }
        if (openRealm()) {
            mRealm = Realm.getDefaultInstance();
        }
        Bundle extras = getIntent().getExtras();
        if (null != getIntent().getExtras()) {
            getBundleExtras(extras);
        }
        setContentView(getContentViewResId());
        initImmersion();
        if (isHideEdit()) {
            HideUtil.init(this);
        }
        createLoadDialog(this);
        initToasty();
        initView();
        requestPermission();
    }
    /*
     * 校验摄像头权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {
                //需要开启相机权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }

        }
    }
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        if (layoutResID == 0) {
            throw new RuntimeException("layoutResID==-1 have u create your layout?");
        }

        if (showToolBar()) {
            //如果需要显示自定义toolbar,并且资源id存在的情况下，实例化baseView;
            baseView = LayoutInflater.from(this).inflate(R.layout.ac_base, null, false);//根布局
            ViewStub mVs_toolbar = (ViewStub) baseView.findViewById(R.id.vs_toolbar);//toolbar容器
            FrameLayout fl_container = (FrameLayout) baseView.findViewById(R.id.fl_container);//子布局容器
            mVs_toolbar.setLayoutResource(getToolBarResId());//toolbar资源id
            mVs_toolbar.inflate();//填充toolbar
            LayoutInflater.from(this).inflate(layoutResID, fl_container, true);//子布局
            setContentView(baseView);
            if (getToolBarResId() == R.layout.layout_common_toolbar) {
                tb_rl = (RelativeLayout) findViewById(R.id.tb_rl);
                rl_top = (RelativeLayout) findViewById(R.id.rl_top);
                tb_iv_left = (ImageView) findViewById(R.id.tb_iv_left);
                tb_tv_right = (TextView) findViewById(R.id.tb_tv_right);
                tb_tv_left = (TextView) findViewById(R.id.tb_tv_left);
                tb_iv_right = (ImageView) findViewById(R.id.tb_iv_right);
                tb_tv_title = (TextView) findViewById(R.id.tb_tv_title);
                mSearchView = (SearchView) findViewById(R.id.search_view);
            }
        } else {
            //不显示通用toolbar
            super.setContentView(layoutResID);

        }
        if (isInitState()) {
            pageStateManager = MyPageManager.init(this, new MyPageListener() {
                @Override
                protected void onReallyRetry() {
                    retry();
                }

                @Override
                public void onEmtptyViewClicked(View emptyView) {
                    super.onEmtptyViewClicked(emptyView);
                    retry();
                }
            });
        }
    }

    protected void showContent() {
        if (isInitState()) {

            pageStateManager.showContent();
        }
    }

    /**
     * @return 是否需要状态切换
     */
    public boolean isInitState() {
        return false;
    }

    protected void showEmptyView() {

        showEmptyView(getString(R.string.page_empty));

    }

    /**
     * @param content 内容为空时的提示
     */
    protected void showEmptyView(String content) {
        if (isInitState()) {
            pageStateManager.showEmpty(content);
        }

    }

    protected void showErrorView() {
        showErrorView(getString(R.string.page_load_error));
    }

    /**
     * @param content 错误提示
     */
    protected void showErrorView(String content) {
        if (isInitState()) {

            pageStateManager.showError(content);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        /**
         * 判断是否有Toolbar,并默认显示返回按钮
         */
        if (showToolBar() && getToolBarResId() != 0 && getToolBarResId() != -1) {
            showBack();
        }
    }

    /**
     * 是否显示通用toolBar
     */
    public abstract boolean showToolBar();

    //获取自定义toolbarview 资源id 默认为-1，showToolBar()方法必须返回true才有效
    public int getToolBarResId() {
        return R.layout.layout_common_toolbar;
    }

    /**
     *  返回
     */
    protected void showBack() {
        tb_iv_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                HideUtil.hideSoftKeyboard(BaseActivity.this);
//                hideSoftInput(BaseActivity.this);
                if (isShowBackDialog) {
                    onBackPressedSupport();
                } else {
                    finish();
                }
            }
        });
    }

    @Override
    public void onBackPressedSupport() {
        if (isShowBackDialog) {
            showBackDialog();
            return;
        }
        super.onBackPressedSupport();
    }

    /**
     * 显示退出提示框
     */
    protected void showBackDialog() {
        if (backDialog == null) {
            backDialog = new TDialog.Builder(getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_normal_two)
                    .setScreenWidthAspect(this, 0.7f)
                    .addOnClickListener(R.id.tv_cancel, R.id.tv_confirm)
                    .setOnViewClickListener(new OnViewClickListener() {
                        @Override
                        public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                            int i = view.getId();
                            if (i == R.id.tv_cancel) {
                                tDialog.dismiss();
                            } else if (i == R.id.tv_confirm) {
                                tDialog.dismiss();
                                finish();
                            }
                        }
                    })
                    .create()
                    .show();
        } else {
            if (!backDialog.isVisible()) {
                backDialog.show();
            }
        }
    }

    /**
     * 创建加载框
     */
    protected void createLoadDialog(Context context) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.view_progress_dialog, null);// 得到加载view
        txt_content = (TextView) v.findViewById(R.id.txt_content);
        loadDialog = new Dialog(this, R.style.MyProgressDialog);// 创建自定义样式dialog
        loadDialog.setCancelable(true);// 不可以用“返回键”取消
        loadDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        loadDialog.setContentView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
    }

    /**
     * 显示加载框
     */
    protected void showLoadDialog() {
        showLoadDialog(getString(R.string.loading), false);
    }

    /**
     * 显示提交中弹出框
     */
    protected void showSubmitDialog() {
        showLoadDialog("提交中...", false);
    }


    /**
     * 显示加载框
     */
    protected void showLoadDialog(String content, boolean iscancel) {
        loadDialog.setCancelable(iscancel);
        if (!loadDialog.isShowing()) {
            txt_content.setText(content);
            loadDialog.show();
        }
    }

    /**
     * 显示加载框
     */
    protected void showLoadDialog(String content) {
        showLoadDialog(content, false);
    }

    protected void setTitleName(String title) {
        if (tb_tv_title != null) {
            if (!TextUtils.isEmpty(title)) {
                if (title.length() > titleMaxLength) {
                    tb_tv_title.setText(title.substring(0, titleMaxLength - 1) + "...");
                } else {
                    tb_tv_title.setText(title);
                }
            }
        }
    }

    protected void setRightTitle(String title) {
        if (tb_tv_right != null) {
            if (!TextUtils.isEmpty(title)) {
                if (title.length() > titleMaxLength) {
                    tb_tv_right.setText(title.substring(0, titleMaxLength - 1) + "...");
                } else {
                    tb_tv_right.setText(title);
                }
                //设置为可见
                tb_tv_right.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 初始化提示框背景颜色等
     */
    protected void initToasty() {
        Toasty.Config.getInstance()
                .setErrorColor(ContextCompat.getColor(this, R.color.md_red_A700))
                .setInfoColor(ContextCompat.getColor(this, R.color.md_blue_400))
                .setSuccessColor(ContextCompat.getColor(this, R.color.md_green_400))
                .setWarningColor(ContextCompat.getColor(this, R.color.md_orange_800))
                .setTextColor(ContextCompat.getColor(this, R.color.white))
//    .tintIcon( boolean true)
                .apply();
//    .setToastTypeface(@NonNull Typeface typeface) // optional
    }


    protected void showToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.normal(this, content, Toast.LENGTH_SHORT).show();
            playMusic(R.raw.info);
        }
    }

    protected void showErrorToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.error(this, content , Toast.LENGTH_SHORT).show();
            playMusic(R.raw.error);
        }
    }

    protected void showSuccessToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.success(this, content , Toast.LENGTH_SHORT).show();
            playMusic(R.raw.success);
        }
    }
    //支持自定义
    protected void showSuccessToast(String content,String voice) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.success(this, content , Toast.LENGTH_SHORT).show();
            if (!StringUtils.isEmpty(voice)) {
                customPlayMusic(voice);
            }else{
                playMusic(R.raw.success);
            }
        }
    }

    protected void showSuccessToast(String content,int voiceID) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.success(this, content , Toast.LENGTH_SHORT).show();
            if (voiceID>0) {
                playMusic(voiceID);
            }else{
                playMusic(R.raw.success);
            }
        }
    }

    protected void showInfoToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.info(this, content , Toast.LENGTH_SHORT).show();
            playMusic(R.raw.info);
        }
    }

    protected void showWarningToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.warning(this, content , Toast.LENGTH_SHORT).show();
            playMusic(R.raw.error);
        }
    }
    protected void showWarningToast(String content,String voice) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.warning(this, content , Toast.LENGTH_SHORT).show();
            if (!StringUtils.isEmpty(voice)) {
                customPlayMusic(voice);
            }else{
                playMusic(R.raw.error);
            }
        }
    }

    protected void showWarningToast(String content,int voiceID) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.warning(this, content , Toast.LENGTH_SHORT).show();
            if (voiceID>0) {
                playMusic(voiceID);
            }else{
                playMusic(R.raw.success);
            }
        }
    }


    protected void showIconToast(String content, int img) {
        Drawable icon = ContextCompat.getDrawable(this, img);
        if (!StringUtils.isEmpty(content)) {
            Toasty.normal(this, content, Toast.LENGTH_SHORT,icon).show();
            playMusic(R.raw.info);
        }
    }

    protected void showIconToast(String content,String voice) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.warning(this, content , Toast.LENGTH_SHORT).show();
            if (!StringUtils.isEmpty(voice)) {
                customPlayMusic(voice);
            }else{
                playMusic(R.raw.error);
            }

        }
    }

    protected void showRepeatToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.success(this, content , Toast.LENGTH_SHORT).show();
            playMusic(R.raw.repeat);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isShowBackDialog) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                onBackPressedSupport();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        throw new RuntimeException("please use setContentView(@LayoutRes int layoutResID) instead");
    }

    /**
     * 初始化沉浸式
     */
    public void initImmersion() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.md_blue_500), 0);
    }

    ;

    /**
     * 获取contentView 资源id
     */
    public abstract int getContentViewResId();

    /**
     * @return 是否需要默认隐藏软键盘
     */
    public boolean isHideEdit() {
        return true;
    }

    /**
     * 获取数据失败状态下的点击事件
     */
    public void retry() {

    }

    /**
     * Bundle  传递数据
     *
     * @param extras
     */
    protected abstract void getBundleExtras(Bundle extras);

    /**
     * 子Activity初始化view
     */
    protected abstract void initView();

    /**
     * eventbus在主线程接收方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BaseEventBusBean event) {
        if (event != null) {
            EventBean(event);
        }
    }

    /**
     * EventBus接收信息的方法，开启后才会调用(非粘性事件)
     *
     * @param event
     */
    protected void EventBean(BaseEventBusBean event) {

    }

    /**
     * 粘性事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventSticky(BaseEventBusBean event) {
        if (event != null) {
            EventStickyBean(event);
        }
    }

    /**
     * EventBus接收信息的方法(粘性事件)
     *
     * @param event
     */
    protected void EventStickyBean(BaseEventBusBean event) {

    }

    protected void setShowBackDialog() {
        isShowBackDialog = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LanguageObservable.getInstance().deleteObserver(this);
        dismissBackDialog();
        dismissLoadDialog();
        baseView = null;
        if (openEventBus()) {
            EventBus.getDefault().unregister(this);
        }
//        if (mImmersionBar != null) {
//            mImmersionBar.destroy();
//        }
        if (openRealm()) {
            mRealm.close();
        }
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 显示退出提示框
     */
    protected void dismissBackDialog() {
        if (backDialog != null && backDialog.isVisible()) {
            backDialog.dismiss();
        }
    }

    /**
     * 加载框消失
     */
    protected void dismissLoadDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    /**
     * 是否开启eventBus
     */
    public abstract boolean openEventBus();

    /**
     * 是否播放提示音
     * @return
     */
    public abstract boolean isPlayMusic();
    /**
     * 是否开启Realm数据库
     */
    public boolean openRealm() {
        return true;
    }

    @Override
    public void update(Observable o, Object arg) {
        recreate();
    }

    /**
     * 检查内部内容是否为空
     *
     * @param v
     * @return
     */
    public boolean checkNull(View v) {
        if (null != v && v instanceof EditText) {
            String str = ((EditText) v).getText().toString();
            if (StringUtils.isNotEmpty(str)) {
                return true;
            }
            return false;
        }
        else if(null != v && v instanceof MarqueeTextView){
            String str = ((MarqueeTextView) v).getText().toString();
            if (StringUtils.isNotEmpty(str)) {
                return true;
            }
            return false;
        }else if(null != v && v instanceof TextView){
            String str = ((TextView) v).getText().toString();
            if (StringUtils.isNotEmpty(str)) {
                return true;
            }
            return false;
        }
        return false;
    }
    public final static String MD5(String content) {
        String newContent = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = content.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            newContent = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newContent.toUpperCase();
    }

    /**
     * 判断是不是正整数
     * @param str
     * @return
     */
    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
    public String getScanSetting(){
        SharedPreferences scanSetting = this.getSharedPreferences("scanSetting", Context.MODE_PRIVATE);
        String initStr = "{\"scan_id\":1,\"manufacturer\":\"Newland\",\"device_model\":\"\",\"action\":\"ACTION_BAR_SCAN\",\"is_broadcast\":1,\"data_name\":\"EXTRA_SCAN_DATA\",\"status_name\":\"EXTRA_SCAN_STATE\",\"device_name\":\"默认巴枪\"}";
        return scanSetting.getString("base", initStr);

    }

    public Boolean checkRepeat(String str){
        try {
            //获取当前毫秒
            Long time = System.currentTimeMillis();
            //System.out.println("当前时间:"+time);
            if (limitRepeatObj!=null && limitRepeatObj.has(str)){
                Long oldTime = limitRepeatObj.getLong(str);
                //System.out.println("保存时间:"+oldTime);
                if (oldTime>0 && (time-oldTime)<1500){
                    XLog.d("同一时间提交被终止："+str+"：重复提交时间："+time);
                    return false;
                }
            }
            assert limitRepeatObj != null;
            limitRepeatObj.put(str,time);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return true;
    }

    //统一设置未输入框
    public Boolean setEditTextFocused(View view,Boolean is_parent){
        //可以设置统计记录起来
        if (view instanceof EditText) {
            view.requestFocus();
        }
        if (view!=null){
            if (is_parent){
                LinearLayout ll = (LinearLayout)view.getParent();
                ll.setBackgroundResource(R.drawable.bg_edittext_focused);
                return true;
            }else{
                view.requestFocus();
                view.setBackgroundResource(R.drawable.bg_edittext_focused);
                return true;
            }
        }
        return false;
    }
    //normal
    public Boolean setEditTextNormal(View view,Boolean is_parent){
        //可以设置统计记录起来
        if (view!=null) {
            if (is_parent){
                LinearLayout ll = (LinearLayout)view.getParent();
                ll.setBackgroundResource(R.drawable.bg_edittext_normal);
            }else{
                view.setBackgroundResource(R.drawable.bg_edittext_normal);
            }
            return true;

        }
        return false;
    }

    /**
     * 获取子元素ImageButton
     * @param linearLayout
     * @return
     */
    public ImageButton getChildImageButton(LinearLayout  linearLayout){
        for( int i = 0; i < linearLayout.getChildCount(); i++ ){
            if( linearLayout.getChildAt(i) instanceof ImageButton ){
                return (ImageButton)linearLayout.getChildAt(i);
            }
        }
        return null;
    }
    /**
     * 统一设置清除数据
     * @param imageButton
     */
    public void unifyClearEdit(ImageButton imageButton){
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LinearLayout  linearLayout = (LinearLayout)view.getParent();
                for( int i = 0; i < linearLayout.getChildCount(); i++ ){
                    if( linearLayout.getChildAt(i) instanceof EditText ){
                        ((EditText) linearLayout.getChildAt(i)).getText().clear();
                        linearLayout.getChildAt(i).requestFocus();
                        break;
                    }
                }
            }
        });
    }

    //金额验证
    public static boolean isNumber(String str,Integer num){
        Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,"+num+"})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match=pattern.matcher(str);
        if (match.matches()){
            return Double.parseDouble(str) > 0;
        }else{
            return false ;
        }

    }

    public static boolean isNumber(String str,Integer num,int min){
        Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,"+num+"})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match=pattern.matcher(str);
        if (match.matches()){
            return Double.parseDouble(str) > min;
        }else{
            return false ;
        }

    }

    public static boolean isNum(String str,Integer num){
        Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,"+num+"})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match=pattern.matcher(str);
        return  match.matches();
    }


    protected double getValNum(EditText v){
        return Double.parseDouble(v.getText().toString().trim());
    }
    protected String getValStr(EditText v){
        return v.getText().toString().trim();
    }


    /**
     * 处理特殊字符串
     * @param str
     * @param ruleStr
     * @return
     */
    protected String StrInterception(String str,String ruleStr){
        try {
            str = str.replaceAll("\u001D", "");
            JSONArray rule = new JSONArray(ruleStr);
            int len = str.length();
            for (int i=0;i<rule.length();i++){
                JSONObject jsonObject = rule.getJSONObject(i);
                String number_start = jsonObject.getString("number_start");
                int cut_type = jsonObject.getInt("cut_type");
                int number_length = jsonObject.getInt("number_length");
                int start_index = jsonObject.getInt("start_index")-1;
                int cut_length = jsonObject.getInt("cut_length");

                if (len!=number_length){
                    continue;
                }

                if (!number_start.equals("%") && !str.startsWith(number_start)){
                    continue;
                }

                if (cut_type==1){
                    str = str.substring(start_index,cut_length+start_index);
                }
                //从后往前截取待完善
            }

        } catch (Exception e) {
            XLog.e("截取失败"+e.getMessage());
            e.printStackTrace();
        }
        return str;
    }
}