package com.sheep.gamegroup.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.kfzs.duanduan.utils.ApkUtils;
import com.mdad.sdk.mdsdk.AdManager;
import com.mdad.sdk.mdsdk.common.AdData;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.IJump;
import com.sheep.gamegroup.absBase.IJumpWeb;
import com.sheep.gamegroup.alipay.PayResult;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventTypes;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.helper.TaskHelper;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.Ext;
import com.sheep.gamegroup.model.entity.FriendAndAwardEntity;
import com.sheep.gamegroup.model.entity.GameAccountEntity;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.entity.GameListTag;
import com.sheep.gamegroup.model.entity.GiftBagApp;
import com.sheep.gamegroup.model.entity.HomeListEntity;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.entity.RobTask;
import com.sheep.gamegroup.model.entity.RouserArticlesEntity;
import com.sheep.gamegroup.model.entity.SlideshowEty;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.TaskChild;
import com.sheep.gamegroup.model.entity.TaskDescEntity;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.entity.WithdrawalEty;
import com.sheep.gamegroup.model.entity.XiaomiGameEntity;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.usage.AppUsageManager;
import com.sheep.gamegroup.view.activity.GameTaskOrderListAct;
import com.sheep.gamegroup.view.dialog.DialogNewbieTaskList;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.service.AutoCheckService;
import com.sheep.jiuyan.samllsheep.service.DownloadService;
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 com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.afinal.simplecache.ACache;
import org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.NEWBIE_TASK;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.RECEIVE_AWARD_GAME_TASK;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.XIAOMI_GAME_RECEIVE;
import static com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST;
import static com.sheep.gamegroup.view.adapter.WelfareAdapter.TO_REFRESH;
import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

/**
 * 一些公用的class
 * Created by ljy on 2018/3/21.
 */

public class CommonUtil {
    //多次点击预防
    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long lastClickTime = 0;

    public static String START_TASK = "开始任务";
    public static String GET_TASK = "领取任务";
    public static String START_PLAY = "开始试玩";
    public static String CONTINUE_DOWNLOAD = "继续下载";
    public static String START_DOWNLOAD = "开始下载";
    public static String FAIL_DOWNLOAD = "下载失败";
    public static String START_INSTALL = "开始安装";
    public static String OPEN_APPLY = "打开应用";
    public static String GAME_RECHAGE = "充值游戏";
    public static String GAME_DOWNLOAD = "下载游戏";
    public static String GAME_INSTALL = "安装游戏";
    public static String GAME_OPEN = "开始试玩";
    public static String GAME_RESERVATION = "预约游戏";
    public static String TASK_OFFLINE = "任务已下线";
    public static final String TASK_AUDIT = "audit";
    private static CommonUtil commonUtil;

    public static CommonUtil getInstance() {
        if (commonUtil == null) {
            commonUtil = new CommonUtil();
        }
        return commonUtil;
    }

    /**
     * 返回提现审核结果
     * 审核状态 1系统审核不通过等待人工审核 2系统审核通过 3人工审核不通过 4人工审核通过
     */
    public String returnAuditResult(WithdrawalEty ety) {
        String result = "未审核";
        switch (ety.getStatus()) {
            case 0:
                result = "未审核";
                break;
            case 1:
                result = "等待人工审核";
                break;
            case 2:
                result = returnPayState(ety);
                break;
            case 3:
                result = "人工审核不通过";
                break;
            case 4:
                result = returnPayState(ety);
                break;
        }
        return result;
    }

    public String returnPayState(WithdrawalEty ety) {

        String result = "未付款";
        switch (ety.getPay_status()) {
            case 0:
            case 1:
            case 3:
                result = "付款中";
                break;
            case 2:
                result = "已付款";
                break;
        }
        return result;
    }

    /**
     * 昵称限制
     *
     * @param str
     * @param maxLen
     * @return
     */
    public boolean handleText(String str, int maxLen) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        int count = 0;
        int endIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            char item = str.charAt(i);
            if (item < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
            if (maxLen == count || (item >= 128 && maxLen + 1 == count)) {
                endIndex = i;
            }
        }
//        if (count <= maxLen) {
//            return str;
//        } else {
//            G.showToast("昵称超过限制长度");
//            return str.substring(0, endIndex) + "...";
//        }
        if (count <= maxLen) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 添加下载
     */
    public DownLoadInfo addNewDownloadTask(String gameName, String downloadUrl, String packageName,
                                           int versionCode, String iconUrl, String size, Integer gameId, int whereFrom) {
        DownLoadInfo task = new DownLoadInfo();
        task.setMIconUrl(iconUrl);
        task.setMGameName(gameName);
        task.setMDownloadUrl(downloadUrl);
        task.setMPackageName(packageName);
        task.setMVersionCode(versionCode);
        task.setMTotalSize(Double.valueOf(size));
        task.setMGameID(gameId);
        task.setWhereFrom(whereFrom);
        task.setMApkPath(DIR + File.separator + packageName + downloadUrl.hashCode() + ClassFileHelper.FILE_SUFFIX);
        return task;
    }

    /**
     * 暂停下载
     */
    public void stopDownloadTask(Context context, String downloadUrl) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return;
        }
