package com.sheep.gamegroup.util;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.LayoutRes;
import android.support.annotation.StringRes;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.RequestOptions;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.mdad.sdk.mdsdk.common.AdData;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.IContentTypeContainer;
import com.sheep.gamegroup.absBase.ITag;
import com.sheep.gamegroup.dateview.DatePickerDialog;
import com.sheep.gamegroup.dateview.DateUtil;
import com.sheep.gamegroup.module.find.util.IFilter;
import com.sheep.gamegroup.model.entity.Advertising;
import com.sheep.gamegroup.model.entity.Container;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.GameAccountEntity;
import com.sheep.gamegroup.model.entity.GiftBagApp;
import com.sheep.gamegroup.model.entity.Lp;
import com.sheep.gamegroup.model.entity.PayEntity;
import com.sheep.gamegroup.model.entity.RobTask;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.util.glide.FilterTransform;
import com.sheep.gamegroup.util.glide.RoundedCornersTransformation;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.gamegroup.util.viewHelper.LayoutParamsUtil;
import com.sheep.gamegroup.view.activity.ActMain;
import com.sheep.gamegroup.view.activity.PersonalInfoAct;
import com.sheep.gamegroup.view.activity.SplashAct;
import com.sheep.gamegroup.view.activity.TaskDetailAct;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.dialog.DialogAddAccount;
import com.sheep.gamegroup.view.dialog.DialogLoading;
import com.sheep.gamegroup.view.dialog.DialogMidong;
import com.sheep.gamegroup.view.dialog.DialogModifyAccount;
import com.sheep.gamegroup.view.dialog.DialogOrienteeringDetails;
import com.sheep.gamegroup.view.dialog.DialogPayAccount;
import com.sheep.gamegroup.view.dialog.DialogPayGame;
import com.sheep.gamegroup.view.dialog.DialogProgress;
import com.sheep.gamegroup.view.fragment.FgtPersonalCenter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.afinal.simplecache.ACache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.AD_TOAST;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.GAME_INSTEAD_OF_RECHARGE_PLATFORM;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.GIFT_BAG_DIALOG_COPY_CODE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.GIFT_BAG_DIALOG_START_APP;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.QR_COPY;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.QR_SAVE;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.QR_SHARE;

/**
 * Created by realicing on 2018/5/11.
 * realicing@sina.com
 */
public class ViewUtil {

    public static final int REQUEST_CODE_TASK_LIST = 110;
    private static ViewUtil viewUtil;
    private RobTask mRobTask;

    public static ViewUtil newInstance() {
        if (viewUtil == null) {
            viewUtil = new ViewUtil();
        }
        return viewUtil;
    }

