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.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.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.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.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.CheckBox;
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.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.mdad.sdk.mdsdk.common.AdData;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sheep.gamegroup.dateview.DatePickerDialog;
import com.sheep.gamegroup.dateview.DateUtil;
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.HomeListEntity;
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.RoundedCornersTransformation;
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.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.DialogShare;
import com.sheep.gamegroup.view.fragment.FgtPersonalCenter;
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.sheep.jiuyan.samllsheep.utils.SpUtils;

import org.afinal.simplecache.ACache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

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.saveAndSetRqImage(iv_qr, link, 800);
        Glide.with(activity)
                .load(R.drawable.icon)
                .apply(new RequestOptions().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();
                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("已保存");
            }
        });
        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();
    }

    /**
     * 主页抢任务，更换任务时，获取新的任务
     *
     * @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;
                        SpUtils.saveOrder("order", mRobTask.getOrder());
                        SheepApp.getInstance().setOrder(mRobTask.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,
     * @param viewAnchor 锚
     */
    public void showRobDutyDialog(final Activity mActivity, View viewAnchor, RobTask robTask) {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_robduty, null, false);
        ImageView ivChangeOne = view.findViewById(R.id.iv_change_one);
        ImageView ivDoNow = view.findViewById(R.id.iv_do_now);

        final ImageView ivIcon = view.findViewById(R.id.iv_duty);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        final TextView tvTitel = view.findViewById(R.id.tv_duty_title);
        final TextView tvDutyMoney = view.findViewById(R.id.tv_robduty_money);
        ViewUtil.setDefaultText(tvTitel);
        ViewUtil.setDefaultText(tvDutyMoney);
        if(robTask != null){
            mRobTask = robTask;
            SpUtils.saveOrder("order", mRobTask.getOrder());
            SheepApp.getInstance().setOrder(mRobTask.getOrder());
            tvDutyMoney.setText("+"+mRobTask.getM().getBonus() + "元");//设置任务奖励金额
            tvTitel.setText(mRobTask.getM().getName()+"");//设置任务名字--getTask().getTask_name()
            GlideImageLoader.setImage(ivIcon, mRobTask.getM().getTask().getIcon());//设置任务图标
        }else {
            mRobTask = getTask(ivIcon, tvTitel, tvDutyMoney);
        }
        final PopupWindow popupWindow = new PopupWindow(mActivity);
        popupWindow.setContentView(view);
        popupWindow.setAnimationStyle(R.style.Rising);
        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.5f, mActivity);
        try {
            popupWindow.showAtLocation(viewAnchor, Gravity.CENTER, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupWindow.setOnDismissListener(new PopDismissListener(mActivity));
        //更换任务
        ivChangeOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRobTask = getTask(ivIcon, tvTitel, tvDutyMoney);
                LogUtil.logI("抢任务---" + new Gson().toJson(mRobTask));

            }
        });
        //立即去做，跳转到任务详情去
        ivDoNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.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) {
                popupWindow.dismiss();
            }
        });

    }

    /**
     * 设置默认方块文本
     *
     * @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("\u2588");
        }
        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) {
        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("推荐给好友");

        TextView withdrawal = view.findViewById(R.id.withdrawal);
        TextView tv_link = view.findViewById(R.id.tv_link);
        TextView save_pic = view.findViewById(R.id.save_pic);
        final ImageView iv_qr = view.findViewById(R.id.iv_qr);

        if (!TextUtils.isEmpty(link))
            tv_link.setText(link);

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

        withdrawal.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();
                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("已保存");
            }
        });
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 领取福利成功的对话框
     *
     * @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 的缓存视图
     *
     * @param view
     * @return
     */
    public static Bitmap getCacheBitmapFromView(View view) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        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.JPEG, 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 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(mContext, R.layout.dialog_parent, 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());
                }
                setColorMapText(dialog_msg, msg, dialogConfig.getColorMsgMap());
                int msgGravity = dialogConfig.getMsgGravity();
                if (msgGravity != Gravity.NO_GRAVITY)
                    dialog_msg.setGravity(msgGravity);
            }
        }

        final WebView dialog_msg_wv = view.findViewById(R.id.dialog_msg_wv);
        if (dialog_msg_wv != null) {
            ViewUtil.loadDataWithBaseURL(dialog_msg_wv, msg);
        }

        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 isRigthBtnShow = 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(isRigthBtnShow ? 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 && isRigthBtnShow ? 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();
    }


    /**
     * 分享
     *
     * @param activity
     * @param url
     */
    public void showShare(Activity activity, String url, String description) {
        new DialogShare(activity, url, description).showShare();
    }

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

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

    public static void setImage(ImageView imageView, String pictures, int radius) {
        if (imageView != null && !TextUtils.isEmpty(pictures)) {
            if (pictures.contains(";")) {
                pictures = pictures.split(";")[0];
            }
            GlideImageLoader.roundedCornersImage(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, String msg) {
        if (textView != null) {
            textView.setText(TextUtils.isEmpty(msg) ? "" : msg);
        }

    }

    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 ProgressDialog mPd;

    public void showProgress(Activity activity) {
        try {
            if (mPd != null) {
                hideProgress(activity);
            }
            mPd = new ProgressDialog(activity);
//        View view= LayoutInflater.from(this).inflate(R.layout.dialog_layout,null);
//        dialogShowLoading.setContentView(view);//自己定义布局
            mPd.setMessage("数据加载中...");
            mPd.setCancelable(true);//能否够被取消
//        dialogShowLoading.setProgressStyle(ProgressDialog.STYLE_SPINNER);//圆环风格
            mPd.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showProgress(Activity activity, boolean cancel) {
        try {
            if (mPd != null) {
                hideProgress(activity);
            }
            mPd = new ProgressDialog(activity);
//        View view= LayoutInflater.from(this).inflate(R.layout.dialog_layout,null);
//        dialogShowLoading.setContentView(view);//自己定义布局
            mPd.setMessage("数据加载中...");
            mPd.setCancelable(cancel);//能否够被取消
//        dialogShowLoading.setProgressStyle(ProgressDialog.STYLE_SPINNER);//圆环风格
            mPd.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void hideProgress(Activity activity) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mPd != null) {
                    mPd.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);
    }

    public static void showShareDialog(final Activity activity, final String url, final String description){
        View dialog_parent = View.inflate(activity, R.layout.ask_to_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(activity, R.style.AppTheme_Dialog_Alert)
                .setView(dialog_parent)
                .create();
//        TextView ask_share_title = dialog_parent.findViewById(R.id.ask_share_title);
        RecyclerView ask_share_list = dialog_parent.findViewById(R.id.ask_share_list);
//        ask_share_list.setHasFixedSize(true);
//        ask_share_list.setNestedScrollingEnabled(false);
        List<String> list = ListUtil.emptyList();
//        list.add(DialogShare.SYS_SEND);
        list.add(DialogShare.WX);
        list.add(DialogShare.QQ);
        list.add(DialogShare.WEIXIN_CIRCLE);
        list.add(DialogShare.QZONE);
//        list.add(DialogShare.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) {
                        CommonUtil.getInstance().popShare(activity, url, item, description);
                    }
                });

            }
        };
        ask_share_list.setAdapter(adapter);
        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();
        }
    }

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

    /**
     * 标签类型（0无，1热门，2最新，3现金，4活跃，5福利）
     * homepage item statues
     */
    public void showGridviewStatues(Context context, TextView textView, HomeListEntity entity) {
        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 (entity.getTag()) {
            default:

                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_red_f07422_stroke_retangle_no_lb);
                textView.setTextColor(context.getResources().getColor(R.color.red_F07422));
                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
     *
     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;
    }
}