//        try {
//            DownloadTarget task = Aria.download(context).load(downloadUrl);
//            if (task != null && task.getTaskState() == IEntity.STATE_RUNNING) {
//                task.stop();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 倒计时
     */
    public void countDownTimer(final TextView tv, long full_second, SelfCountDownTimer countDownUtil) {
        countDownUtil = new SelfCountDownTimer(full_second * 1000, 1000, (int) full_second) {
            @Override
            public void onTimerRest() {
                tv.setText("");
            }

            @Override
            public void onTimerTick(long millisUntilFinished, int counTime) {
                String textStr = counTime + " s";
                tv.setText("");
            }

            @Override
            public void onTimerFinish() {
                tv.setText("");
            }
        };
    }

    /**
     * 任务倒计时
     * 组装String
     * 若00:00:00后任务未完成，视为自动放弃，您可重新接受
     */
    public String assemblyString(String date) {
        String str = "若<font color='#ff2d4b'><small>" + date + "</small></font>后任务未完成，视为自动放弃，您可重新接受";
        return str;
    }

    public String assemblyStrings(String date, String notice) {
        String str = notice + "<font color='#ff2d4b'><small>" + date + "</small></font>";
        return str;
    }

    /**
     * 任务传送数据组装
     * is_succession:0:不是连续  1:连续任务 3 全部显示
     * task_type:1002平台游戏，1003 腾讯游戏，1004 小米游戏
     */
    public HashMap<String, String> setHashMap(int page, int per_page,
                                              int platform, int is_hot,
                                              int is_recommend, int about_to_begin,
                                              String task_type, int is_succession) {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", page + "");
        hashMap.put("per_page", per_page + "");
        hashMap.put("platform", platform + "");
        hashMap.put("is_hot", is_hot + "");
        hashMap.put("is_recommend", is_recommend + "");
        hashMap.put("about_to_begin", about_to_begin + "");
        hashMap.put("task_type", task_type + "");
        hashMap.put("is_succession", is_succession + "");
        return hashMap;
    }

    /**
     * json 获取key
     */
    public String getValue(String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (jsonObject != null) {
                Set<Map.Entry<String, Object>> set = jsonObject.entrySet();
                for (Map.Entry<String, Object> entry : set) {
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                    return entry.getValue().toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 格式化图片 html
     */
    public CharSequence getCharSequence(final Context context, String value, String imgName) {

        String html = value + "<img src='" + imgName + "' />";
        CharSequence c = Html.fromHtml(html, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                Drawable mipmap = context.getResources().getDrawable(
                        getResourceId(source)
                );
                mipmap.setBounds(0, 0, mipmap.getIntrinsicWidth() / 1,
                        mipmap.getIntrinsicHeight() / 1);
                return mipmap;
            }
        }, null);
        return c;
    }

    /**
     * 获取行数和一行的字数，来设置字符
     */
    public void getViewCharLines(final Context context, final TextView textView, String value) {
        final ViewTreeObserver vto = textView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
//                vto.removeGlobalOnLayoutListener(this);
                if (textView.getLineCount() > 2) {
                    int lineEndIndexOne = textView.getLayout().getLineEnd(1);
                    int lineEndIndexTwo = textView.getLayout().getLineEnd(2);
                    String text = textView.getText().subSequence(0, lineEndIndexTwo - 3) + "...";
                    textView.setText(text);
                }
            }
        });

    }

    /**
     * 根据资源的ID的变量名活的Filed的对象，使用反射机制来实现
     *
     * @param name
     * @return
     */
    public int getResourceId(String name) {
        try {
            //根据资源的ID的变量名活的Filed的对象，使用反射机制来实现
            Field f = R.mipmap.class.getField(name);
            //使用反射机制，取得并返回资源id字段
            return Integer.parseInt(f.get(null).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 设置view 背景颜色
     */
    public void setViewBackground(TextView textView, String colorValue) {
        try {
            GradientDrawable gradientDrawable = (GradientDrawable) textView.getBackground();
            gradientDrawable.setColor(Color.parseColor(colorValue));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 首页，homelist 跳转 逻辑
     */
    public void goWhere(Context context, HomeListEntity entity, String from) {
        if (entity == null) {
            return;
        }
        try {
            goNative(context, entity, from);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final int JUMP_NEW_USER_TASK = -1;//新手任务
    public static final int JUMP_TRY_PLAY = 1;//试玩赚钱
    public static final int JUMP_ASK_FRIEND = 2;//邀请赚钱
    public static final int JUMP_LIE_MAKE = 3;//躺着赚钱
    public static final int JUMP_CREDIT_CARD = 4;//办卡赚钱
    public static final int JUMP_GAME_CENTER = 5;//游戏中心
    public static final int JUMP_RECHARGE_Q = 6;//充值q币
    public static final int JUMP_WX_ASSIST = 7;//微信辅助
    public static final int JUMP_SUCCESSION_TASK = 8;//连续任务
    public static final int JUMP_SIGN_CARD = 9;//打卡赚钱
    public static final int JUMP_H5_INNER = 98;//内部WebView加载H5
    public static final int JUMP_H5_OUTER = 99;//外部浏览器加载H5
    public static final int JUMP_GAME_TASK = 11;//游戏任务
    public static final int JUMP_XIAN_WAN = 12;//闲玩任务
    public static final int JUMP_GAME_RECHARGE = 13;//游戏代充（游戏充值）
    public static final int JUMP_MI_DONG = 14;//幂动科技（简单任务）
    public static final int JUMP_XIAO_MI = 15;//小米游戏列表
    //TODO 这里移动积分兑换的id需要替换
    public static final int JUMP_EXCHANGE_CMCC = 1000025;//移动积分兑换
    public static final int JUMP_GMAE = 16;//游戏
    public static final int JUMP_FIND_RECOMMEND = 17;//推荐
    public static final int JUMP_WATCH_FOCUS = 18;//看点
    public static final int JUMP_FIND_ACT = 19;//活动
    public static final int JUMP_FIND_INFORMATION = 20;//资讯
    public static final int JUMP_FIND_GMAE = 21;//发现中的游戏

    /**
     * 点击jump跳转
     */
    public void goNative(Context context, IJump jump, String from) {
        Activity activity = (Activity) context;
        switch (Integer.valueOf(jump.getJump())) {
            case JUMP_NEW_USER_TASK://新手任务
                DialogNewbieTaskList.tryShowDialog(activity);
                NEWBIE_TASK.onEvent();
                break;
            case JUMP_TRY_PLAY://试玩赚钱
                Jump2View.getInstance().goTryplayView(context, null);
                break;
            case JUMP_ASK_FRIEND://邀请赚钱
                Jump2View.getInstance().goAskGetMoney(context, null);
                break;
            case JUMP_LIE_MAKE://躺着赚钱
                Jump2View.getInstance().tryGoLyingView(context, null);
                break;
            case JUMP_CREDIT_CARD://办卡赚钱
                Jump2View.getInstance().goCreditCardTaskList(context, null);
                break;
            case JUMP_GAME_CENTER://玩转游戏
                Jump2View.getInstance().goMainGame(context);
                break;
            case JUMP_RECHARGE_Q://充值q币
                Jump2View.getInstance().goRechargeQAct(context, from);
                break;
            case JUMP_WX_ASSIST://微信辅助
                Jump2View.getInstance().goWeb(context, jump.getUrl(), "微信二维码辅助好友注册任务");
                break;
            case JUMP_SUCCESSION_TASK://连续任务
                Jump2View.getInstance().goSequentialTaskView(context);
                break;
            case JUMP_SIGN_CARD://打卡赚钱
                Jump2View.getInstance().goSignCardAct(context, null);
                break;
            case JUMP_H5_INNER://内部WebView加载H5
                if (checkLongMao(activity, jump)) {
                    if (jump instanceof IJumpWeb) {
                        Jump2View.getInstance().goWeb(context, (IJumpWeb) jump);
                    } else {
                        Jump2View.getInstance().goWeb(context, jump.getUrl(), jump.getTitle());
                    }
                }
                break;
            case JUMP_H5_OUTER://外部浏览器加载H5
                if (checkLongMao(activity, jump))
                    Jump2View.getInstance().goWeb(context, jump.getUrl());
                break;
            case JUMP_GAME_TASK://游戏任务
                Jump2View.getInstance().goGameMakeMoney(context, 0);
                break;
            case JUMP_XIAN_WAN://闲玩任务
                Jump2View.getInstance().goXianWanWeb(context, null);
                break;
            case JUMP_GAME_RECHARGE://游戏代充（游戏充值）
                Jump2View.getInstance().goGameRecharge(activity, null);
                break;
            case JUMP_MI_DONG://幂动科技（简单任务）
                Jump2View.getInstance().goMiDong(activity, null);
                break;
            case JUMP_XIAO_MI://小米游戏列表
                Jump2View.getInstance().goXiaomiGameList(activity, null);
                break;
            case JUMP_EXCHANGE_CMCC://移动积分兑换
                Jump2View.getInstance().goActExchangeCMCC(context);
                break;
            case IDConstant.JUMP_YM://有米积分
                Jump2View.getInstance().goYm(activity);
                break;
            case IDConstant.JUMP_SIGN_SHEEP://签到小绵羊
                Jump2View.getInstance().goActSignSheep(activity);
                break;
            case IDConstant.JUMP_GUIDE_NEW_USER://新手引导图文或视频
                Jump2View.getInstance().goActGuideNewUser(activity);
                break;
            case IDConstant.JUMP_FOOT_PRINT://足迹
                Jump2View.getInstance().goActFootPrint();
                break;
            case IDConstant.JUMP_APPRENTICE_RED_PACKET://收徒红包
                Jump2View.getInstance().goActApprenticeRedPacket();
                break;
            case IDConstant.JUMP_EXCHANGE_MALL://兑换商城
                Jump2View.getInstance().goActExchangeMall();
                break;
            case IDConstant.JUMP_EVERY_DAY_SHARE://每日分享
                Jump2View.getInstance().goActEveryDayShare();
                break;
            case IDConstant.JUMP_ENTERTAINMENT_LUCK_DRAW://娱乐抽奖
                Jump2View.getInstance().goActEntertainmentLuckDraw();
                break;
            case IDConstant.JUMP_COIN_CENTER://金币中心
                Jump2View.getInstance().goActCoinCenter();
                break;
            default:
                String url = jump.getUrl();
                if (TextUtils.isEmpty(url))
                    G.showToast(R.string.coming_soon);
                else//有链接直接跳转内部h5
                    Jump2View.getInstance().goWeb(context, jump.getUrl(), jump.getTitle());
                break;

        }
    }

    //以龙猫开头的则认为是龙猫app
    public static final String LONG_MAO_APP_NAME = "龙猫";
    public static final String LONG_MAO_APP_PACKAGE_NAME = "com.cfyl.galesaur.guess";
    public static final String LONG_MAO_APP_URI = "guess://longmao";

    /**
     * 尝试跳转到龙猫竞猜
     *
     * @param activity
     * @param jump
     * @return 判断到已经安装，返回false
     */
    private boolean checkLongMao(Activity activity, IJump jump) {
        if (jump.getTitle() != null && jump.getTitle().startsWith(LONG_MAO_APP_NAME) && PackageUtil.isAppInstalled(SheepApp.getInstance(), LONG_MAO_APP_PACKAGE_NAME)) {
            try {
                PackageUtil.startApp(SheepApp.getInstance(), LONG_MAO_APP_PACKAGE_NAME);
            } catch (Exception ignore) {
                try {
                    Intent intent = Intent.parseUri(LONG_MAO_APP_URI, Intent.URI_INTENT_SCHEME);
                    intent.setComponent(null);
                    activity.startActivity(intent);
                } catch (Exception ignore2) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 注销账户
     */
    public void loginOut(final BaseActivity activity) {
        //登出

        UMConfigUtils.onProfileSignOff();
        UMConfigUtils.onEvent(UMConfigUtils.Event.USER_LOGOUT);
        UMShareAPI api = UMShareAPI.get(activity);
        api.deleteOauth(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                activity.hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                activity.hideProgress();
            }
        });

        api.deleteOauth(activity, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                activity.hideProgress();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                activity.hideProgress();
            }
        });
        SpUtils.saveToken(activity, "");
        DataUtil.getInstance().clearData();
        //删除自动审核任务中保存的数据，防止用户切换账号后直接提交
        DDProviderHelper.getInstance().deleteTaskRecord();
        ActivityManager.getInstance().finishAllActivity();
        Jump2View.getInstance().goLoginView(activity, "");

        activity.finish();
    }

    private boolean isLoadingAcceptedTaskList = false;

    /**
     * 添加应用自动审核任务
     */
    public void updateAutoCheck(TaskEty task) {
        if (AutoCheckService.IS_USE_THIS_SERVICE) {//5.0及以下设备，不管取消还是接受任务都重新更新正在运行的自动审核任务列表
            reloadAutoTaskList();
        } else {//5.1及以上设备,直接记录任务开始时间
            if (task != null && task.isAppAutoCommitTask() && !TextUtils.isEmpty(task.getPackage_names())) {//接受自动审核任务才记录
                AcceptTaskRecord lastAcceptTaskRecord = DDProviderHelper.getInstance().getAcceptTaskRecord(task.getPackage_names());
                long runTime = AppUsageManager.getInstance().getTotalTimeInForeground(task.getPackage_names());
                if (lastAcceptTaskRecord == null) {
                    AcceptTaskRecord acceptTaskRecord = new AcceptTaskRecord();
                    acceptTaskRecord.setPackageName(task.getPackage_names());
                    acceptTaskRecord.setUserId(DataUtil.getInstance().getUserId());
                    acceptTaskRecord.setAcceptTime(System.currentTimeMillis());
                    acceptTaskRecord.setRunTime(runTime);
                    DDProviderHelper.getInstance().addAcceptTaskRecord(acceptTaskRecord);//重置记录 5.1及以上使用
                } else {
                    lastAcceptTaskRecord.setRunTime(runTime);
                    DDProviderHelper.getInstance().updateAcceptTaskRecord(lastAcceptTaskRecord);
                }
            }
        }
    }

    //5.0及以下设备，不管取消还是接受任务都重新更新正在运行的自动审核任务列表
    public void reloadAutoTaskList() {
        if (AutoCheckService.IS_USE_THIS_SERVICE) {
            if (isLoadingAcceptedTaskList) {
                return;
            }
            isLoadingAcceptedTaskList = true;
            SheepApp.getInstance().getNetComponent().getApiService()
                    .returnTask(TaskAcceptedEty.IS_SUCCESSION_ALL, TaskAcceptedEty.SHOW_GAME_TASK_NO)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onError(BaseMessage baseMessage) {
                            isLoadingAcceptedTaskList = false;
                        }

                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            List<TaskAcceptedEty> list = baseMessage.getDatas(TaskAcceptedEty.class);
                            reloadAutoTaskList(list);
                            isLoadingAcceptedTaskList = false;
                        }
                    });
        }
    }

    //5.0及以下设备，正在运行的任务列表发生变化就要通知后台服务
    public void reloadAutoTaskList(List<TaskAcceptedEty> list) {
        if (AutoCheckService.IS_USE_THIS_SERVICE && !ListUtil.isEmpty(list)) {
            ArrayList<String> packageNameList = ListUtil.emptyList();
            for (TaskAcceptedEty item : list) {
                Release_task taskReleaseEty;
                TaskEty taskEty;
                if ((taskReleaseEty = item.getRelease_task()) != null && (taskEty = taskReleaseEty.getTask()) != null
                        && taskEty.isAppAutoCommitTask() && !TextUtils.isEmpty(taskEty.getPackage_names()))
                    packageNameList.add(taskEty.getPackage_names());
            }
            Jump2View.getInstance().startAutoCheckService(SheepApp.getInstance(), packageNameList);
        }
    }

    /**
     * 设置 drawLeft drawRight
     */
    public void setDraw2View(Context context, TextView view, int res, int color) {
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        view.setCompoundDrawables(drawable, null, null, null);
        view.setTextColor(context.getResources().getColor(color));
    }

    /**
     * 更新用户信息
     */
    public void getUserInfo(Context context) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);

                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        UserEntity userEntity = baseMessage.getData(UserEntity.class);
                        if (userEntity == null) {
                            return;
                        }
                        DataUtil.getInstance().setUserEntity(userEntity);
                    }
                });
    }

    /**
     * 获取重定向后的url
     */
    public void getRedirectUrl(final Handler handler, final DownLoadInfo downLoadInfo) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url1 = new URL(downLoadInfo.getMDownloadUrl());
                    HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
                    connection.setConnectTimeout(6 * 1000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode() >= 300 && connection.getResponseCode() < 400) {
                        downLoadInfo.setMDownloadUrl(connection.getHeaderField("Location"));
                        getRedirectUrl(handler, downLoadInfo);
                    } else if (connection.getResponseCode() == 200) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = downLoadInfo;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 任务详情、连续任务、子任务组装
     */
    public void bindDataTaskDetailSon(TaskChild taskChild, TextView textView, int i) {
        String state = "";
        switch (taskChild.getStatus()) {
            case 1:
            default:
                state = " (即将开始)";
                break;
            case 2:
                state = " (可领取 )";
                break;
            case 3:
                state = " (进行中 )";
                break;
            case 4:
                state = " (待审核 )";
                break;
            case 5:
                state = " (已完成 )";
                break;
            case 6:
                switch (taskChild.getAllowSubmit()) {
                    default:
                    case TaskAcceptedEty.ALLOW_SUBMIT_NO:
                        state = " (审核失败)";
                        break;
                    case TaskAcceptedEty.ALLOW_SUBMIT_YES:
                        state = " (审核失败，请重新上传截图)";
                        break;
                }
                break;
            case 7:
                state = " (已过期 )";
                break;
        }
        textView.setText(Html.fromHtml(taskChild.getName() + "<font color='#FAF632'>" + state + "</font>"));
    }

    public void bindDataTaskDetailSonStep(TaskDescEntity taskDescEntity, TextView textView, int i) {

        String state = "";
        switch (i + 1) {
            case 1:
            default:
                state = "一";
                break;
            case 2:
                state = "二";
                break;
            case 3:
                state = "三";
                break;
            case 4:
                state = "四";
                break;
            case 5:
                state = "五";
                break;
            case 6:
                state = "六";
                break;
            case 7:
                state = "七";
                break;
            case 8:
                state = "八";
                break;
            case 9:
                state = "九";
                break;
            case 10:
                state = "十";
                break;
        }
        textView.setText(Html.fromHtml("<font color='#2EC2F7'>" + "第" + state + "步：" + "</font>" + taskDescEntity.getDesc() + " "));
    }

    /**
     * 倒计时
     */
    public SelfCountDownTimer getCountDownTimer(long demoTime, final TextView textView, final String notice) {
        SelfCountDownTimer selfCountDownTimer = new SelfCountDownTimer(demoTime * 1000, 1000, (int) demoTime) {
            @Override
            public void onTimerRest() {
                textView.setText("");
            }

            @Override
            public void onTimerTick(long millisUntilFinished, int counTime) {
                textView.setText(notice);
                textView.append(TimeUtil.getHours(millisUntilFinished));
            }

            @Override
            public void onTimerFinish() {
                textView.setVisibility(View.GONE);
            }
        };
        return selfCountDownTimer;
    }

    /**
     * 重置map参数
     */
    public HashMap<View, SelfCountDownTimer> timerHashMap = new HashMap<>();

    public void getHashMap(TextView textView) {
        SelfCountDownTimer scTimer = timerHashMap.get(textView);
        if (scTimer != null) {
            scTimer.cancel();
            scTimer = null;
        }
    }

    public void addTimerHashMap(TextView textView, SelfCountDownTimer selfCountDownTimer) {
        timerHashMap.put(textView, selfCountDownTimer);
    }

    /**
     * 重置map参数
     */
    public void cancelAllTimers(HashMap<View, SelfCountDownTimer> timerHashMap) {
        if (timerHashMap == null)
            return;
        Set<Map.Entry<View, SelfCountDownTimer>> s = timerHashMap.entrySet();
        Iterator it = s.iterator();
        while (it.hasNext()) {
            try {
                Map.Entry pairs = (Map.Entry) it.next();
                SelfCountDownTimer cdt = (SelfCountDownTimer) pairs.getValue();
                cdt.cancel();
                cdt = null;
            } catch (Exception ignored) {
            }
        }
        it = null;
        s = null;
        timerHashMap.clear();
    }


    /**
     * 把homeList列表分开，例如：超维对决显示的图片是充满的，并且在绵羊头条下面
     *
     * @param allList
     * @param homeList
     * @param fullHomeList
     */
    public void splitHomeList(List<HomeListEntity> allList, List<HomeListEntity> homeList, final List<HomeListEntity> fullHomeList) {
        ListUtil.addAll(homeList, ListUtil.removeItem(allList, new ListUtil.CallBack<HomeListEntity, Boolean>() {
            @Override
            public Boolean call(HomeListEntity item) {
                boolean result = "1024".equals(item.getDesc()) || "17".equals(item.getJump());//描述为1024或者jump为17的跳转超维对决
                if (result) {
                    fullHomeList.add(item);
                }
                return !result;
            }
        }));
    }

    /**
     * 支付接口调用
     *
     * @param payInfo
     */
    public void pay(final String payInfo, final Activity activity, final AlertDialog dialog) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                final String result = alipay.pay(payInfo, true);

                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        PayResult payResult = new PayResult(result);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