    public static void showQR(final Activity activity, String link) {
        QR_SHARE.onEvent();
        View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                .setView(dialog_parent)
                .create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        View view = LayoutInflater.from(activity).inflate(R.layout.x_ask_qr_dialog, dialog_center_ll, true);
        dialog_title.setText("我的二维码");

        final ImageView iv_qr = view.findViewById(R.id.iv_qr);
        View save_pic = view.findViewById(R.id.save_pic);
        ImageView iv_qr_small = view.findViewById(R.id.iv_qr_small);

        GlideImageLoader.saveAndSetRqImageDisHardConfig(iv_qr, link, 800);
        Glide.with(activity)
                .load(R.drawable.icon)
                .apply(new RequestOptions().disallowHardwareConfig().override(G.WIDTH / 8))
                .into(iv_qr_small);

        dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        save_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                QR_SAVE.onEvent();
                try {
                    File file = ViewUtil.saveImage((View) iv_qr.getParent(), ClassFileHelper.DIR, System.currentTimeMillis() + ".jpg");
                    if (file != null) {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        activity.sendBroadcast(intent); // 发送广播通知相册
                    } else {
                        ViewUtil.sysSaveImage((View) iv_qr.getParent(), "小绵羊", "二维码分享");
                    }
                    G.showToast("已保存");
                } catch (Exception e) {
                    e.printStackTrace();
                    G.showToast(BuildConfig.DEBUG ? e.getMessage() : "暂不支持");
                }
            }
        });
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @param context   Activity的上下文
     * @param mTextView 显示日期的TextView
     */
    public static void showDateDialog(final PersonalInfoAct context, final TextView mTextView, String time) {
        List<Integer> date;
        try {
            date = DateUtil.getDateForString((TextUtils.isEmpty(time) && time.equals("0001-01-01T00:00:00Z")) ? "1990-01-01" : time);//从1990-01-01开始显示}
        } catch (Exception e) {
            date = DateUtil.getDateForString("1990-01-01");
        }
        DatePickerDialog.Builder builder = new DatePickerDialog.Builder(context);
        builder.setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {
            @Override
            public void onDateSelected(int[] dates) {
                mTextView.setText(dates[0] + "-" + (dates[1] > 9 ? dates[1] : ("0" + dates[1])) + "-" + (dates[2] > 9 ? dates[2] : ("0" + dates[2])));
                context.upLoadBirthday(mTextView.getText().toString());
            }

            @Override
            public void onCancel() {

            }
        }).setSelectYear(date.get(0) - 1)
                .setSelectMonth(date.get(1) - 1)
                .setSelectDay(date.get(2) - 1);
        Dialog dateDialog = builder.create();
        dateDialog.show();
    }

    public static void refreshXrv(XRecyclerView view_list) {
        try {
            if (view_list != null)
                view_list.refresh();
            /**
             * java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jcodecraeer.xrecyclerview.ArrowRefreshHeader.setState(int)' on a null object reference
             *         at com.jcodecraeer.xrecyclerview.XRecyclerView.refresh(XRecyclerView.java:202)
             */
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //加载js
    public static void loadJs(com.tencent.smtt.sdk.WebView mWebView, String js) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript("javascript:" + js, new com.tencent.smtt.sdk.ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        } else {
            mWebView.loadUrl("javascript:" + js);
        }
    }

    //加载js
    public static void loadJs(WebView mWebView, String js) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript("javascript:" + js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        } else {
            mWebView.loadUrl("javascript:" + js);
        }
    }

    //刷新RecyclerView的adapter
    public static void notifyDataSetChanged(RecyclerView recyclerView) {
        if (recyclerView != null && recyclerView.getAdapter() != null)
            recyclerView.getAdapter().notifyDataSetChanged();
    }

    public static void dismiss(DialogProgress dialogProgress, int delay) {
        if (dialogProgress != null) {
            dismiss(dialogProgress.getAlertDialog(), delay);
        }
    }

    public static void dismiss(DialogLoading dialogLoading, int delay) {
        if (dialogLoading != null) {
            dismiss(dialogLoading.getAlertDialog(), delay);
        }
    }

    public static void dismiss(final AlertDialog dialog, int delay) {
        if (dialog != null) {
            if (delay > 0) {
                delay(new AbsObserver<Integer>() {
                    @Override
                    public void onNext(Integer integer) {
                        try {
                            dialog.dismiss();
                        } catch (Exception ignore) {

                        }
                    }
                }, delay);
            } else {
                dialog.dismiss();
            }
        }
    }

    public static void delay(Observer<Integer> observer, int delay) {
        io.reactivex.Observable.just(1)
                .delay(delay, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public static void setChecked(Checkable view, boolean checked) {
        if (view != null)
            view.setChecked(checked);
    }

    /**
     * 主页抢任务，更换任务时，获取新的任务
     *
     * @return , TaskEty对象
     */
    public RobTask getTask(final ImageView ivIcon, final TextView tvTitel, final TextView tvDutyMoney) {
        //LogUtil.logI(SpUtils.getOrder("order") + "开始的order");

        CommonUtil.getInstance().robTask(new Action1<RobTask>() {
            @Override
            public void call(RobTask robTask) {
                if (robTask != null) {
                    try {
                        mRobTask = robTask;
                        DataUtil.putAsInt(DataKey.KEY_ORDER, robTask.getOrder());
                        tvDutyMoney.setText("+" + mRobTask.getM().getBonus() + "元");//设置任务奖励金额
                        tvTitel.setText(mRobTask.getM().getName() + "");//设置任务名字--getTask().getTask_name()
                        GlideImageLoader.setImage(ivIcon, mRobTask.getM().getTask().getIcon());//设置任务图标
                    } catch (Exception e) {
                    }
                } else {
                    G.showToast("任务已被抢光！请实时关注任务发布！");
                }
            }
        });
        return mRobTask;
    }

    /**
     * 抢任务弹框
     *
     * @param mActivity 当前Activity,
     */
    public void showRobDutyDialog(final Activity mActivity, RobTask robTask) {
        showRobDutyDialog(mActivity, robTask, R.layout.dialog_game_or_task_or_gift, null);
    }

    /**
     * 抢任务弹框
     *
     * @param mActivity 当前Activity,
     */
    public void showRobDutyDialog(final Activity mActivity, RobTask robTask, @LayoutRes int layoutId, Action1<View> action1) {
        View view = LayoutInflater.from(mActivity).inflate(layoutId, null, false);
        final AlertDialog mAlertDialog = new AlertDialog.Builder(mActivity, R.style.MyDialogActivityTheme)
                .setView(view)
                .create();
        if (action1 != null)
            action1.call(view);
        View dialog_btn_left = view.findViewById(R.id.dialog_btn_left);
        View dialog_btn_right = view.findViewById(R.id.dialog_btn_right);

        final ImageView dialog_iv = view.findViewById(R.id.dialog_iv);
        ImageView ivClose = view.findViewById(R.id.dialog_close);
        final TextView dialog_name_tv = view.findViewById(R.id.dialog_name_tv);
        final TextView dialog_amount_tv = view.findViewById(R.id.dialog_amount_tv);
        ViewUtil.setDefaultText(dialog_name_tv);
        ViewUtil.setDefaultText(dialog_amount_tv);
        if (robTask != null && robTask.getM() != null) {
            mRobTask = robTask;
            DataUtil.putAsInt(DataKey.KEY_ORDER, robTask.getOrder());
            ViewUtil.setText(dialog_amount_tv, String.format(Locale.CHINA, "+%s元", mRobTask.getM().getBonus()));//设置任务奖励金额
            ViewUtil.setText(dialog_name_tv, mRobTask.getM().getName());//设置任务名字--getTask().getTask_name()
            GlideImageLoader.setImage(dialog_iv, mRobTask.getM().getTask().getIcon());//设置任务图标
        } else {
            mRobTask = getTask(dialog_iv, dialog_name_tv, dialog_amount_tv);
        }

        //更换任务
        dialog_btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRobTask = getTask(dialog_iv, dialog_name_tv, dialog_amount_tv);

            }
        });
        //立即去做，跳转到任务详情去
        dialog_btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAlertDialog.dismiss();
                if (mRobTask == null) {
                    G.showToast("抢任务失败！");
                    return;
                }
                Intent intent = new Intent(mActivity, TaskDetailAct.class);
                intent.putExtra("btn_show", false);
                intent.putExtra("is_from_task_list", false);
                intent.putExtra("task_id", mRobTask.getM().getId());
                mActivity.startActivity(intent);

            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.dismiss();
            }
        });
        mAlertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                DataUtil.putAsInt(DataKey.KEY_ORDER, 1);
                if (mActivity instanceof ActMain && DataUtil.getAsBoolean("tryShowHalfScreenAd", false)) {
                    DataUtil.putAsBoolean("tryShowHalfScreenAd", false);
                    Jump2View.getInstance().tryShowHalfScreenAd(mActivity, ((ActMain) mActivity).getContainer());
                }
            }
        });
        try {
            mAlertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static final String BLOCK = "\u2588";//用特殊字符显示方块

    /**
     * 设置默认方块文本
     *
     * @param textView
     */
    public static void setDefaultText(TextView textView) {
        String text = textView.getText().toString();
        int length = TextUtils.isEmpty(text) ? Math.abs(new Random().nextInt(7)) : text.length();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append(BLOCK);
        }
        textView.setText(stringBuilder);
    }


    /**
     * 兑换红包弹窗
     *
     * @param mActivity 当前Activity的，
     */
    public static void changeRedPackage(final Activity mActivity, View viewAnchor, final FgtPersonalCenter fgtPersonalCenter) {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_get_redpackage, null);
        final EditText edInvitationCode = view.findViewById(R.id.ed_invitation_code);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        final TextView tvGetRedPackage = view.findViewById(R.id.tv_get_redpackage);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.7f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new PopDismissListener(mActivity));
        tvTitle.setText("兑换");
        tvGetRedPackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edInvitationCode.getText())) {
                    G.showToast("邀请码不能为空！");
                } else {
                    fgtPersonalCenter.getRedPackage(edInvitationCode.getText().toString(), popupWindow);
                    popupWindow.dismiss();
                }
            }
        });
        edInvitationCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                // 获取系统剪贴板
                ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 获取剪贴板的剪贴数据集
                ClipData clipData = clipboard.getPrimaryClip();

                if (clipData != null && clipData.getItemCount() > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    CharSequence codetext = clipData.getItemAt(0).getText();
                    if (!TextUtils.isEmpty(codetext)) {
                        edInvitationCode.setText(codetext);
                    }
                }
                return false;
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

    }

    /**
     * 测量屏幕的宽
     *
     * @param mActivity ,
     * @return 屏幕的宽
     */
    private static int measureWidth(Activity mActivity) {
        WindowManager manager = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = manager.getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        defaultDisplay.getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 测量屏幕的宽
     *
     * @param mActivity ,
     * @return 屏幕的宽
     */
    public static int measureHeight(Activity mActivity) {
        WindowManager manager = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = manager.getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        defaultDisplay.getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * @param mActivity  ，个人资料Activity
     * @param viewAnchor ，锚
     *                   选择性别弹窗
     */
    public static void choiceSex(final PersonalInfoAct mActivity, View viewAnchor) {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_choice_sex, null);
        TextView tvOk = view.findViewById(R.id.tv_cancel);
        final CheckBox cbMale = view.findViewById(R.id.btn_male);
        final CheckBox cbFemale = view.findViewById(R.id.btn_female);
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        cbFemale.setTextColor(Color.parseColor("#ff444444"));
        cbMale.setTextColor(Color.parseColor("#ff444444"));
        popupWindow.setContentView(view);
        popupWindow.setWidth(measureWidth(mActivity));
        popupWindow.setHeight(ActionBar.LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.Rising);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(0.5f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.BOTTOM, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new PopDismissListener(mActivity));
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.upLoadSex((!cbFemale.isChecked() && !cbMale.isChecked()) ? 0 : cbMale.isChecked() ? 1 : 2, popupWindow);
            }
        });
        //选择男
        cbMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbMale.setTextColor(Color.parseColor("#ff2d4b"));
                    cbFemale.setTextColor(Color.parseColor("#ff444444"));
                }
            }
        });
        //选择女
        cbFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbFemale.setTextColor(Color.parseColor("#ff2d4b"));
                    cbMale.setTextColor(Color.parseColor("#ff444444"));

                }
            }
        });

    }

    public static View setBottomLine(final XRecyclerView view_list) {
        return setBottomLine(view_list, null);
    }

    public static View setBottomLine(final XRecyclerView view_list, final Action1<String> action1) {
        View view = LayoutInflater.from(SheepApp.getInstance()).inflate(action1 != null ? R.layout.empty : R.layout.common_foot_view, null);
        if (view_list != null) {
            view_list.setFootView(view, new CustomFooterViewCallBack() {
                @Override
                public void onLoadingMore(View yourFooterView) {
                    if (action1 != null) {
                        action1.call("onLoadingMore");
                    } else {
                        TextView bottom_line_text = yourFooterView.findViewById(R.id.bottom_line_text);
                        bottom_line_text.setText("羊羊努力加载中...");
                    }
                }

                @Override
                public void onLoadMoreComplete(View yourFooterView) {
                    if (action1 != null) {
                        action1.call("onLoadMoreComplete");
                    } else {
                        TextView bottom_line_text = yourFooterView.findViewById(R.id.bottom_line_text);
                        bottom_line_text.setText(canScrollToTop() ? "加载完成，点击我回到顶部" : "加载完成");
                        yourFooterView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (canScrollToTop())
                                    view_list.scrollToPosition(0);
                            }
                        });
                    }
                }

                @Override
                public void onSetNoMore(View yourFooterView, boolean noMore) {
                    if (action1 != null) {
                        action1.call("onSetNoMore");
                    } else {
                        yourFooterView.setVisibility(isEmpty() ? View.GONE : View.VISIBLE);
                        TextView bottom_line_text = yourFooterView.findViewById(R.id.bottom_line_text);
                        bottom_line_text.setText(canScrollToTop() ? "我是有底线的，点击我回到顶部" : "我是有底线的");
                        yourFooterView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (canScrollToTop())
                                    view_list.scrollToPosition(0);
                            }
                        });
                    }
                }

                private boolean isEmpty() {
                    return view_list.getAdapter().getItemCount() == 0;
                }

                private boolean canScrollToTop() {
                    return view_list.getAdapter().getItemCount() > 10;
                }
            });
        }
        return view;
    }

    public static View setBottomLine(final SmartRefreshLayout refreshLayout, final Action1<String> action1) {
        View view = LayoutInflater.from(SheepApp.getInstance()).inflate(action1 != null ? R.layout.empty : R.layout.common_foot_view, null);
        TextView bottom_line_text = view.findViewById(R.id.bottom_line_text);
        bottom_line_text.setText("点击加载更多...");
        bottom_line_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoLoadMore();
            }
        });
        return view;
    }

    /**
     * popwindow消失监听类，消失恢复window透明度
     */
    public static class PopDismissListener implements PopupWindow.OnDismissListener {
        Activity mActivity;

        public PopDismissListener(Activity activity) {
            mActivity = activity;
        }

        @Override
        public void onDismiss() {
            backgroundAlpha(1f, mActivity);
        }

    }

    /**
     * @param bgAlpha  ，透明度值
     * @param activity 恢复透明度
     */
    public static void backgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 分享对话框
     *
     * @param activity
     * @param link
     */
    public static void shareLink(final Activity activity, final String link) {
        shareLink(activity, null, link, null, null, null);
    }

    public static void shareLink(final Activity activity, String viewTitle, final String link, final String title, final String content, final ShareCallback callback) {
        View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                .setView(dialog_parent)
                .create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        View view = LayoutInflater.from(activity).inflate(R.layout.x_recommend_dialog, dialog_center_ll, true);
        dialog_title.setText(TextUtils.isEmpty(viewTitle) ? "推荐给好友" : viewTitle);

        View wx = view.findViewById(R.id.but_share_wx);
        View qq = view.findViewById(R.id.but_share_qq);
        View pyq = view.findViewById(R.id.but_share_pyq);
        View zone = view.findViewById(R.id.but_share_zone);
        final View url = view.findViewById(R.id.but_share_link);
        TextView save_pic = view.findViewById(R.id.save_pic);
        final ImageView iv_qr = view.findViewById(R.id.iv_qr);

        /* 分享到微信 */
        wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareAction(activity, title, content, link, SHARE_MEDIA.WEIXIN, callback);
                dialog.dismiss();
            }
        });

        /* 分享到QQ */
        qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareAction(activity, title, content, link, SHARE_MEDIA.QQ, callback);
                dialog.dismiss();
            }
        });

        /* 分享到朋友圈 */
        pyq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareAction(activity, title, content, link, SHARE_MEDIA.WEIXIN_CIRCLE, callback);
                dialog.dismiss();
            }
        });

        /* 分享到QQ空间 */
        zone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareAction(activity, title, content, link, SHARE_MEDIA.QZONE, callback);
                dialog.dismiss();
            }
        });

        GlideImageLoader.saveAndSetRqImageDisHardConfig(iv_qr, link, 800);
        dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QR_COPY.onEvent();
                StringUtils.CopyText(link);
                G.showToast("复制链接成功!");
            }
        });

        save_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QR_SAVE.onEvent();
                try {
                    File file = ViewUtil.saveImage((View) iv_qr.getParent(), ClassFileHelper.DIR, System.currentTimeMillis() + ".jpg");
                    if (file != null) {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        activity.sendBroadcast(intent); // 发送广播通知相册
                    } else {
                        ViewUtil.sysSaveImage((View) iv_qr.getParent(), "小绵羊", "二维码分享");
                    }
                    G.showToast("已保存");
                } catch (Exception e) {
                    e.printStackTrace();
                    G.showToast(BuildConfig.DEBUG ? e.getMessage() : "暂不支持");
                }
            }
        });
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建链接并分享
     *
     * @param activity 上下文参数
     * @param url      分享链接
     * @param media    分享平台
     */
    private static void shareAction(Activity activity, String title, String content, String url, SHARE_MEDIA media, final ShareCallback callback) {
        /* 缩略图 */
        UMImage image = new UMImage(activity, R.drawable.icon);
        /* URL */
        UMWeb web = new UMWeb(url);
        /* 标题 */
        web.setTitle(!TextUtils.isEmpty(title) ? "赚钱就来小绵羊" : title);
        web.setThumb(image);
        web.setDescription(!TextUtils.isEmpty(content) ? "更懂你的赚钱工具，超多福利，超多赏金，拿到你手软！" : content);
        switch (media) {
            case WEIXIN_CIRCLE:
                web.setTitle(web.getTitle() + "\n" + web.getDescription());
                break;
        }
        ShareAction action = new ShareAction(activity);
        action.setPlatform(media);
        action.withMedia(web);
        action.setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                G.showToast("分享成功！");
                if (callback != null) {
                    callback.callback();
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                G.showToast("分享失败！");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                G.showToast("您已取消分享！");
            }
        });
        action.share();
    }

    public static interface ShareCallback {
        void callback();
    }

    /**
     * 领取福利成功的对话框
     *
     * @param activity
     * @param item
     */
    public static void showGetWelfareDialog(final Activity activity, final GiftBagApp item) {
        showGetWelfareDialog(activity, item, null);
    }

    public static void showGetWelfareDialog(final Activity activity, final GiftBagApp item, final String packageName) {
        View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                .setView(dialog_parent)
                .create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        View view = LayoutInflater.from(activity).inflate(R.layout.x_get_welfare_dialog, dialog_center_ll, true);
        dialog_title.setText("领取成功");

        TextView dialog_btn_left = view.findViewById(R.id.dialog_btn_left);
        TextView dialog_btn_right = view.findViewById(R.id.dialog_btn_right);
        dialog_btn_left.setText("关闭");
        dialog_btn_right.setText("启动游戏");

        final TextView get_welfare_code_tv = view.findViewById(R.id.get_welfare_code_tv);
        TextView get_welfare_copy_tv = view.findViewById(R.id.get_welfare_copy_tv);
        TextView get_welfare_content_tv = view.findViewById(R.id.get_welfare_content_tv);
        // 设置内容与兑换码
        get_welfare_content_tv.setText(String.format(Locale.CHINA, "礼包内容：%s", item.getGift_bag().getGiftContent()));
        get_welfare_code_tv.setText(String.format(Locale.CHINA, "兑换码：%s", item.getCode()));
        get_welfare_copy_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GIFT_BAG_DIALOG_COPY_CODE.onEvent("gift_bag_id", item.getGift_bag().getId(), "gift_bag_code", item.getCode());
                StringUtils.CopyText(item.getCode());
                G.showToast("复制兑换码成功");
            }
        });

        dialog_btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                GIFT_BAG_DIALOG_START_APP.onEvent("gift_bag_id", item.getGift_bag().getId(), "package_name", TextUtils.isEmpty(packageName) ? item.getApp().getPackage_names() : packageName);
                //启动游戏
                PackageUtil.startApp(activity, TextUtils.isEmpty(packageName) ? item.getApp().getPackage_names() : packageName);
            }
        });
        dialog_btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取一个 View 的缓存视图
     * 如果报错：Software rendering doesn't support hardware bitmaps
     * 在Glide 4.3上，hardware bitmaps(开启hardware bitmaps作用大概就是在使用ARGB_8888这种高质量的图片时，图片在内存中只会存在一份，反正就是一种节省内存的机制。) 配置默认是开启的，这也是Glide的一个Bug，高版本不知道修复了没有。
     * <p>
     * 解决方案是在构建RequestOptions时，将该配置关掉。
     * <p>
     * requestOptions.disallowHardwareConfig();
     *
     * @param view
     * @return
     */
    public static Bitmap getCacheBitmapFromView(View view) {
        int w = view.getWidth();
        int h = view.getHeight();

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        view.draw(c);
        return bitmap;
    }

    public static void sysSaveImage(View view, String title, String description) {
        MediaStore.Images.Media.insertImage(view.getContext().getContentResolver(), getCacheBitmapFromView(view), title, description);
    }

    public static File saveImage(View view, String dir, String fileName) {
        return saveImage(getCacheBitmapFromView(view), dir, fileName);
    }

    public static File saveImage(Bitmap bmp, String dir, String fileName) {
        File appDir = new File(dir);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void setH5Text(TextView textView, com.tencent.smtt.sdk.WebView webView, String content) {
        if (textView == null || webView == null) {
            return;
        }
        if (ViewUtil.isH5Content(content)) {
            webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
            textView.setVisibility(View.GONE);
        } else if (content.startsWith("<p>")) {
            ViewUtil.loadDataWithBaseURL(webView, content);
            textView.setVisibility(View.GONE);
        } else {
            webView.setVisibility(View.GONE);
            String[] items = content.split("\n");
            StringBuilder stringBuilder = new StringBuilder(INDENT);
            for (int i = 0; i < items.length; i++) {
                if (i != 0)
                    stringBuilder.append("\n").append(INDENT);
                stringBuilder.append(items[i]);
            }
            textView.setText(stringBuilder.toString());
            textView.setMovementMethod(new ScrollingMovementMethod());
        }
    }

    public static void setH5Text(TextView textView, String content) {
        if (textView != null) {
            if (TextUtils.isEmpty(content)) {
                textView.setText("");
                return;
            }
            textView.setText(Html.fromHtml(content));
            textView.setMovementMethod(new ScrollingMovementMethod());
        }
    }

    public static void setH5ImgText(TextView textView, String content, int maxWidth) {
        if (textView != null) {
            if (TextUtils.isEmpty(content)) {
                textView.setText("");
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                textView.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, new DetailImageGetter(textView, content, maxWidth), new DetailTagHandler()));
            } else {
                textView.setText(Html.fromHtml(content, new DetailImageGetter(textView, content, maxWidth), new DetailTagHandler()));
            }
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    public static void setH5ImgText(TextView textView, String content, int maxWidth, Html.TagHandler tagHandler) {
        if (textView != null) {
            if (TextUtils.isEmpty(content)) {
                textView.setText("");
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                textView.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, new DetailImageGetter(textView, content, maxWidth), tagHandler));
            } else {
                textView.setText(Html.fromHtml(content, new DetailImageGetter(textView, content, maxWidth), tagHandler));
            }
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    public static void loadDataWithBaseURL(com.tencent.smtt.sdk.WebView webView, String content) {
        webView.loadDataWithBaseURL(null,
                new StringBuilder("<html><head><meta name=\"viewport\" content=\"width=device-width,height=auto, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" /><style>img{max-width:100% !important;height:auto !important;}</style><style>body{max-width:100% !important;}</style></head><body>").append(content).append("</body></html>").toString()
                , "text/html", "utf-8", null);
    }

    public static void loadDataWithBaseURL(WebView webView, String content) {
        webView.loadDataWithBaseURL(null,
                new StringBuilder("<html><head><meta name=\"viewport\" content=\"width=device-width,height=auto, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" /><style>img{max-width:100% !important;height:auto !important;}</style><style>body{max-width:100% !important;}</style></head><body>").append(content).append("</body></html>").toString()
                , "text/html", "utf-8", null);
    }

    public static boolean isH5Content(String content) {
        return content.trim().startsWith("<html>") || content.trim().startsWith("<!DOCTYPE html>") || content.trim().endsWith("</html>");
    }


    public static AlertDialog showMsgDialog(final Context context, String msg) {
        return showMsgDialog(context, new DialogConfig().setMsg(msg).setBtnLeftText("知道了"));
    }

    public static AlertDialog showMsgDialog(final Context context, String msg, String title) {
        return showMsgDialog(context, new DialogConfig().setMsg(msg).setTitle(title).setBtnLeftText("知道了"));
    }

    public static AlertDialog showMsgDialog(final Context context, String msg, String title, String leftBtn, String rightBtn,
                                            View.OnClickListener onClickListener, View.OnClickListener onRightClickListener, View.OnClickListener onCloseClickListener) {
        return showMsgDialog(context, new DialogConfig().setMsg(msg).setTitle(title).setBtnLeftText(leftBtn)
                .setBtnRightText(rightBtn)
                .setBtnLeftOnClickListener(onClickListener)
                .setBtnRightOnClickListener(onRightClickListener)
                .setBtnCloseOnClickListener(onCloseClickListener));
    }

    public static AlertDialog showMsgDialog(final Context context, String msg, String title, boolean isFinish) {
        return showMsgDialog(context, new DialogConfig().setMsg(msg).setTitle(title).setFinish(isFinish).setBtnLeftText("知道了"));
    }

    public static AlertDialog showMsgDialog(Context context, final DialogConfig dialogConfig) {
        final Context mContext = context == null ? ActivityManager.getInstance().currentActivity() : context;
        String title = dialogConfig.getTitle();
        String msg = dialogConfig.getMsg();
        String msgMore = dialogConfig.getMsgMore();
        String tip = dialogConfig.getTip();
        String btnLeftText = dialogConfig.getBtnLeftText();
        final View.OnClickListener btnLeftOnClickListener = dialogConfig.getBtnLeftOnClickListener();
        String btnRightText = dialogConfig.getBtnRightText();
        final View.OnClickListener btnRightOnClickListener = dialogConfig.getBtnRightOnClickListener();
        final View.OnClickListener btnCloseOnClickListener = dialogConfig.getBtnCloseOnClickListener();
        View dialog_parent = View.inflate(SheepApp.getInstance(), dialogConfig.getParentLayoutId(), null);
        final AlertDialog dialog = new AlertDialog.Builder(mContext, mContext instanceof Activity ? R.style.MyDialogActivityTheme : R.style.AppTheme_Dialog_Alert).setView(dialog_parent).create();
        TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
        switch (dialogConfig.getTheme()) {//设置按钮风格
            case DialogConfig.THEME_PURPLE:
                dialog_title.setBackgroundResource(R.drawable.shape_purple_solid_rectangle_top);
                break;
        }
        View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
        LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
        final View view = LayoutInflater.from(mContext).inflate(dialogConfig.getLayoutId(), dialog_center_ll, true);
        if (!TextUtils.isEmpty(title))
            dialog_title.setText(title);

        final TextView dialog_msg = view.findViewById(R.id.dialog_msg);
        if (dialog_msg != null) {
            if (TextUtils.isEmpty(msg)) {
                dialog_msg.setVisibility(View.GONE);
            } else {
                dialog_msg.setVisibility(View.VISIBLE);
                if (dialogConfig.getMsgIndent() > 0) {
                    msg = addIndent(msg, dialogConfig.getMsgIndent());
                }
                if (msg.startsWith("<p>")) {//<p></p>这种格式的用dialog_msg.setText(Html.fromHtml(msg));方式显示，避免高度变化，影响用户体验
                    dialog_msg.setText(Html.fromHtml(msg));
                    if (msg.split("<p>").length > 1) {
                        ViewGroup.LayoutParams msgLayoutParams = dialog_msg.getLayoutParams();
                        if (msgLayoutParams instanceof LinearLayout.LayoutParams) {
                            ((LinearLayout.LayoutParams) msgLayoutParams).bottomMargin *= -2;
                        } else if (BuildConfig.DEBUG) {
                            G.showToast("这里的bottomMargin显得多了，需要干掉");
                        }
                        dialog_msg.setLayoutParams(msgLayoutParams);
                    }
                } else {
                    setColorMapText(dialog_msg, msg, dialogConfig.getColorMsgMap());
                }
                int msgGravity = dialogConfig.getMsgGravity();
                if (msgGravity != Gravity.NO_GRAVITY)
                    dialog_msg.setGravity(msgGravity);
            }
        }

        TextView dialog_msg_more = view.findViewById(R.id.dialog_msg_more);
        if (dialog_msg_more != null) {
            if (TextUtils.isEmpty(msgMore)) {
                dialog_msg_more.setVisibility(View.GONE);
            } else {
                dialog_msg_more.setVisibility(View.VISIBLE);
                dialog_msg_more.setText(msgMore);
                if (dialogConfig.getMsgMoreColor() > 0)
                    dialog_msg_more.setTextColor(mContext.getResources().getColor(dialogConfig.getMsgMoreColor()));
            }
        }

        TextView dialog_tip = view.findViewById(R.id.dialog_tip);
        if (dialog_tip != null) {
            if (TextUtils.isEmpty(tip)) {
                dialog_tip.setVisibility(View.GONE);
            } else {
                dialog_tip.setVisibility(View.VISIBLE);
                dialog_tip.setText(tip);
            }
        }

        TextView dialog_btn_left = view.findViewById(R.id.dialog_btn_left);
        boolean isLeftBtnShow = btnLeftText != null || btnLeftOnClickListener != null;
        if (dialog_btn_left != null) {
            switch (dialogConfig.getTheme()) {//设置按钮风格
                case DialogConfig.THEME_PURPLE:
                    dialog_btn_left.setBackgroundResource(R.drawable.selector_button_full_purple);
                    dialog_btn_left.setTextColor(Color.WHITE);
                    break;
            }
            dialog_btn_left.setVisibility(isLeftBtnShow ? View.VISIBLE : View.GONE);
            if (!TextUtils.isEmpty(btnLeftText))
                dialog_btn_left.setText(btnLeftText);
            dialog_btn_left.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (btnLeftOnClickListener != null) {
                        btnLeftOnClickListener.onClick(v);
                    }
                    if (!dialogConfig.isBtnLeftNotDissDialog())
                        dialog.dismiss();
                }
            });
        }

        TextView dialog_btn_right = view.findViewById(R.id.dialog_btn_right);
        boolean isRightBtnShow = btnRightText != null || btnRightOnClickListener != null;
        if (dialog_btn_right != null) {
            switch (dialogConfig.getTheme()) {//设置按钮风格
                case DialogConfig.THEME_PURPLE:
                    dialog_btn_right.setBackgroundResource(R.drawable.selector_button_full_purple);
                    dialog_btn_right.setTextColor(Color.WHITE);
                    break;
            }
            dialog_btn_right.setVisibility(isRightBtnShow ? View.VISIBLE : View.GONE);
            if (!TextUtils.isEmpty(btnRightText))
                dialog_btn_right.setText(btnRightText);
            dialog_btn_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (btnRightOnClickListener != null) {
                        btnRightOnClickListener.onClick(v);
                    }
                    dialog.dismiss();
                }
            });
        }

        View dialog_btn_center = view.findViewById(R.id.dialog_btn_center);
        if (dialog_btn_center != null) {
            dialog_btn_center.setVisibility(isLeftBtnShow && isRightBtnShow ? View.VISIBLE : View.GONE);
        }

        if (dialog_close != null) {
            if (dialogConfig.isCancelable())//
                dialog_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (btnCloseOnClickListener != null) {
                            btnCloseOnClickListener.onClick(v);
                        }
                        dialog.dismiss();
                    }
                });
            else
                dialog_close.setVisibility(View.GONE);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                try {
                    if (dialogConfig.isFinish()) {
                        if (mContext instanceof Activity) {
                            ((Activity) mContext).finish();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        if (!(mContext instanceof Activity) && dialog.getWindow() != null) {
            dialog.getWindow().setType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? WindowManager.LayoutParams.TYPE_PHONE : WindowManager.LayoutParams.TYPE_TOAST);
        }
        if (!dialogConfig.isCancelable())
            dialog.setCancelable(false);
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dialog;
    }

    /**
     * 通过map来设置字体颜色
     *
     * @param textView
     * @param msg
     * @param colorMsgMap key为文本，value为要设置的颜色（#FF0000）
     */
    public static void setColorMapText(TextView textView, String msg, Map<String, String> colorMsgMap) {
        if (textView == null) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            textView.setText("");
        }
        if (colorMsgMap.isEmpty()) {
            textView.setText(msg);
        } else {
            int index = 0;
            for (Map.Entry<String, String> entry : colorMsgMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();//例如红色 #FF0000
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value) && msg.contains(key) && value.length() == 7) {
                    int length = msg.length();
                    if (index < length) {
                        int position = msg.indexOf(key, index);
                        String start = msg.substring(0, position);
                        String middle = getHtmlText(key, value);
                        String end = msg.substring(position + key.length());
                        index = (start + middle).length();
                        msg = start + middle + end;
                    }
                }
            }
            textView.setText(Html.fromHtml(msg));
        }
    }

    /**
     * 通过map来设置字体颜色
     *
     * @param textView
     * @param msg
     * @param items    key为文本，value为要设置的颜色（#FF0000）
     */
    public static void setColorMapText(TextView textView, String msg, String... items) {
        if (textView == null) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            textView.setText("");
        }
        if (items == null || items.length < 1 || items.length % 2 == 1) {
            textView.setText(msg);
        } else {
            int index = 0;
            for (int i = 0; i + 1 < items.length; ) {
                String key = items[i];
                String value = items[i + 1];//例如红色 #FF0000
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value) && msg.contains(key) && value.length() == 7) {
                    int length = msg.length();
                    if (index < length) {
                        int position = msg.indexOf(key, index);
                        String start = msg.substring(0, position);
                        String middle = getHtmlText(key, value);
                        String end = msg.substring(position + key.length());
                        index = (start + middle).length();
                        msg = start + middle + end;
                    }
                }
                i += 2;
            }
            textView.setText(Html.fromHtml(msg));
        }
    }

    /**
     * 获取html格式并带颜色的文字
     *
     * @param text  文字
     * @param color 颜色
     * @return
     */
    public static String getHtmlText(String text, String color) {
        return String.format(Locale.CHINA, "<font color='%s'>%s</font>", color, text);
    }


    public static void showHalfScreenAd(final Activity activity, final Advertising advertising, Container<Action1<Integer>> container) {
        if (activity != null) {
            View dialog_parent = View.inflate(activity, R.layout.dialog_parent, null);
            final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.MyDialogActivityTheme)
                    .setView(dialog_parent)
                    .create();
            TextView dialog_title = dialog_parent.findViewById(R.id.dialog_title);
            final View dialog_close = dialog_parent.findViewById(R.id.dialog_close);
            final LinearLayout dialog_center_ll = dialog_parent.findViewById(R.id.dialog_center_ll);
            View view = LayoutInflater.from(activity).inflate(R.layout.dialog_half_screen_ad, dialog_center_ll, true);
            setText(dialog_title, advertising.getName());

            ACache aCache = ACache.get(SheepApp.getInstance());
            String wh = aCache.getAsString(advertising.getDisplay_src());
            if (!TextUtils.isEmpty(wh) && wh.contains(";")) {
                String[] items = wh.split(";");
                dialog_center_ll.setMinimumWidth(Integer.parseInt(items[0]));
                dialog_center_ll.setMinimumHeight(Integer.parseInt(items[1]));
            }
            dialog_center_ll.setPadding(0, activity.getResources().getDimensionPixelSize(R.dimen.content_padding_54), 0, activity.getResources().getDimensionPixelSize(R.dimen.content_padding_15));

            ImageView ad_iv = view.findViewById(R.id.ad_iv);
            VideoView ad_video_view = view.findViewById(R.id.ad_video_view);
            TextView ad_msg = view.findViewById(R.id.ad_msg);
//            final TextView ad_skip = view.findViewById(R.id.ad_skip);
            View dialog_rl = view.findViewById(R.id.dialog_rl);

//            SurfaceHolder holder = ad_video_view.getHolder();
//            holder.setFixedSize(ad_video_view.getWidth(), ad_video_view.getWidth()*3/4);
//            ad_video_view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,G.WIDTH*4/7));
            if (advertising.isImage()) {
                RequestBuilder<Drawable> builder = Glide.with(activity).load(advertising.getDisplay_src());
                if (TextUtils.isEmpty(advertising.getDesc())) {//没有标题时 去掉下面的边距 并给图片左下理右下添加图角
                    builder.apply(new RequestOptions().transform(new RoundedCornersTransformation(activity.getResources().getDimensionPixelSize(R.dimen.content_padding_36), 0, RoundedCornersTransformation.CornerType.BOTTOM)));
                    dialog_center_ll.setPadding(0, activity.getResources().getDimensionPixelSize(R.dimen.content_padding_54), 0, 0);
                }
                builder.into(ad_iv);
                ad_video_view.setVisibility(View.GONE);
            } else {
                Uri uri = Uri.parse(advertising.getDisplay_src());
                ad_iv.setVisibility(View.GONE);
                final VideoView videoView = ad_video_view;
                videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra) {
                        if (!mediaPlayer.isLooping())
                            mediaPlayer.setLooping(true);
                        LogUtil.println("onInfo what = " + what + " extra = " + extra);
                        return false;
                    }
                });
                videoView.setVideoURI(uri);
                videoView.start();
                videoView.requestFocus();
                if (container != null) {
                    container.setT(new Action1<Integer>() {
                        @Override
                        public void call(Integer integer) {
                            if (integer == 1) {//onResume
                                videoView.resume();
                            } else if (integer == 2) {//onPause
                                videoView.pause();
                            }
                        }
                    });
                }
            }
//            RxjavaCountDownTimer timer = null;
//            if (advertising.getShow_time() > 0) {
//                ad_skip.setVisibility(View.VISIBLE);
//                dialog.setCancelable(false);
//                timer = RxjavaCountDownTimer.getInstance(BuildConfig.DEBUG ? 1 : advertising.getShow_time())
//                        .setOnTickListener(new RxjavaCountDownTimer.OnTickListener() {
//                            @Override
//                            public void onFinish() {
//                                dialog.setCancelable(true);
//                                dialog_close.setVisibility(View.VISIBLE);
//                                ad_skip.setEnabled(true);
//                                ad_skip.setVisibility(View.GONE);
//                            }
//
//                            @Override
//                            public void onTicker(long time) {
//                                dialog.setCancelable(false);
//                                dialog_close.setVisibility(View.GONE);
//                                ad_skip.setEnabled(false);
//                                ad_skip.setText(activity.getString(R.string.tip_skip, time));
//                            }
//                        }).start();
//            } else {
//                ad_skip.setVisibility(View.GONE);
//            }
//
//            final RxjavaCountDownTimer finalTimer = timer;

            dialog_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            dialog_rl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SplashAct.goAdLink(activity, advertising);
                    AD_TOAST.onEvent("ad_id", advertising.getId());
                    dialog.dismiss();
                }
            });
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
//                    if (finalTimer != null) {
//                        finalTimer.clear();
//                    }
                    ACache aCache = ACache.get(SheepApp.getInstance());
                    aCache.put(advertising.getDisplay_src(), String.format(Locale.CHINA, "%d;%d", dialog_center_ll.getWidth(), dialog_center_ll.getHeight()));
                    Jump2View.getInstance().tryShowReservation(activity);
                }
            });
            if (TextUtils.isEmpty(advertising.getDesc())) {
                ad_msg.setVisibility(View.GONE);
            } else {
                ad_msg.setText(advertising.getDesc());
            }
            try {
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //显示定向货币详情
    public static void showOrienteeringDetails(Activity activity) {
        new DialogOrienteeringDetails(activity).showOrienteeringDetails();
    }

    /**
     * game 充值
     */
    public static void showGamePayAccount(Activity activity, String gameId, String gameName) {
        PayEntity payEntity = new PayEntity();
        payEntity.setGame_id(gameId);
        payEntity.setGame_name(gameName);
        newInstance().showGamePayAccount(activity, payEntity);
    }

    public static void showGamePayAccount(Activity activity, TaskEty taskEty) {
        PayEntity payEntity = new PayEntity();
        payEntity.setGame_id(taskEty.getThird_task_id());
        payEntity.setGame_name(taskEty.getName());
        payEntity.setTask_type(taskEty.getTask_type() + "");
        newInstance().showGamePayAccount(activity, payEntity);
    }

    public void showGamePayAccount(Activity activity, PayEntity payEntity) {
        GAME_INSTEAD_OF_RECHARGE_PLATFORM.onEvent("game_id", payEntity.getGame_id() + "", "name", payEntity.getGame_name() + "");
        new DialogPayAccount(activity, payEntity).showPayaccount();
    }

    public static void showGamePay(Activity activity, PayEntity payEntity) {
        new DialogPayGame(activity, payEntity).showPayGame();
    }

    /**
     * 用户详情
     */
    public void showGameAccountDetail(Activity activity, int id) {
        new DialogModifyAccount(activity, id).showAddAccount();
    }

    /**
     * 用户详情
     */
    public void showGameAccountDetail(Activity activity, GameAccountEntity item) {
        new DialogModifyAccount(activity, item).showAddAccount();
    }


    public static void centerImage(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.centerImage(imageView, pictures);
            }
        }
    }

    public static void setAvatar(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.drawable.avatar);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setAvatar(imageView, pictures);
            }
        }
    }

    public static void setBlur(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setBlur(imageView, pictures);
            }
        }
    }

    //加载默认原图滤镜效果
    public static void setImage(ImageView imageView, final IFilter filter) {
        if (imageView != null && filter != null && filter.getConfig() != null) {
            String url = getNetImgByName("alter_original");
            if (filter.getConfig().isEmpty()) {
                setImage(imageView, url);
                return;
            }
            Glide.with(SheepApp.getInstance())
                    .load(url)
                    .apply(new RequestOptions().transform(new FilterTransform(filter)))
                    .into(imageView);
        }
    }

    public static void setImage(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setImage(imageView, pictures);
            }
        }
    }

    public static void setViewWH(ImageView imageView, String pictures, int width) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                Uri uri = Uri.parse(pictures);
                int w = NumberFormatUtils.parseInteger(uri.getQueryParameter("w"));
                int h = NumberFormatUtils.parseInteger(uri.getQueryParameter("h"));
                if (w > 0 && h > 0) {
                    LayoutParamsUtil.resetLayoutParams(imageView, new Lp().setWidth(width).setHeight((int) (width * h * 1.0f / w)));
                }
            }
        }
    }

    public static void setViewWH(View view, int width, float radio) {
        LayoutParamsUtil.resetLayoutParams(view, new Lp().setWidth(width).setHeight((int) (width * radio)));
    }

    public static void setImagePath(ImageView imageView, String paths) {
        if (imageView != null) {
            if (TextUtils.isEmpty(paths)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (paths.contains(";")) {
                    paths = paths.split(";")[0];
                }
                Glide.with(SheepApp.getInstance()).load(new File(paths)).into(imageView);
            }
        }
    }

    public static void setImagePath(ImageView imageView, String paths, int radio) {
        if (imageView != null) {
            if (TextUtils.isEmpty(paths)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (paths.contains(";")) {
                    paths = paths.split(";")[0];
                }
                Glide.with(SheepApp.getInstance()).load(new File(paths)).apply(new RequestOptions().transform(new RoundedCornersTransformation(radio, 0))).into(imageView);
            }
        }
    }

    public static void setImageLoading(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setImage(imageView, pictures, R.drawable.loading_01);
            }
        }
    }

    public static void setImage(ImageView imageView, String pictures, int radius) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.roundedCornersImage(imageView, pictures, radius);
            }
        }
    }

    public static void setGameImage(ImageView imageView, String pictures) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setGameImage(imageView, pictures);
            }
        }
    }

    public static void setGameImage(ImageView imageView, String pictures, int radius) {
        if (imageView != null) {
            if (TextUtils.isEmpty(pictures)) {
                imageView.setImageResource(R.mipmap.icon);
            } else {
                if (pictures.contains(";")) {
                    pictures = pictures.split(";")[0];
                }
                GlideImageLoader.setGameImage(imageView, pictures, radius);
            }
        }
    }

    public static void setTextTime(TextView textView, long time, String format) {
        if (textView != null) {
            textView.setText(TimeUtil.TimeStamp2Date(time, format));
        }
    }

    public static void setText(TextView textView) {
        if (textView != null) {
            textView.setText("");
        }
    }

    public static void setText(TextView textView, CharSequence msg) {
        if (textView != null) {
            textView.setText(TextUtils.isEmpty(msg) ? "" : msg);
        }
    }

    public static void setText(TextView textView, @StringRes int stringId, Object... objects) {
        if (textView != null) {
            textView.setText(SheepApp.getInstance().getString(stringId, objects));
        }
    }

    public static void setText(TextView textView, String format, Object... objects) {
        if (textView != null) {
            textView.setText(String.format(Locale.CHINA, format, objects));
        }
    }

    public static void setText(TextView textView, IContentTypeContainer<Integer, String> contentTypeContainer, int maxWidth) {
        switch (contentTypeContainer.getContentType()) {
            case StringUtils.CONTENT_TYPE_FONT:
                setText(textView, contentTypeContainer.getContentResult());
                break;
            case StringUtils.CONTENT_TYPE_H5:
//                setH5Text(textView, contentTypeContainer.getContentResult());
                setH5ImgText(textView, contentTypeContainer.getContentResult(), maxWidth);
                break;
            case StringUtils.CONTENT_TYPE_EXP:
                setH5ImgText(textView, contentTypeContainer.getContentResult(), maxWidth);
                break;
        }
    }

    public static void setText(TextView textView, IContentTypeContainer<Integer, String> contentTypeContainer, int maxWidth, Html.TagHandler tagHandler) {
        switch (contentTypeContainer.getContentType()) {
            case StringUtils.CONTENT_TYPE_FONT:
                setText(textView, contentTypeContainer.getContentResult());
                break;
            case StringUtils.CONTENT_TYPE_H5:
//                setH5Text(textView, contentTypeContainer.getContentResult());
                setH5ImgText(textView, contentTypeContainer.getContentResult(), maxWidth, tagHandler);
                break;
            case StringUtils.CONTENT_TYPE_EXP:
                setH5ImgText(textView, contentTypeContainer.getContentResult(), maxWidth, tagHandler);
                break;
        }
    }

    public static void setText(TextView textView, int integer) {
        if (textView != null) {
            textView.setText(String.valueOf(integer));
        }
    }

    public static void setText(TextView textView, float f) {
        if (textView != null) {
            textView.setText(String.valueOf(f));
        }
    }

    /**
     * 设置视频播放和播放按钮与占位图
     *
     * @param videoView
     * @param placeHolderlView 占位图片
     * @param control          控制播放的按钮
     * @param url
     */
    public static void setVideoAndFull(final VideoView videoView, final ImageView placeHolderlView, final ImageView control, final String url) {
        if (videoView == null || control == null || url == null) {
            return;
        }
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoView.setVisibility(View.VISIBLE);
                placeHolderlView.setVisibility(View.INVISIBLE);
                if (videoView.isPlaying()) {
                    videoView.pause();
                    control.setImageResource(R.drawable.ic_play_but_image);
                } else if (!videoView.isPlaying()) {
                    videoView.start();
                    control.setImageResource(R.drawable.loading_01);
                }
            }
        };
        control.setOnClickListener(onClickListener);
        videoView.setOnClickListener(onClickListener);
        videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra) {
                LogUtil.println("setVideoAndFull", "onInfo what = " + what + " extra = " + extra);
                if (!mediaPlayer.isLooping())
                    mediaPlayer.setLooping(true);
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        LogUtil.println("setVideoAndFull", "onInfo", "正在缓冲");
                        control.setImageResource(R.drawable.loading_01);
                        control.setVisibility(View.VISIBLE);
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                        LogUtil.println("setVideoAndFull", "onInfo", "缓冲完成");
                        //缓存完成，继续播放
                        control.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                LogUtil.println("setVideoAndFull", "onPrepared");
                if (placeHolderlView != null)
                    placeHolderlView.setVisibility(View.GONE);
            }
        });
        Uri uri = Uri.parse(url);
        videoView.setVideoURI(uri);
    }

    public static void setTextRetainMost2(TextView textView, float f) {
        if (textView != null) {
            textView.setText(NumberFormatUtils.retainMost2(f));
        }
    }

    public static void setEnabled(View view, boolean enabled) {
        if (view != null) {
            view.setEnabled(enabled);
        }
    }

    public static void setVisibility(View view, boolean isVisible) {
        if (view != null) {
            view.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        }
    }

    public static void toggleVisibility(View view) {
        if (view != null) {
            view.setVisibility(isVisible(view) ? View.GONE : View.VISIBLE);
        }
    }

    public static boolean isVisible(View view) {
        return view != null && view.getVisibility() == View.VISIBLE;
    }

    public static void setVisibility2(View view, boolean isVisible) {
        if (view != null) {
            view.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        }
    }

    public static void toggleVisibility2(View view) {
        if (view != null) {
            view.setVisibility(isVisible(view) ? View.INVISIBLE : View.VISIBLE);
        }
    }

    public static final String INDENT = "\u3000";//用特殊字符显示空白的缩进字符

    public static void setText(TextView textView, String msg, int indent) {
        if (textView != null) {
            textView.setText(addIndent(msg, indent));
        }

    }

    //在msg前面添加空格
    public static String addIndent(String msg, int indent) {
        if (indent > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < indent; i++) {
                stringBuilder.append(INDENT);
            }
            if (!TextUtils.isEmpty(msg))
                stringBuilder.append(msg);
            return stringBuilder.toString();
        }
        return msg;
    }

    /**
     * show ProgressDialog
     */

    protected WeakReference<ProgressDialog> mPd;

    public void showProgress(Activity activity) {
        try {
            if (mPd != null && mPd.get() != null) {
                hideProgress(activity);
            } else {
                mPd = new WeakReference(new ProgressDialog(activity));
            }
            mPd.get().setMessage("数据加载中...");
            mPd.get().setCancelable(true);//能否够被取消
            mPd.get().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showProgress(Activity activity, boolean cancel) {
        try {
            if (mPd != null && mPd.get() != null) {
                hideProgress(activity);
            } else {
                mPd = new WeakReference(new ProgressDialog(activity));
            }
            mPd.get().setMessage("数据加载中...");
            mPd.get().setCancelable(cancel);//能否够被取消
            mPd.get().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void hideProgress(Activity activity) {
        activity.runOnUiThread(() -> {
            if (mPd != null && mPd.get() != null) {
                mPd.get().dismiss();
            }
        });
    }


    /**
     * 添加游戏账户
     */
    public void showAddAccount(Activity activity, Action1<Integer> action1) {
        new DialogAddAccount(activity).showAddAccount(action1);
    }

    /**
     * 幂动详情diaolog
     *
     * @param activity
     * @param action1
     */
    public void showMidongDialog(Activity activity, boolean isSign, final AdData data, Action1<Integer> action1) {
        new DialogMidong(activity).showMidongDialog(isSign, data);
    }

    /**
     * 显示分享弹出框
     *
     * @param activity
     * @param shareLinkConfig
     * @param action1         回调的view为nul时，代表流程结束；不为空时，代表初始化dialog的view，可以做自定义
     */
    public static void showShareDialog(final Activity activity, final ShareLinkConfig shareLinkConfig, final Action1<View> action1) {
        View dialogView = View.inflate(activity, R.layout.ask_to_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.AppTheme_Dialog_Alert)
                .setView(dialogView)
                .create();
//        TextView ask_share_title = dialogView.findViewById(R.id.ask_share_title);
        RecyclerView ask_share_list = dialogView.findViewById(R.id.ask_share_list);
        if (action1 != null)
            action1.call(dialogView);
//        ask_share_list.setHasFixedSize(true);
//        ask_share_list.setNestedScrollingEnabled(false);
        List<String> list = ListUtil.emptyList();
//        list.add(ShareLinkConfig.SYS_SEND);
        list.add(ShareLinkConfig.WX);
        list.add(ShareLinkConfig.QQ);
        list.add(ShareLinkConfig.WEIXIN_CIRCLE);
        list.add(ShareLinkConfig.QZONE);
//        list.add(ShareLinkConfig.COPY_SHARE_LINK);
        final List<String> imgList = ListUtil.emptyList();
//        imgList.add("share_face_to_face");
        imgList.add("share_wx");
        imgList.add("share_qq");
        imgList.add("share_weixin_circle");
        imgList.add("share_qzone");
//        imgList.add("share_copy_share_link");
        final List<String> nameList = ListUtil.emptyList();
//        nameList.add("分享app");
        nameList.add("微信");
        nameList.add("QQ好友");
        nameList.add("朋友圈");
        nameList.add("QQ空间");
//        nameList.add("复制链接");
        GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, list.size());
        ask_share_list.setLayoutManager(gridLayoutManager);
        AdbCommonRecycler<String> adapter = new AdbCommonRecycler<String>(activity, list) {

            @Override
            public int getViewIdByType(int type) {
                return R.layout.ask_to_share_item;
            }

            @Override
            public void convert(ViewHolder holder, final String item) {
                View itemView = holder.itemView;
                if (item == null)
                    return;
                ImageView ask_to_share_item_img = itemView.findViewById(R.id.ask_to_share_item_img);
                TextView ask_to_share_item_name = itemView.findViewById(R.id.ask_to_share_item_name);
                int position = holder.getAdapterPosition();
                GlideImageLoader.setImage(ask_to_share_item_img, getNetImgByName(imgList.get(position)));
                ask_to_share_item_name.setText(nameList.get(position));
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            dialog.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        shareLinkConfig.setShareType(item).toShare(activity);
                    }
                });

            }
        };
        ask_share_list.setAdapter(adapter);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (action1 != null)
                    action1.call(null);
            }
        });
        try {
            dialog.show();
            Window window = dialog.getWindow();
            if (window != null) {
                window.setGravity(Gravity.BOTTOM);
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = G.WIDTH > G.HEIGHT ? G.HEIGHT : G.WIDTH;
                window.setAttributes(params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (action1 != null)
                action1.call(null);
        }
    }

    public static String getNetImgByName(String name) {
        return String.format(Locale.CHINA, "http://cdngame.kuaifazs.com/%s.png", name);
    }

    public static String getNetImgByNameAndSuffix(String name) {
        return String.format(Locale.CHINA, "http://cdngame.kuaifazs.com/%s", name);
    }

    /**
     * 标签类型（0无，1热门，2最新，3现金，4活跃，5福利，6红包）
     * homepage item statues
     */
    public static void updateTag(TextView textView, ITag tag) {
        Context context = SheepApp.getInstance();
        textView.setVisibility(View.INVISIBLE);

        int padding1 = textView.getContext().getResources().getDimensionPixelSize(R.dimen.content_padding_1);
        int padding2 = textView.getContext().getResources().getDimensionPixelSize(R.dimen.content_padding_2);
        switch (tag.getTag()) {
            default:

                break;
            case 1:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_red_stroke_rectangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_FD2D54));
                textView.setText("热门");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
            case 2:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_f07422_stroke_retangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_F07422));
                textView.setText("最新");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
            case 3:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_red_stroke_rectangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_FD2D54));
                textView.setText("现金");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
            case 4:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_f07422_stroke_retangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_F07422));
                textView.setText("活跃");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
            case 5:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_f07422_stroke_retangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_F07422));
                textView.setText("福利");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
            case 6:
                textView.setVisibility(View.VISIBLE);
                textView.setBackgroundResource(R.drawable.shape_red_stroke_rectangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_FD2D54));
                textView.setText("红包");
                textView.setPadding(padding2, padding1, padding2, padding1);
                break;
        }

    }

    /**
     * 获取状态栏高度
     *
     * @param activity
     * @return , 状态栏高度
     */
    public static int getBarHeight(FragmentActivity activity) {
        int result = 0;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * paint
     * R.color.green
     * R.color.yellow_text_light
     * R.color.black_text_gray
     * <p>
     * android:textColor="#cc8e8e8e"
     * android:textSize="10sp"
     * R.drawable.shape_blue_stroke_rectangle_no_lb
     */
    public View paintView(Context context, String text, int color, int drawable) {

        View view = LayoutInflater.from(context).inflate(R.layout.game_tag_textview, null, false);
        TextView textView = view.findViewById(R.id.user_label_tv);

        textView.setText(text);
        textView.setTextColor(context.getResources().getColor(color));
        textView.setBackgroundResource(drawable);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        int padding = textView.getContext().getResources().getDimensionPixelSize(R.dimen.content_padding_2);
        textView.setPadding(2 * padding, padding, 2 * padding, padding);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(textView.getLayoutParams());
        lp.setMargins(0, 0, padding, 0);
        textView.setLayoutParams(lp);

        return view;
    }
}