//						String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                        String resultStatus = payResult.getResultStatus();
                        Jump2View.getInstance().goRechargeResultAct(activity, resultStatus);
                        if (activity instanceof GameTaskOrderListAct)
                            EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.ONFRESH_GAMETASK_ORDER_LIST_PAGE));
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }
                });
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付
     *
     * @param payInfo
     */
    public void alipay(final String payInfo, final boolean b, Observer<String> observer) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                Activity activity = ActivityManager.getInstance().currentActivity();
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, b);
                PayResult payResult = new PayResult(result);
                /**
                 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                 * docType=1) 建议商户依赖异步通知
                 */
//						String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                emitter.onNext(resultStatus);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * ACache.get(context).put("url_config", (JSONObject) urlConfig);
     * JSONObject url_config = (JSONObject)ACache.get(context).get("url_config");
     * agenturl;//代理
     * faqurl;//FAQ
     * world_cup_url;//世界杯
     * find_share_url;//发现详情分享
     * task_desc_url;//分享任务详情
     */
    public void initUrlConfigByNet(final String name, final Action1<String> action1) {
        JSONObject url_config = DataUtil.getInstance().getCacheResult(ApiKey.url, JSONObject.class);
        if (name == null || url_config == null) {
            SheepApp.getInstance()
                    .getNetComponent()
                    .getApiService()
                    .getNameUrl()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onError(BaseMessage baseMessage) {
                            if (action1 != null)
                                action1.call(null);
                        }

                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            if (action1 != null) {
                                if (name == null) {
                                    return;
                                }
                                JSONObject urlConfig = baseMessage.getData(JSONObject.class);
                                if (urlConfig == null) {
                                    action1.call(null);
                                } else {
                                    String url = urlConfig.getString(name);
                                    action1.call(url);
                                }
                            }
                        }
                    });
        } else {
            String url = url_config.getString(name);
            if (action1 != null)
                action1.call(url);
        }
    }

    /**
     * 获取详情地址
     * integer($int64)
     * 1充值订单，2取消订单
     */
    public void gameTaskPayOrGiveUp(final Activity context, final int finalPay_type, int id, final int status) {
        ViewUtil.newInstance()
                .showProgress(context);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", status);
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .gameTaskPayOrGiveUp(id, jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg() + "");
                        ViewUtil.newInstance()
                                .hideProgress(context);

                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        try {
                            ViewUtil.newInstance()
                                    .hideProgress(context);
                            if (status == 2) {
                                EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.ONFRESH_GAMETASK_ORDER_LIST_PAGE));
                                return;
                            }
                            if (finalPay_type == 1) {
                                CommonUtil.getInstance()
                                        .pay(baseMessage.getData().toString(),
                                                context,
                                                null);
                            } else {
                                EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.ONFRESH_GAMETASK_ORDER_LIST_PAGE));
                                G.showToast("充值成功!");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * md5 加密
     */
    public String encrypt2Md5(String value) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(value.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return "";
    }

    /**
     * 获取代理是否显示
     */
    public void getAgencyState(final Context context, final Action1<BaseMessage> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .agentRegion()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null) {
                            action1.call(null);
                        }
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        try {

                            if (action1 != null) {
                                action1.call(baseMessage);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 获取任务信息
     */
    public void getTaskAllDetail(int id, final Action1<BaseMessage> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getAcceptedTaskDetail(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null)
                            action1.call(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(baseMessage);
                    }
                });
    }

    public void updateUserInfo(final Action1<UserEntity> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null)
                            action1.call(null);

                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        UserEntity userEntity = baseMessage.getData(UserEntity.class);
                        if (userEntity != null) {
                            DataUtil.getInstance().setUserEntity(userEntity);
                        }
                        if (action1 != null)
                            action1.call(userEntity);
                    }
                });
    }

    public void callActionWithUserInfo(final Action1<UserEntity> action1) {
        UserEntity userEntity = DataUtil.getInstance().getUserEntity();
        if (userEntity == null) {
            updateUserInfo(action1);
        } else {
            if (action1 != null) {
                action1.call(userEntity);
            }
        }
    }

    /**
     * 判断地址是否为图片
     */
    public boolean judgeUrlPicture(String url) {
        if (TextUtils.isEmpty(url))
            return false;
        String[] strings = new String[]{"png", "jpg", "jpeg", "gif", "svg", "bmp"};
        for (String s : strings) {
            if (url.toLowerCase().endsWith(s))
                return true;
        }
        return false;
    }


    //对---游戏任务中的预约任务----进行---预约操作
    public void reservationGameTask(final Context context, final Release_task taskReleaseEty, final Action1<Integer> action1) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("device_id", DeviceUtil.getDeviceId(context));
        jsonObject.put("release_task_id", taskReleaseEty.getId());
        jsonObject.put("create_time", System.currentTimeMillis() / 1000L);//这里添加时间戳，防止用户抓包后重复使用
        jsonObject.put("app_version", String.valueOf(BuildConfig.VERSION_CODE));
        SheepApp.getInstance().getNetComponent().getApiService().acceptedTask(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (baseMessage.getCode() == 200) {
                            ViewUtil.showMsgDialog(context, new DialogConfig().setTitle("预约成功")
                                    .setMsg(String.format(Locale.CHINA, "恭喜您获得%s元绵羊币\n注意%s准时开放下载", taskReleaseEty.getBonusText(),
                                            TimeUtil.TimeStamp2Date(taskReleaseEty.getTask().getAppointment_time(), "yyyy-MM-dd\u0020HH:mm")))
                                    .setBtnLeftText("收入钱包").setBtnLeftOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if (action1 != null)
                                                action1.call(1);
                                        }
                                    }));
                        } else if (baseMessage.getCode() == 0) {
                            try {
                                if (action1 != null)
                                    action1.call(TextUtils.isEmpty(baseMessage.getData() + "") ? 0 : Integer.valueOf(baseMessage.getData() + ""));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            G.showToast(baseMessage.getMsg());
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

    public void acceptedTask(final Context context, final GameEntity gameEntity, final Action1<Integer> action1) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("device_id", DeviceUtil.getDeviceId(context));
        jsonObject.put("release_task_id", gameEntity.getRelease_task().getId());
        jsonObject.put("create_time", System.currentTimeMillis() / 1000L);//这里添加时间戳，防止用户抓包后重复使用
        jsonObject.put("app_version", String.valueOf(BuildConfig.VERSION_CODE));
        SheepApp.getInstance().getNetComponent().getApiService().acceptedTask(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        try {
                            String acceptId = baseMessage.getData(String.class);
                            try {
                                if (!TextUtils.isEmpty(acceptId))
                                    gameEntity.setAccepted_task_id(Integer.valueOf(acceptId));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            receiveAwards(context, gameEntity, action1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

    //对---游戏任务中的领取奖励
    public void receiveAward(final Context context, final GameEntity gameEntity, final Action1<Integer> action1) {
        RECEIVE_AWARD_GAME_TASK.onEvent();
        if (gameEntity.getAccepted_task_id() < 1) {
            acceptedTask(context, gameEntity, action1);
        } else {
            receiveAwards(context, gameEntity, action1);
        }


    }

    //领取奖励
    public void receiveAwards(final Context context, final GameEntity gameEntity, final Action1<Integer> action1) {
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .receive_award(gameEntity.getAccepted_task_id())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getErrorMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        //这里领取了奖励，要刷新用户信息
                        CommonUtil.getInstance().updateUserInfo(null);
                        ViewUtil.showMsgDialog(context,
                                "恭喜你获得" + gameEntity.getBonusText() + "元奖励",
                                "提示",
                                true);
                        if (action1 != null)
                            action1.call(1);
                    }
                });
    }

    private void giveUpTask(final Context context, final Release_task taskReleaseEty, final Action1<Integer> action1) {
        SheepApp.getInstance().getNetComponent().getApiService().giveUpTask(taskReleaseEty.getAccepted_task_id())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(context) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        reservationGameTask(context, taskReleaseEty, action1);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

    public void tryGiveUpTask(final Context context, final Release_task taskReleaseEty, final Action1<Integer> action1) {
        ViewUtil.showMsgDialog(context, new DialogConfig().setTitle("提示")
                .setMsg("是否放弃正在运行中的任务").setBtnRightText("否")
                .setBtnLeftText("是").setBtnLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        giveUpTask(context, taskReleaseEty, action1);
                    }
                }));
    }

    /**
     * 中间显示**
     */
    public String returnStarData(String value, int middle, int starShowNum, int endShowNum) {
        if (TextUtils.isEmpty(value))
            return "";
        if (value.length() > (starShowNum + endShowNum)) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(value.substring(0, starShowNum));
            stringBuilder.append("****");
            stringBuilder.append(value.substring(value.length() - endShowNum, value.length()));
            return stringBuilder.toString();
        }
        return value;
    }

    /**
     * 删除账号
     */
    public void deleteGameAccount(final Context context, final int id, final Action1<Integer> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);
        SheepApp.getInstance().getNetComponent().getApiService().delGameAccount(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        if (action1 != null)
                            action1.call(1);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage);
                    }
                });
    }

    /**
     * 修改游戏账号密码
     */
    public void modifyGameAccount(final Context context, final JSONObject jsonObject, final Action1<Integer> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);
        SheepApp.getInstance().getNetComponent().getApiService().editGameAccount(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        if (action1 != null)
                            action1.call(1);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage);
                    }
                });
    }

    /**
     * 获取计算可用定向消费券的数据
     */
    public void getVoucherAndRatio(final Context context, final String gameId, final Action1<BaseMessage> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getVoucherAndRatio(gameId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {

                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage.getMsg() + "");
                        if (action1 != null)
                            action1.call(baseMessage);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);

                        if (action1 != null)
                            action1.call(baseMessage);
                    }
                });
    }

    /**
     * 查询游戏账号详情
     */
    public void getGameAccountDetail(final Context context, final int gameId, final Action1<BaseMessage> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getGameAccountDetail(gameId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {

                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage.getMsg() + "");
                        if (action1 != null)
                            action1.call(null);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);

                        if (action1 != null)
                            action1.call(baseMessage);
                    }
                });
    }

    /**
     * 领取游戏账号
     */
    public void gameAccountManager(final Context context, final int task_id, final Action1<BaseMessage> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .gameAccountManager(task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {

                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage.getMsg() + "");
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        ViewUtil.newInstance().hideProgress((Activity) context);
                        try {
                            GameAccountEntity gameAccountEntity = baseMessage.getData(GameAccountEntity.class);
                            if (gameAccountEntity != null) {
                                String text = String.format(context.getResources().getString(R.string.get_game_task_success_dialog), gameAccountEntity.getDetailShowName(), gameAccountEntity.getAccount());
                                ViewUtil.showMsgDialog(context,
                                        text,
                                        "恭喜你获得" + gameAccountEntity.getDetailShowName() + "福利号");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (action1 != null)
                            action1.call(baseMessage);
                    }
                });
    }

    /**
     * 游戏任务
     */
    public void gameTask(final Context context, final String task_type, final String name, final Action1<BaseMessage> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .releaseGameTask(
                        1,
                        100,
                        0,
                        task_type,
                        name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage.getMsg());
                        if (action1 != null)
                            action1.call(null);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);

                        if (action1 != null)
                            action1.call(baseMessage);

                    }
                });
    }

    /**
     * 游戏任务
     */
    public void xiaomiGame(final Context context, int page, int per_page, final String name, final Action1<BaseMessage> action1) {
        ViewUtil.newInstance().showProgress((Activity) context);

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .xiaomiGameList(
                        page,
                        per_page,
                        1,
                        1,
                        name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);
                        G.showToast(baseMessage.getMsg());
                        if (action1 != null)
                            action1.call(null);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.newInstance().hideProgress((Activity) context);

                        if (action1 != null)
                            action1.call(baseMessage);

                    }
                });
    }

    /**
     * 充值游戏游戏任务
     */
    public void gameTaskList(final Context context, final int task_type, final String name, final Action1<BaseMessage> action1) {

        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .rechargeGameList(
                        task_type,
                        name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage.getMsg());
                        if (action1 != null)
                            action1.call(null);
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(baseMessage);

                    }
                });
    }

    /**
     * show view
     */
    public void showView(int goneOrShow, View view) {
        view.setVisibility(goneOrShow);
    }

    /**
     * 点击时间
     */
    public boolean clickTime(int intevalTime) {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > intevalTime) {
            lastClickTime = currentTime;
            return true;
        }
        return false;
    }

    /**
     * 通过反射调整tabLayout中下划线的宽度
     *
     * @param tabLayout
     */
    public void reflex(final TabLayout tabLayout, final Context context) {
        reflex(tabLayout, context, false);
    }

    /**
     * 通过反射调整tabLayout中下划线的宽度
     *
     * @param tabLayout
     */
    public void reflex(final TabLayout tabLayout, final Context context, final boolean reMeasure) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

//                    int dp10 = dip2px(tabLayout.getContext(), 10);
                    int add = context.getResources().getDimensionPixelSize(R.dimen.content_padding_10);
                    int count = mTabStrip.getChildCount();
                    int fillCount = Math.min(5, count);//一屏的个数

                    for (int i = 0; i < count; i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("textView");//com.android.support:design:28.0.0
//                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");//com.android.support:design:27.1.0
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0 || reMeasure) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        int margin = (G.WIDTH - fillCount * width - 2 * add) / (fillCount * 2);
                        params.leftMargin = margin + (i == 0 ? add : 0);
                        params.rightMargin = margin + (i + 1 == count ? add : 0);
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //设置无数据显示 为加载中
    public void resetEmptyView(View empty_view) {
        if (empty_view != null && empty_view.getVisibility() == View.VISIBLE) {
            ImageView empty_view_img = empty_view.findViewById(R.id.empty_view_img);
            if (empty_view_img == null) {
                if (BuildConfig.DEBUG) G.showToast("无数据layout中找不到ImageView");
                return;
            }
            TextView empty_view_msg = empty_view.findViewById(R.id.empty_view_msg);
            if (empty_view_msg == null) {
                if (BuildConfig.DEBUG) G.showToast("无数据layout中找不到TextView");
                return;
            }
            empty_view_img.setImageResource(R.drawable.loading_01);
            empty_view_msg.setText(R.string.loading);
        }
    }

    //设置无数据距离上面的距离
    public void setEmptyViewMargin(View empty_view, int topMargin, int bottomMargin) {
        if (empty_view != null) {
            ViewGroup.LayoutParams layoutParams = empty_view.getLayoutParams();
            if (layoutParams instanceof RelativeLayout.LayoutParams) {
                ((RelativeLayout.LayoutParams) layoutParams).topMargin = topMargin;
                ((RelativeLayout.LayoutParams) layoutParams).bottomMargin = bottomMargin;
            } else if (layoutParams instanceof LinearLayout.LayoutParams) {
                ((LinearLayout.LayoutParams) layoutParams).topMargin = topMargin;
                ((LinearLayout.LayoutParams) layoutParams).bottomMargin = bottomMargin;
            }
            empty_view.setLayoutParams(layoutParams);
        }
    }

    //设置无数据显示
    public void updateEmptyView(View empty_view, boolean showEmpty) {
        updateEmptyView(empty_view, showEmpty, false);
    }

    //设置无数据显示
    public void updateEmptyView(View empty_view, boolean showEmpty, boolean isNetImg) {
        if (empty_view == null) {
            return;
        }
        if (showEmpty) {
            empty_view.setVisibility(View.VISIBLE);
            ImageView empty_view_img = empty_view.findViewById(R.id.empty_view_img);
            if (empty_view_img == null) {
                if (BuildConfig.DEBUG) G.showToast("无数据layout中找不到ImageView");
                return;
            }
            final TextView empty_view_msg = empty_view.findViewById(R.id.empty_view_msg);
            if (empty_view_msg == null) {
                if (BuildConfig.DEBUG) G.showToast("无数据layout中找不到TextView");
                return;
            }
            if (NetUtil.isConnected(SheepApp.getInstance())) {
                if (isNetImg) {
                    GlideImageLoader.setImage(empty_view_img, ViewUtil.getNetImgByName("wushuju"));
                } else {
                    empty_view_img.setImageResource(R.mipmap.wushuju);
                }
                empty_view_msg.setText("加载中...");
                empty_view_msg.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        empty_view_msg.setText(R.string.wushuju);
                    }
                }, 1000);
            } else {
                if (isNetImg) {
                    GlideImageLoader.setImage(empty_view_img, ViewUtil.getNetImgByName("wushuju_net_error"));
                } else {
                    empty_view_img.setImageResource(R.mipmap.wushuju_net_error);
                }
                empty_view_msg.setText(R.string.wushuju_net_error);
            }
        } else {
            empty_view.setVisibility(View.GONE);
        }
    }

    /**
     * 幂动科技
     * appId为应用id，开发者可联系后台获取
     * id 用户uid
     */
    public boolean initMiDong(Activity activity, String id) {
        if (!SheepApp.getInstance().isInitMidong() && !TextUtils.isEmpty(id)) {
            SheepApp.getInstance().setInitMidong(true);
            String appId = "40";
            String cUId = String.valueOf(id);
            String appKey = "ad9a30556666207";
            AdManager.getInstance(SheepApp.getInstance()).init(activity, appId, cUId, appKey);
            return true;
        }
        return false;
    }

    public void onDestroy() {
        if (SheepApp.getInstance().isInitMidong()) {
            AdManager.getInstance(SheepApp.getInstance()).onAppExit();
        }
    }

    /**
     * 小米游戏账号领取
     */
    public void xiaomiRevieceAcctoun(TextView find_information_game_task_top, final Object item, final Activity activity) {
        XIAOMI_GAME_RECEIVE.onEvent();
        find_information_game_task_top.setText("领取福利号");
        find_information_game_task_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                JSONObject jsonObject = new JSONObject();
                if (item instanceof XiaomiGameEntity) {

                    jsonObject.put("id", ((XiaomiGameEntity) item).getId());
                } else if (item instanceof Applications) {
                    jsonObject.put("id", ((Applications) item).getId());
                }

                ViewUtil.newInstance().showProgress(activity);
                SheepApp.getInstance()
                        .getNetComponent()
                        .getApiService()
                        .receiveXiaomiAccount(jsonObject)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onError(BaseMessage baseMessage) {
                                G.showToast(baseMessage.getMsg());
                                ViewUtil.newInstance().hideProgress(activity);
                            }

                            @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                G.showToast(baseMessage.getMsg());
                                ViewUtil.newInstance().hideProgress(activity);
                                final JSONObject jsonObject1 = JSONObject.parseObject(JSONObject.toJSONString(baseMessage.getData()));
                                String text = String.format(activity.getResources().getString(R.string.get_xiaomi_game_success_dialog),
                                        jsonObject1 != null ? jsonObject1.getString("account") : "*****",
                                        jsonObject1 != null ? jsonObject1.getString("password") : "*****");

                                ViewUtil.showMsgDialog(activity,
                                        text,
                                        "恭喜你获得福利号",
                                        "截图保存",
                                        "我知道了",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                File file = ViewUtil.saveImage((View) v.getParent().getParent(), 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 {
                                                    if (jsonObject1 != null)
                                                        ViewUtil.sysSaveImage((View) v.getParent().getParent(), "小绵羊-小米", "小绵羊-小米账号");
                                                }
                                                G.showToast("已保存");
                                                EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.REFRESH_XIAOMI_GAME_LIST));
                                            }
                                        },
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                                EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.REFRESH_XIAOMI_GAME_LIST));
                                            }
                                        },
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.REFRESH_XIAOMI_GAME_LIST));
                                            }
                                        });

                            }
                        });
            }
        });
    }

    /**
     * 下载回调 状态修改
     */
    public void setEventResultViewStatus(BigEvent event, View view) {
        setEventResultViewStatus(event, view, true);
    }

    /**
     * 下载回调 状态修改
     */
    public void setEventResultViewStatus(BigEvent event, View view, boolean isShowSpeed) {
        if (event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            String url = task.getMDownloadUrl();
            TextView tvProgress = view.findViewWithTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress != null) {
                switch (event.getEventTypes()) {
                    case DOWNLOAD_RUNNING:
                        try {
                            int p = task.getMPercent();    //任务进度百分比
                            String speed = task.getAverageSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
                            if (isShowSpeed)
                                tvProgress.setText(String.format(Locale.CHINA, "%d%%(%s)", Math.abs(p), speed));//添加下载速度
                            else
                                tvProgress.setText(String.format(Locale.CHINA, "%d%%", Math.abs(p)));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case DOWNLOAD_STOP:
                        tvProgress.setText("继续下载");
                        break;
                    case DOWNLOAD_COMPLETE:
                        tvProgress.setText("安装游戏");
                        break;
                    case DOWNLOAD_CANCEL:
                        tvProgress.setText("下载取消");
                        break;
                    case DOWNLOAD_FAIL:
                        tvProgress.setText("下载失败");
                        break;
                }
            }
        }

    }

    /**
     * js 下载
     */
    public void showDownLoad(final Activity activity, String url, final String name) {
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(DIR, name) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        G.showToast("下载文件失败：" + e.getMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Activity curActivity = ActivityManager.getInstance().currentActivity();
                        if (curActivity == null)
                            curActivity = activity;
                        String suffix = name.substring(name.lastIndexOf(".") + 1);
                        switch (suffix) {
                            case ".png":
                            case ".jpg"://图片
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                Uri uri = Uri.fromFile(response);
                                intent.setData(uri);
                                curActivity.sendBroadcast(intent); // 发送广播通知相册
                                break;
                            case "apk":
                                ApkUtils.installApk(curActivity, response.getAbsolutePath());
                                break;
                        }
                        G.showToast("下载文件成功");
                    }
                });
    }

    /**
     * 获取用户未做任务金额
     */
    public void getUserNoDoingTaskMoney(final Action1<BaseMessage> action1) {

        SheepApp.getInstance().getNetComponent().getApiService().getCanReceiveAward()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(baseMessage);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(null);
                    }
                });
    }

    /**
     * 任务审核
     */
    public void staticAudit(final Action1<BaseMessage> action1) {

        SheepApp.getInstance().getNetComponent().getApiService().staticAudit()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(baseMessage);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(null);
                    }
                });
    }

    /**
     * 获取任务记录列表
     */
    public void getAudit(final Action1<BaseMessage> action1, int page, int pre_page, int type) {
        SheepApp.getInstance().getNetComponent().getApiService().acceptedTask(page, pre_page, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(baseMessage);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {

                        if (action1 != null)
                            action1.call(null);
                    }
                });
    }

    /**
     * 是否添加新手任务
     */
    public boolean addNewTask(final Activity activity, final UserEntity userEntity) {
        if (userEntity == null) {
            return false;
        }
        if (userEntity.getIs_new() == 2) { //1新用户 2老用户
            return false;
        } else {
            return true;
        }
    }

    /**
     * 设置游戏标识文本，如：现金，福利
     *
     * @param textView
     * @param taskReleaseEty
     */
    public void setTaskTagText(TextView textView, Release_task taskReleaseEty) {
        textView.setVisibility(View.VISIBLE);
        ViewUtil.setColorMapText(textView, String.format(Locale.CHINA, "%s", taskReleaseEty.getCashOrWelfare()), taskReleaseEty.getCashOrWelfare(), "#FD2D54");
        textView.setBackgroundResource(R.drawable.shape_red_stroke_rectangle_no_lb);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
        int padding = textView.getContext().getResources().getDimensionPixelSize(R.dimen.content_padding_2);
        textView.setPadding(4 * padding, padding, 4 * padding, padding);
    }

    /**
     * 唤醒业务打开app内容成功后回调
     */
    public void awakenDetail(RouserArticlesEntity item) {
        long longTime = AppUsageManager.getInstance().getAppLastUseTime(item.getPackage_name(), 0);
        int status = 2;
        if (longTime <= 0) {
            status = 1;
        } else {
            for (int i = 0; i < 31; i++) {
                if (item.getType() == i) {
                    if (System.currentTimeMillis() - i * 24 * 60 * 60 * 1000 > longTime) {
                        status = 2;
                    } else {
                        status = 1;
                    }
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("awaken_articles_id", item.getId());
        jsonObject.put("invitation_code", DataUtil.getInstance().getInvitationCode());
        jsonObject.put("status", status);
        SheepApp.getInstance().getNetComponent().getApiService().awakenDetail(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {

                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {

                    }
                });
    }

    public void clickBanner(Activity activity, int position, List<SlideshowEty> slideshowEtyLists) {
        clickBanner(activity, ListUtil.getItem(slideshowEtyLists, position));
    }

    public void clickBanner(Activity activity, SlideshowEty item) {
        if (item == null) {
            return;
        }
        UMConfigUtils.onEvent(UMConfigUtils.Event.BANNER_CLICK_HORIZONTAL);
        UMConfigUtils.IdEvent.BANNER.commit(item.getId());
        Ext ext;
        switch (item.getType()) {// 0,类型 1跳转试玩赚钱、2单个任务详情、3信用卡办理、4 H5页面、5 微信二维码任务
            case 1:
                Jump2View.getInstance().goTryplayView(activity, null);
                break;
            case 2:
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                Jump2View.getInstance().goTaskDetailView(activity, ext.getId());
                break;
            case 3:
                Jump2View.getInstance()
                        .goCreditCardTaskList(activity, 3);
                break;
            case 4:
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                if (ext.getTitle() == null)//外部浏览器加载H5
                    Jump2View.getInstance().goWeb(activity, ext.getUrl());
                else//内部WebView加载H5
                    Jump2View.getInstance().goWeb(activity, ext.getUrl(), ext.getTitle());
                break;
            case 5:
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null || ext.getUrl() == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                Jump2View.getInstance().goWeb(activity, ext.getUrl(), "微信二维码辅助好友注册任务");

                break;
            case 6://连续任务
                Jump2View.getInstance().goSequentialTaskView(activity);
                break;
            case 9://打卡赚钱
                Jump2View.getInstance().goSignCardAct(activity, null);
                break;
            case 7://玩转游戏
                Jump2View.getInstance().goMainGame(activity);
                break;
            case 11://游戏任务
                Jump2View.getInstance().goGameMakeMoney(activity, 0);
                break;
            case 12://闲玩任务
                Jump2View.getInstance().goXianWanWeb(activity, null);
                break;
            case 13://游戏代充
                Jump2View.getInstance().goGameRecharge(activity, null);
                break;
            case 14://幂动科技
                Jump2View.getInstance().goMiDong(activity, null);
                break;
            case 15://小米游戏列表
                Jump2View.getInstance().goXiaomiGameList(activity, null);
                break;
            case JUMP_GMAE://游戏详情
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                Jump2View.getInstance().goPlayGameDetail(activity, ext.getId());
                break;
            case JUMP_FIND_RECOMMEND://发现--推荐
            case JUMP_FIND_ACT://发现--活动
            case JUMP_FIND_INFORMATION://webView资讯
            case JUMP_FIND_GMAE://发现中的游戏详情
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                Jump2View.getInstance().goFindItem(activity, ext.getId());
                break;
            case JUMP_WATCH_FOCUS://看点
                ext = EntityUtils.getExtInfo(item.getExt());
                if (ext == null) {
                    G.showToast(R.string.error_data);
                    return;
                }
                Jump2View.getInstance().goWatchFocus(activity, ext.getId());
                break;
            default:
                G.showToast(R.string.coming_soon);
                break;
        }
    }

    /**
     * tag 标签绘制
     * R.drawable.shape_blue_stroke_rectangle_no_lb
     *
     * @param i -1:不限制 否者限制tag 个数
     */
    public void paintLineaLayout(Context activity, GameEntity gameEntity, LinearLayout ll_game_tag, int i, int color, int drawable) {
        List<GameListTag> gameListTagList = gameEntity.getApp().getTags();
        if (!ListUtil.isEmpty(gameListTagList)) {
            ll_game_tag.removeAllViews();
            for (int j = 0; j < gameListTagList.size(); j++) {
                if (i == -1 || i > j) {
                    String tag = gameListTagList.get(j).getName();
                    switch (tag) {
                        case "礼包":
                            color = R.color.red_FD2D54;
                            drawable = R.drawable.shape_red_stroke_rectangle_no_lb;
                            break;
                        case "福利":
                            color = R.color.yellow_D3AF57;
                            drawable = R.drawable.shape_yellow_stroke_rectangle_no_lb;
                            break;
                    }
                    if (!TextUtils.isEmpty(tag)) {
                        ll_game_tag.addView(ViewUtil.newInstance().paintView(activity, tag, color, drawable));
                    }
                } else {
                    return;
                }
            }
        }
    }

    /**
     * 玩转游戏 按钮设置
     * type 1
     * 0,--------1,已接受任务 2,正在进行中,3完成任务,4放弃任务,5任务失败,6审核失败,7提交审核,8任务已下线,9至少完成了一个任务了
     */
    public void palyGameDetailBtnValue(final Context context, final GameEntity gameEntity, final TextView detail_task_tv_center, final int type) {
        if (detail_task_tv_center == null)
            return;
        final boolean showSimpleText = detail_task_tv_center.getText().length() < 4;
        final Release_task releaseEty = gameEntity.getRelease_task();
        final TaskEty taskEty = releaseEty != null ? releaseEty.getTask() : null;
        if (releaseEty != null && taskEty != null) {//游戏任务

            if (taskEty.isGameReservationCantDownload()) {//预约
                if (gameEntity.getStatus() == 1 || gameEntity.getStatus() == 2 || gameEntity.getStatus() == 3) {
                    detail_task_tv_center.setText(DownloadTextUtl.getHasReservationText(showSimpleText));
                    detail_task_tv_center.setEnabled(false);
                } else {
                    detail_task_tv_center.setText(DownloadTextUtl.getReservationText(showSimpleText));
                    detail_task_tv_center.setEnabled(true);
                    if (type == 0) {
                        detail_task_tv_center.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                CommonUtil.getInstance().reservationGameTask(context, releaseEty, new Action1<Integer>() {
                                    @Override
                                    public void call(Integer integer) {
                                        if (integer > 0) {
                                            gameEntity.setAccepted_task_id(integer);
                                            detail_task_tv_center.setText(DownloadTextUtl.getHasReservationText(showSimpleText));
                                            detail_task_tv_center.setEnabled(false);

                                        }
                                    }
                                });
                            }
                        });

                    }
                }

            } else {
                releaseEty.getDownloadHelper().updateDownloadTaskView((Activity) context, taskEty, detail_task_tv_center, null, type);
            }
        } else if (gameEntity.getApp().isCanDownload()) {//可下载
            gameEntity.getApp().getFindAppHelper().updateDownloadTaskView((Activity) context, gameEntity.getApp(), detail_task_tv_center, type);
            detail_task_tv_center.setTag("PUBLIC_TAG_PREFIX_TEXTVIEW_LIST" + gameEntity.getApp().getDownload_link());
        } else {//预约下载
            gameEntity.getApp().getFindAppHelper().updateReservationView((Activity) context, gameEntity.getApp(), detail_task_tv_center, type);
            detail_task_tv_center.setTag("PUBLIC_TAG_PREFIX_TEXTVIEW_LIST" + gameEntity.getApp().getDownload_link());
        }
    }

    /**
     * 领取礼包
     *
     * @param item
     */
    public void receiveGiftById(final Context context, final GiftBagApp item, final Action1<Integer> action1, final String packageName) {
        SheepApp.getInstance().getNetComponent().getApiService().receiveGiftBag(item.getGift_bag().getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        String code = baseMessage.getData(String.class);
                        item.setCode(code);
                        if (action1 != null)
                            action1.call(TO_REFRESH);
                        ViewUtil.showGetWelfareDialog((Activity) context, item, packageName);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                    }
                });
    }

    /**
     * 判断是否 安装应用
     */
    public boolean isInstallApp(String packageName, String name) {
        boolean isInstalled = PackageUtil.isAppInstalled(SheepApp.getInstance(), packageName);
        if (!isInstalled) {
            G.showToast("还未安装" + name);
            return false;
        }
        return true;
    }

    /**
     * 抢任务
     */
    public void robTask(final Action1<RobTask> action1) {
        SheepApp.getInstance().getNetComponent().getApiService().getNewTask(DataUtil.getAsInt(DataKey.KEY_ORDER, 1))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        if (action1 != null) {
                            RobTask mRobTask = baseMessage.getData(RobTask.class);
                            action1.call(mRobTask);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (action1 != null) {
                            action1.call(null);
                        }
                    }
                });
    }

    public void callActionWithFriendCountAndAward(final Action1<FriendAndAwardEntity> action1) {
        FriendAndAwardEntity friendAndAwardEntity = DataUtil.getInstance().getCacheResult(ApiKey.friend_count_and_award, FriendAndAwardEntity.class);
        if (friendAndAwardEntity == null)
            SheepApp.getInstance().getNetComponent().getApiService().FriendCountAndAward()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onError(BaseMessage baseMessage) {
                            if (action1 != null)
                                action1.call(null);
                        }

                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            if (action1 != null)
                                action1.call(baseMessage.getData(FriendAndAwardEntity.class));
                        }
                    });
        else if (action1 != null)
            action1.call(friendAndAwardEntity);

    }

    /**
     * 获取时间
     */
    public long[] getLastMonth() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        int lastMonthMaxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);
        //按格式输出
        String endtime = sdf.format(c.getTime()); //上月最后一天
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-01  00:00:00");
        String starttime = sdf2.format(c.getTime()); //上月第一天
        try {
            Date dateStart = sdf.parse(starttime);
            Date datEnd = sdf.parse(endtime);
            return new long[]{dateStart.getTime(), datEnd.getTime()};
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 幂动btn赋值
     *
     * @param activity
     * @param btnInstall
     * @param data
     */
    public void setDownloadTvText(Context activity, TextView btnInstall, AdData data) {
        if (PackageUtil.isAppInstalled(activity, data.getPackage_name())) {
            btnInstall.setText("继续体验");
        } else {
            String downloadState = ACache.get(SheepApp.getInstance()).getAsString(String.format(Locale.CHINA, "%s%s", AdManager.class.getSimpleName(), data.getId()));
            if (downloadState == null) {
                btnInstall.setText("立即下载");
            } else {
                switch (downloadState) {
                    case "onDownloadStart":
                        btnInstall.setText("正在下载");
                        break;
                    case "onDownloadSuccess":
                        btnInstall.setText("立即安装");
                        break;
                    case "onDownloadFail":
                    default:
                        btnInstall.setText("立即下载");
                        break;
                }
            }
        }
    }

    /**
     * 给任务设置标签
     */
    public void setTaskTag(Context context, View itemView, Release_task taskReleaseEty, String show_type) {
        if (!TextUtils.isEmpty(show_type)) {
            switch (show_type) {
                case TASK_AUDIT:
                    TaskHelper.setTaskTagText((TextView) itemView.findViewById(R.id.item_num_tv), taskReleaseEty);
                    break;
                default:
                    TaskHelper.setTaskTypeText((TextView) itemView.findViewById(R.id.item_num_tv), taskReleaseEty);
                    TaskHelper.setTaskTagText((TextView) itemView.findViewById(R.id.item_num_tv1), taskReleaseEty);
                    TaskHelper.setNumText((TextView) itemView.findViewById(R.id.item_num_tv2), taskReleaseEty);
                    break;
            }
        } else {
            TaskHelper.setTaskTagText((TextView) itemView.findViewById(R.id.item_num_tv), taskReleaseEty);
            TaskHelper.setNumText((TextView) itemView.findViewById(R.id.item_num_tv1), taskReleaseEty);
        }
    }

    //使webView支持下载文件
    public void setDownloadListener(final Activity activity, WebView webView) {
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                LogUtil.println("setDownloadListener", "setDownloadListener", "onDownloadStart", url, userAgent, contentDisposition, mimeType);
                showDownloadDialog(activity, url);
            }
        });
    }

    //使webView支持下载文件
    public void setDownloadListener(final Activity activity, com.tencent.smtt.sdk.WebView webView) {
        webView.setDownloadListener(new com.tencent.smtt.sdk.DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                LogUtil.println("setDownloadListener", "setDownloadListener", "onDownloadStart", url, userAgent, contentDisposition, mimeType);
                showDownloadDialog(activity, url);

            }
        });
    }

    //显示下载提示框
    public void showDownloadDialog(final Activity activity, final String url) {
        final String fileName = com.sheep.gamegroup.util.FileUtil.getFileName(url);
        final File saveFile = new File(DIR, fileName);
        final boolean exists = saveFile.exists();
        ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("下载提示")
                .setMsg((exists ? "是否重新下载文件：" : "是否下载文件：") + saveFile.getAbsolutePath()).setBtnLeftText("取消下载").setBtnRightText("确认下载")
                .setBtnRightOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (exists && saveFile.delete()) {
                            LogUtil.println("setDownloadListener", "setDownloadListener", "onDownloadStart", url, saveFile.getAbsolutePath(), "成功删除原来的文件");
                        }
                        DownloadService.sysDownload(activity, url, fileName, "来自小绵羊的下载：" + fileName, fileName, "系统开始下载apk");
                    }
                }));
    }
}
