package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.utils.ApkUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.liulishuo.okdownload.StatusUtil;
import com.sheep.gamegroup.absBase.AbsChooseImageActivity;
import com.sheep.gamegroup.di.components.DaggerTaskDetailComponent;
import com.sheep.gamegroup.di.modules.TaskDetailModule;
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.greendao.download.ProcessRecord;
import com.sheep.gamegroup.greendao.download.ScreenShotRecord;
import com.sheep.gamegroup.helper.TaskHelper;
import com.sheep.gamegroup.model.api.ICallBack;
import com.sheep.gamegroup.model.api.IDownload;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogEntity;
import com.sheep.gamegroup.model.entity.Ext;
import com.sheep.gamegroup.model.entity.InputAndUrlList;
import com.sheep.gamegroup.model.entity.ScreenshotsEntity;
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.Release_task;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.presenter.TaskDetailContract;
import com.sheep.gamegroup.presenter.TaskDetailPresenter;
import com.sheep.gamegroup.usage.AppUsageManager;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DeviceUtil;
import com.sheep.gamegroup.util.DownloadTextUtl;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LocationUtils;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.PngUtil;
import com.sheep.gamegroup.util.RequestCodeConstants;
import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdpTaskDetailChildListview;
import com.sheep.gamegroup.view.adapter.TaskdetailSonListviewAdp;
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.ListenerShotService;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

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

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.model.entity.TaskChild.STATUS_RUNNING;
import static com.sheep.gamegroup.model.entity.TaskEty.INSPECT_TYPE_PERSION;
import static com.sheep.gamegroup.model.entity.TaskEty.INSPECT_TYPE_SDK;
import static com.sheep.gamegroup.model.entity.TaskEty.INSPECT_TYPE_SHEEP;
import static com.sheep.gamegroup.model.entity.TaskEty.OPEN_MODE_TYPE_APP;
import static com.sheep.gamegroup.model.entity.TaskEty.OPEN_MODE_TYPE_H5_IN;
import static com.sheep.gamegroup.model.entity.TaskEty.OPEN_MODE_TYPE_H5_OUT;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_APP;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_APPLET;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_CHANG_SI;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_CREDIT_CARD;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_SHEEP;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_TECENT;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_XIAO_MI;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_H5;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_SUCCESSION;
import static com.sheep.gamegroup.util.CommonUtil.START_TASK;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.GAME_INSTEAD_OF_RECHARGE_GET;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.RECEIVE_AWARD_GAME_TASK;

/**
 * 任务详情页面
 * Created by ljy on 2018/4/2.
 */

public class TaskDetailAct extends AbsChooseImageActivity implements TaskDetailContract.View {

    @BindView(R.id.icon_iv)
    ImageView iconIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.date_tv)
    TextView dateTv;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.detail_task_tv)
    TextView detailTaskTv;
    @BindView(R.id.web_text)
    WebView webText;
    @BindView(R.id.ll_infos)
    LinearLayout llInfos;
    @BindView(R.id.btn_task_item)
    TextView btnTaskItem;
    @BindView(R.id.btn_up_imag)
    TextView btnUpImag;
    @BindView(R.id.bottom_btn_layout)
    LinearLayout bottom_btn_layout;
    @BindView(R.id.detail_task_listview)
    MyListview detail_task_listview;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.detail_shrae_friend_layout)
    LinearLayout detail_shrae_friend_layout;
    @BindView(R.id.detail_item_layout_2)
    LinearLayout detail_item_layout_2;
    @BindView(R.id.detail_item_layout_3)
    LinearLayout detail_item_layout_3;
    @BindView(R.id.item_layout)
    View item_layout;
    /**
     * 2.6详情改版
     */
    @BindView(R.id.detail_task_recyclerview)
    MyListview detail_task_recyclerview;
    @BindView(R.id.ems_game_layout)
    RelativeLayout ems_game_layout;
    @BindView(R.id.detail_share_friend_tv)
    TextView detail_share_friend_tv;
    @BindView(R.id.taskdetail_user_use_layout)
    LinearLayout taskdetail_user_use_layout;
    @BindView(R.id.taskdetail_explain_layout)
    LinearLayout taskdetail_explain_layout;
    @BindView(R.id.item_exlpain_title)
    TextView item_exlpain_title;
    @BindView(R.id.item_exlpain_conetent)
    TextView item_exlpain_conetent;
    @BindView(R.id.item_notice)
    TextView item_notice;

    @BindView(R.id.start_task_btntv)
    TextView start_task_btntv;
    @BindView(R.id.start_task_line)
    TextView start_task_line;
    @BindView(R.id.down_task_btntv)
    TextView down_task_btntv;
    @BindView(R.id.down_task_line)
    TextView down_task_line;
    @BindView(R.id.install_task_btntv)
    TextView install_task_btntv;
    @BindView(R.id.install_task_line)
    TextView install_task_line;
    @BindView(R.id.award_task_btntv)
    TextView award_task_btntv;
    @BindView(R.id.end_of_time_tv)
    TextView end_of_time_tv;
    @BindView(R.id.num_tv)
    TextView num_tv;
    @BindView(R.id.num_tv1)
    TextView num_tv1;

    @BindView(R.id.task_detail_reward)
    TextView task_detail_reward;
    @BindView(R.id.task_detail_cancel)
    TextView task_detail_cancel;

    private Activity activity;
    @Inject
    TaskDetailPresenter presenter;

    private TaskEty taskEty;

    //通过task_id找
    private Release_task taskReleaseEty;
    //接口获取
    private TaskAcceptedEty gettaskAcceptedEty;

    private int releaseTaskId = -1;

    private int type;


    private AdpTaskDetailChildListview adpTaskDetailChildListview;
    private List<TaskChild> taskChildList = new ArrayList<>();

    //是否需要在onResume中刷新页面
    private boolean isFresh = false;

    @Override
    protected int getLayoutId() {
        return R.layout.task_detail_layout;
    }

    private boolean isFromTaskList = false;//是否是从任务记录界面过来

    @Override
    public void initView() {
        activity = this;
        isFromTaskList = getIntent().getBooleanExtra("is_from_task_list", false);
        releaseTaskId = getIntent().getIntExtra("task_id", -1);
        DaggerTaskDetailComponent.builder()
                .netComponent(SheepApp.getInstance().getNetComponent())
                .taskDetailModule(new TaskDetailModule(this))
                .build()
                .inject(this);
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitle(activity, "任务详情")
                .setTitleFinish(activity);
        downloadUtil = new DownloadUtil();
        adpTaskDetailChildListview = new AdpTaskDetailChildListview(taskChildList, activity);
        detail_task_listview.setAdapter(adpTaskDetailChildListview);
        adpTaskDetailChildListview.notifyDataSetChanged();
        bottom_btn_layout.setVisibility(View.GONE);
        ViewUtil.setDefaultText(nameTv);
        ViewUtil.setDefaultText(priceTv);
        ViewUtil.setDefaultText(dateTv);
        ViewUtil.setDefaultText(num_tv);
        if (DataUtil.IS_LISTEN_SCREEN_SHOT) {//监听小绵羊截图功能需要开启查看应用使用情况的权限
            AppUsageManager.getInstance().tryOpenLookAppUsageStatsPermission(false);
        }
    }

    @Override
    public void initListener() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        if (releaseTaskId != -1) {
            getAcceptedTaskDetail(releaseTaskId);
        }
    }

    private void loadData() {
        detail_shrae_friend_layout.setVisibility(View.VISIBLE);

        taskEty = taskReleaseEty.getTask();
        if (onResumeCount == 0) {
            if (DataUtil.IS_USE_SCREEN_SHOT && taskEty.needShotScreen()) {
                //如果要使用小绵羊截图方案，则在进入任务详情界面启动FloatShotScreenService，并获取截屏权限，并把intent data传递给FloatShotScreenService
                Jump2View.getInstance().startShotScreenFloat(SheepApp.getInstance(), null);
                DataUtil.getInstance().requestCapturePermission(activity, new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
//                    if(BuildConfig.DEBUG) G.showToast("初始化截屏数据成功");
                    }
                });
            }
        }
        ViewUtil.setText(nameTv, taskReleaseEty.getName());
        ViewUtil.setText(priceTv, String.format(Locale.CHINA, "+%s元", taskReleaseEty.getBonusText()));
        if (!taskReleaseEty.getDeadline().equals("永久")) {
            ViewUtil.setText(dateTv, String.format(Locale.CHINA, "截至日期：%s", TimeUtil.getDate(TimeUtil.FORMAT, Long.valueOf(taskReleaseEty.getDeadline()))));
        } else {
            ViewUtil.setText(dateTv, String.format(Locale.CHINA, "截至日期：%s", taskReleaseEty.getDeadline()));
        }
        ViewUtil.setText(num_tv, String.format(Locale.CHINA, "剩%s份", taskReleaseEty.getLast_num()));

        TaskHelper.setTaskTagText(num_tv, taskReleaseEty);
        TaskHelper.setNumText(num_tv1, taskReleaseEty);

        GlideImageLoader.setGameImage(iconIv, taskEty.getIcon());


        detailTaskTv.setVisibility(View.GONE);


        setSonVuewShow();

        loadOld();
        //自动审核
        if (taskEty.getInspect_type() == INSPECT_TYPE_SHEEP || DataUtil.IS_LISTEN_SCREEN_SHOT) {
            ViewUtil.setColorMapText(item_exlpain_title, getString(R.string.supplement_explain_n), "点我开启权限", "#FF0000");
            //用户可主动点击进行开启查看权限
            taskdetail_explain_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AppUsageManager.getInstance().openLookAppUsageStatsPermission();
                }
            });
            taskdetail_explain_layout.setVisibility(View.VISIBLE);
        } else {
            taskdetail_explain_layout.setVisibility(View.GONE);
        }
        /**
         * detail_task_tv 游戏任务，显示
         */
        if (taskEty.isGameTask() && taskEty.isCan_receive_account()) {
            detailTaskTv.setVisibility(View.VISIBLE);
            detailTaskTv.setText("领取福利号");
            detailTaskTv.setBackground(activity.getResources().getDrawable(R.drawable.selector_button_full_main));
        }
        //设置是否显示取消任务按钮
        if (gettaskAcceptedEty != null && (gettaskAcceptedEty.getStatus() == 1 || gettaskAcceptedEty.getStatus() == 2) &&
                taskEty.canCancelTask()) {
            task_detail_reward.setVisibility(View.GONE);
            task_detail_cancel.setVisibility(View.VISIBLE);
        } else {
            task_detail_reward.setVisibility(View.VISIBLE);
            task_detail_cancel.setVisibility(View.GONE);
        }
        updateBottom();
    }

    private static final int TASK_TYPE_INIT = -1;//初始化状态，可能是未领取，如果不是请让第一按钮处于不可见或者不可操作状态
    private static final int TASK_TYPE_COMMON_H5 = 10;//h5任务标志
    private static final int TASK_TYPE_SUCCESSION_H5_OUT = 13;//连续任务中的h5任务标志
    private static final int TASK_TYPE_SUCCESSION_H5_IN = 12;//连续任务中的h5任务标志
    private static final int TASK_TYPE_RESERVATION = 11;//游戏任务中还不可以下载任务(预约任务)-->预约游戏

    /**
     * 用户操作按钮状态与文字设置
     */
    private void updateBottom() {
        type = TASK_TYPE_INIT;
        //先复原按钮状态
        bottom_btn_layout.setVisibility(View.VISIBLE);
        btnTaskItem.setVisibility(View.VISIBLE);
        btnTaskItem.setEnabled(true);
        btnUpImag.setVisibility(View.VISIBLE);
        btnUpImag.setEnabled(true);
        //判断任务是否下线
        if (taskReleaseEty.isOffline()) {//任务已经下线
            if (gettaskAcceptedEty == null) {//无任务记录
                btnUpImag.setText(CommonUtil.TASK_OFFLINE);//第二按钮不可点击且显示状态
                btnUpImag.setEnabled(false);
                switch (taskEty.getTask_type()) {// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务 1004 小米游戏任务
                    case TASK_TYPE_H5://h5业务
                    case TASK_TYPE_APPLET://小程序
                        btnTaskItem.setVisibility(View.GONE);
                        break;
                    case TASK_TYPE_CREDIT_CARD:
                    case TASK_TYPE_CHANG_SI://信用卡与畅思任务不考虑
                        bottom_btn_layout.setVisibility(View.GONE);
                        break;
                    case TASK_TYPE_SUCCESSION://连续任务
                        switch (taskEty.getOpen_mode()) {//连续任务的打开方式 1:打开应用 2:H5内部 3:H5外部
                            case OPEN_MODE_TYPE_H5_OUT:
                            case OPEN_MODE_TYPE_H5_IN:
                                type = TASK_TYPE_COMMON_H5 + taskEty.getOpen_mode();
                                btnTaskItem.setText(START_TASK);
                                break;
                            case OPEN_MODE_TYPE_APP:
                            default:
                                setFirstBtnState();
                                break;
                        }
                        break;
                    case TASK_TYPE_GAME_SHEEP:
                    case TASK_TYPE_GAME_TECENT:
                    case TASK_TYPE_GAME_XIAO_MI://游戏任务
                        setFirstBtnState();
                        break;
                    default://试玩任务直接设置下线状态
                        setFirstBtnState();
                        break;
                }
            } else {//有任务记录
                btnUpImag.setText(CommonUtil.TASK_OFFLINE);//第二按钮不可点击且显示状态
                btnUpImag.setEnabled(false);
                switch (taskEty.getTask_type()) {// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务 1004 小米游戏任务
                    case TASK_TYPE_CREDIT_CARD:
                    case TASK_TYPE_CHANG_SI://信用卡与畅思任务不考虑
                        bottom_btn_layout.setVisibility(View.GONE);
                        break;
                    case TASK_TYPE_SUCCESSION://连续任务
                        switch (taskEty.getOpen_mode()) {//连续任务的打开方式 1:打开应用 2:H5内部 3:H5外部
                            case OPEN_MODE_TYPE_H5_OUT:
                            case OPEN_MODE_TYPE_H5_IN:
                                type = TASK_TYPE_COMMON_H5 + taskEty.getOpen_mode();
                                btnTaskItem.setText(START_TASK);
                                break;
                            case OPEN_MODE_TYPE_APP:
                            default:
                                setFirstBtnState();
                                break;
                        }
                        int failChildPosition = taskEty.getFailChildPosition();//获取第一个审核失败子任务的位置
                        if (type == DownloadUtil.STATUS_INSTALLED && failChildPosition > -1) {//已经安装并且有任务未完成的情况下
                            setSecondBtnResubmit(failChildPosition);
                            break;
                        }
                        break;
                    case TASK_TYPE_GAME_SHEEP:
                    case TASK_TYPE_GAME_TECENT:
                    case TASK_TYPE_GAME_XIAO_MI://游戏任务
                        setFirstBtnState();
                        break;
                    case TASK_TYPE_APPLET://小程序
                    case TASK_TYPE_H5://h5业务
                        btnTaskItem.setVisibility(View.GONE);
                        if (gettaskAcceptedEty.getStatus() != TaskAcceptedEty.STATUS_FINISHED) {//有任务未完成的情况下
                            setSecondBtnResubmit();
                        }
                        break;
                    default://试玩任务直接设置下线状态
                        setFirstBtnState();
                        if (type == DownloadUtil.STATUS_INSTALLED && gettaskAcceptedEty.getStatus() != TaskAcceptedEty.STATUS_FINISHED) {//已经安装并且有任务未完成的情况下
                            setSecondBtnResubmit();
                        }
                        break;
                }

            }
        } else {//任务未下线
            if (gettaskAcceptedEty == null) {//无任务记录-->显示领取任务按钮
                btnUpImag.setVisibility(View.GONE);//不显示第二按钮
                btnTaskItem.setText(CommonUtil.GET_TASK);
            } else {//有任务记录
                switch (taskEty.getTask_type()) {// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务 1004 小米游戏任务
                    case TASK_TYPE_H5://h5业务
                        type = TASK_TYPE_COMMON_H5;
                        btnTaskItem.setText(START_TASK);
                        switch (gettaskAcceptedEty.getStatus()) {
                            case 1://"已接受任务";
                            case 2:// "正在进行中";
                                break;
                            case 6://任务审核失败可以重新提交
                                setSecondBtnResubmit();
                                break;
                            case 7:// "提交审核";
                                btnUpImag.setText("正在审核");
                                btnUpImag.setEnabled(false);
                                btnTaskItem.setVisibility(View.GONE);
                                break;
                            case 3://完成任务
                                btnUpImag.setText("已完成");
                                btnUpImag.setEnabled(false);
                                btnTaskItem.setVisibility(View.GONE);
                                break;
                        }
                        break;
                    case TASK_TYPE_APPLET://小程序任务
                        btnTaskItem.setVisibility(View.GONE);
                        switch (gettaskAcceptedEty.getStatus()) {
                            case 1://"已接受任务";
                            case 2:// "正在进行中";
                                break;
                            case 6://任务审核失败可以重新提交
                                setSecondBtnResubmit();
                                break;
                            case 7:// "提交审核";
                                btnUpImag.setText("正在审核");
                                btnUpImag.setEnabled(false);
                                break;
                            case 3://完成任务
                                btnUpImag.setText("已完成");
                                btnUpImag.setEnabled(false);
                                break;
                        }
                        break;
                    case 2:
                    case 1001://信用卡与畅思任务不考虑
                        bottom_btn_layout.setVisibility(View.GONE);
                        break;
                    case TASK_TYPE_GAME_SHEEP:
                    case TASK_TYPE_GAME_TECENT:
                    case TASK_TYPE_GAME_XIAO_MI://游戏任务
                        if (taskEty.isGameReservationCantDownload()) {//游戏任务中还不可以下载任务(预约任务)-->预约游戏
                            type = TASK_TYPE_RESERVATION;
                            btnTaskItem.setText(CommonUtil.GAME_RESERVATION);
                            btnUpImag.setVisibility(View.GONE);//不显示第二按钮
                        } else {//游戏任务中可以下载的预约任务
                            setFirstBtnState();
                            setGameTaskFirstBtnState();
                        }
                        break;
                    case TASK_TYPE_SUCCESSION://连续任务
                        switch (taskEty.getOpen_mode()) {//连续任务的打开方式 1:打开应用 2:H5内部 3:H5外部
                            case OPEN_MODE_TYPE_H5_OUT:
                            case OPEN_MODE_TYPE_H5_IN:
                                type = TASK_TYPE_COMMON_H5 + taskEty.getOpen_mode();
                                btnTaskItem.setText(START_TASK);
                                break;
                            case OPEN_MODE_TYPE_APP:
                            default:
                                setFirstBtnState();
                                break;
                        }
                        setOtherTaskBtnState();
                        break;
                    default://其它任务先设置下载状态
                        setFirstBtnState();
                        setOtherTaskBtnState();
                        break;
                }
            }
        }
    }

    //设置第二按钮重新提交相关状态
    private void setSecondBtnResubmit(int failChildPosition) {
        switch (gettaskAcceptedEty.getAllowSubmit()) {
            case TaskAcceptedEty.ALLOW_SUBMIT_NO:
                btnUpImag.setEnabled(false);
                btnUpImag.setText("任务失败");
                btnUpImag.setVisibility(View.VISIBLE);
                break;
            case TaskAcceptedEty.ALLOW_SUBMIT_YES:
                btnUpImag.setEnabled(true);
                btnUpImag.setText(String.format(Locale.CHINA, "重新上传截图（第%d天）", failChildPosition + 1));
                btnUpImag.setVisibility(View.VISIBLE);
                break;
        }
    }

    //设置第二按钮重新提交相关状态
    private void setSecondBtnResubmit() {
        switch (gettaskAcceptedEty.getAllowSubmit()) {
            case TaskAcceptedEty.ALLOW_SUBMIT_NO:
                btnUpImag.setEnabled(false);
                btnUpImag.setText("任务失败");
                btnUpImag.setVisibility(View.VISIBLE);
                break;
            case TaskAcceptedEty.ALLOW_SUBMIT_YES:
                btnUpImag.setEnabled(true);
                btnUpImag.setText("重新提交");
                btnUpImag.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 设置应用自动审核的连续任务底部按钮的状态（任务未下线且有任务记录且已经安装游戏）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setAutoSuccessionTaskBottomState() {
        boolean hasChildRunning = taskEty.hasChildRunning();//有子任务正在进行
        boolean hasChildCanAccepted = taskEty.hasChildCanAccepted();//有子任务处于可领取状态

        if (hasChildRunning) {//有子任务正在进行
        } else if (hasChildCanAccepted) {//有子任务处于可领取状态
            btnUpImag.setVisibility(View.GONE);
            btnTaskItem.setText(CommonUtil.GET_TASK);//可以领取子任务
            type = TASK_TYPE_INIT;
        } else {//不能上传截图则不显示第二按钮
            btnUpImag.setVisibility(View.GONE);
        }
    }

    /**
     * 设置应用自动审核的任务底部按钮的状态（任务未下线且有任务记录且已经安装游戏）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setAutoTaskSecondBtnState() {
        setSecondBtnState();
    }

    /**
     * 设置非应用自动审核的连续任务底部按钮的状态（任务未下线且有任务记录且已经安装游戏）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setSuccessionTaskBottomState() {
        int failChildPosition = taskEty.getFailChildPosition();//获取第一个审核失败子任务的位置
        boolean hasChildFail = failChildPosition > -1;//有子任务审核失败
        boolean hasChildRunning = taskEty.hasChildRunning();//有子任务正在进行
        boolean hasChildCanAccepted = taskEty.hasChildCanAccepted();//有子任务处于可领取状态

        if (hasChildFail) {
            setSecondBtnResubmit(failChildPosition);
        } else if (hasChildRunning) {//有子任务正在进行
            btnUpImag.setText("上传截图");
        } else if (hasChildCanAccepted) {//有子任务处于可领取状态
            btnUpImag.setVisibility(View.GONE);
            btnTaskItem.setText(CommonUtil.GET_TASK);//可以领取子任务
            type = TASK_TYPE_INIT;
        } else {//不能上传截图则不显示第二按钮
            btnUpImag.setVisibility(View.GONE);
        }
    }

    /**
     * 设置连续任务与试玩任务两个按钮状态（任务未下线且有任务记录）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setOtherTaskBtnState() {
        switch (taskEty.getInspect_type()) {// 1自动审核　2手动审核 3,应用自动审核
            case INSPECT_TYPE_SDK:
                btnUpImag.setText("无需截图");//第二按钮不可点击且显示状态（sdk自动审核暂不支持）
                btnUpImag.setEnabled(false);
                break;
            case INSPECT_TYPE_PERSION:
                switch (type) {
                    case DownloadUtil.STATUS_INIT:
                    case DownloadUtil.STATUS_FINISH:
                        btnUpImag.setVisibility(View.GONE);
                        break;
                    default:
                        setOtherNormalTaskBtnState();
                        break;
                }
                break;
            case INSPECT_TYPE_SHEEP:
                btnUpImag.setText("领取奖励");
                switch (type) {
                    case DownloadUtil.STATUS_INIT:
                    case DownloadUtil.STATUS_FINISH:
                        btnUpImag.setVisibility(View.GONE);
                        break;
                    default:
                        if (taskEty.isSuccession())//连续任务
                            setAutoSuccessionTaskBottomState();
                        else
                            setAutoTaskSecondBtnState();
                        break;
                }
                break;
        }
    }

    /**
     * 设置连续任务与试玩任务两个按钮状态（任务未下线且有任务记录且是手动审核任务且已经安装应用）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setOtherNormalTaskBtnState() {
        boolean isSuccession = taskEty.isSuccession();
        if (isSuccession) {//连续任务
            setSuccessionTaskBottomState();
        } else {
            setSecondBtnState();
        }
    }

    /**
     * 设置第二个按钮状态（任务未下线且有任务记录且已经安装应用）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setSecondBtnState() {
        switch (gettaskAcceptedEty.getStatus()) {
            case TaskAcceptedEty.STATUS_ACCEPTED_TASK://"已接受任务";
            case TaskAcceptedEty.STATUS_RUNNING:// "正在进行中";
                break;
            case TaskAcceptedEty.STATUS_AUDIT_FAILURE://试玩任务审核失败可以重新提交
                setSecondBtnResubmit();
                break;
            case TaskAcceptedEty.STATUS_SUBMIT:// "提交审核";
                btnUpImag.setText("正在审核");
                btnUpImag.setEnabled(false);
                break;
            case TaskAcceptedEty.STATUS_FINISHED://完成任务
                btnUpImag.setText("已完成");
                btnUpImag.setEnabled(false);
                break;
        }
    }

    /**
     * 设置游戏任务中两个按钮的状态和文字显示（任务未下线且有任务记录）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setGameTaskFirstBtnState() {
        switch (type) {
            case DownloadUtil.STATUS_INIT:
                btnUpImag.setVisibility(View.GONE);
                btnTaskItem.setText(CommonUtil.GAME_DOWNLOAD);
                break;
            case DownloadUtil.STATUS_FINISH:
                btnUpImag.setVisibility(View.GONE);
                btnTaskItem.setText(CommonUtil.GAME_INSTALL);
                break;
            case DownloadUtil.STATUS_INSTALLED:
                if (gettaskAcceptedEty.getStatus() == 3) {
                    btnUpImag.setText(CommonUtil.GAME_RECHAGE);
                    btnUpImag.setVisibility(View.VISIBLE);
                    btnTaskItem.setText("启动游戏");
                } else {
                    btnTaskItem.setVisibility(View.GONE);
                    btnUpImag.setText("领取奖励");
                }
                break;

        }
    }

    /**
     * 设置第一按钮的状态和文字显示
     */
    private void setFirstBtnState() {
        setBtnStr(taskEty, downloadUtil, new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (o instanceof Integer) {
                    type = (int) o;
                } else if (o instanceof String) {
                    btnTaskItem.setText((String) o);
                } else if (o instanceof Boolean) {
                    btnTaskItem.setEnabled((Boolean) o);
                }
            }
        });
    }

    private void loadOld() {
        if (taskEty.isOldTask()) {
            detail_item_layout_2.setVisibility(View.VISIBLE);
            detail_item_layout_3.setVisibility(View.VISIBLE);
            detail_task_listview.setVisibility(View.VISIBLE);

            if (taskEty.getChild() != null && taskEty.getChild().size() > 0) {
                taskChildList.clear();
                taskChildList.addAll(taskEty.getChild());
            }

            webText.setWebChromeClient(new WebChromeClient() {

            });
            webText.getSettings().setJavaScriptEnabled(true);
            webText.setWebViewClient(new WebViewClient() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    view.loadDataWithBaseURL(null, request.getUrl().toString(), "text/html", "utf-8", null);
                    return true;
                }
            });
            ViewUtil.loadDataWithBaseURL(webText, taskEty.getDesc());

            if (taskChildList != null && taskChildList.size() > 0) {
                detail_task_listview.setVisibility(View.VISIBLE);
                adpTaskDetailChildListview.notifyDataSetChanged();
            } else {

                detail_task_listview.setVisibility(View.GONE);
            }
            taskSchedule();
        }

    }

    public static void setBtnStr(IDownload taskEty, DownloadUtil mDownloadTaskService, Action1<Object> action1) {
        setBtnStr(taskEty, mDownloadTaskService, action1, false);
    }

    public static void setBtnStr(IDownload taskEty, DownloadUtil mDownloadTaskService, Action1<Object> action1, boolean showSimpleText) {
        boolean isInstalled = PackageUtil.isAppInstalled(SheepApp.getInstance(), taskEty.getPackage_names());
        boolean isExistApk = !TextUtils.isEmpty(PackageUtil.isExistsFile(taskEty.getPackage_names(), taskEty.getDownload_link()));
        String buttonStr;
        action1.call(true);
        if (isInstalled) {
            action1.call(DownloadUtil.STATUS_INSTALLED);
            switch (taskEty.getTask_type()) {// 1时间试玩任务 3应用下载 1000连续任务， 1002 1003游戏任务 1002平台游戏，1003 腾讯游戏，1004 小米游戏
                case TASK_TYPE_APP:
                    buttonStr = DownloadTextUtl.getOpenApplyText(showSimpleText);
                    break;
                default:
                    buttonStr = DownloadTextUtl.getStartOpenText(showSimpleText);
                    break;
            }
        } else {
            if (taskEty.getDownload_link() == null || !taskEty.getDownload_link().startsWith("http")) {
                buttonStr = DownloadTextUtl.getNoDownloadText(showSimpleText);
                action1.call(false);
                action1.call(DownloadUtil.STATUS_INIT);
            } else {
                DownLoadInfo downLoadInfo = mDownloadTaskService.getDownloadTaskByUrl(taskEty);
                Integer mStatus = downLoadInfo.getMStatus();
                int taskState = mStatus == null ? 0 : mStatus;
                switch (taskState) {
                    case DownloadUtil.STATUS_ING:
                        action1.call(DownloadUtil.STATUS_INIT);
                        buttonStr = DownloadTextUtl.getProgressText(showSimpleText, downLoadInfo);
                        break;
                    case DownloadUtil.STATUS_PAUSE:
                        action1.call(DownloadUtil.STATUS_INIT);
                        buttonStr = DownloadTextUtl.getContinueDownloadText(showSimpleText);
                        break;
                    case DownloadUtil.STATUS_FINISH:
                        if (isExistApk) {
                            action1.call(DownloadUtil.STATUS_FINISH);
                            buttonStr = DownloadTextUtl.getStartInstallText(showSimpleText);
                        } else {
                            action1.call(DownloadUtil.STATUS_INIT);
                            buttonStr = DownloadTextUtl.getStartDownloadText(showSimpleText);
                        }
                        break;
                    case DownloadUtil.STATUS_FAIL:
                        action1.call(DownloadUtil.STATUS_INIT);
                        buttonStr = DownloadTextUtl.getFailDownloadText(showSimpleText);
                        break;
                    default:
                        action1.call(DownloadUtil.STATUS_INIT);
                        buttonStr = DownloadTextUtl.getStartDownloadText(showSimpleText);
                        break;
                }
            }
        }
        action1.call(buttonStr);
    }

    /**
     * 下载模块修改
     */
    private DownloadUtil downloadUtil;

    @OnClick({R.id.detail_task_tv, R.id.web_text, R.id.ll_infos, R.id.btn_task_item, R.id.btn_up_imag, R.id.detail_share_friend_tv, R.id.task_detail_cancel})
    public void onViewClicked(View view) {
        try {
            switch (view.getId()) {
                case R.id.detail_task_tv://查看任务截图
                    lookScreenShot();
                    break;
                case R.id.web_text:
                    break;
                case R.id.ll_infos:
                    break;
                case R.id.btn_task_item:
                    onClickFirstBtn();
                    break;
                case R.id.btn_up_imag:
                    onClickSecondBtn();
                    break;
                case R.id.detail_share_friend_tv:
                    if(taskReleaseEty != null){
                        Jump2View.getInstance().tryShare(activity, "task_desc_url", "task_id", releaseTaskId);
                    } else {
                        Jump2View.getInstance().tryShare(activity, "task_desc_url", "task_id", releaseTaskId,
                                String.format(Locale.CHINA, "邀你来玩【%s】，获%s元礼金，还有更多礼金相送", taskReleaseEty.getName(), taskReleaseEty.getBonusText()));
                    }
                    break;
                case R.id.task_detail_cancel://尝试取消任务
                    if (gettaskAcceptedEty != null && gettaskAcceptedEty.getId() > 0)
                        取消任务(gettaskAcceptedEty.getId(), new Action1<Integer>() {
                            @Override
                            public void call(Integer integer) {
                                hideProgress();
                                gettaskAcceptedEty = null;
                                taskReleaseEty = null;
                                CommonUtil.getInstance().updateAutoCheck(null);
                                presenter.taskDesc(releaseTaskId);
                            }
                        });
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            G.showToast(e.getMessage());
        }
    }

    /**
     * 查看截图
     */
    private void lookScreenShot() {
        if (taskEty.isGameTask() && taskEty.isCan_receive_account()) {

            GAME_INSTEAD_OF_RECHARGE_GET.onEvent();
            CommonUtil.getInstance()
                    .gameAccountManager(activity, Integer.parseInt(taskReleaseEty.getTask_id()), new Action1<BaseMessage>() {
                        @Override
                        public void call(BaseMessage baseMessage) {
                            G.showToast("领取成功");
                            initData();
                        }
                    });
            return;
        }
        if (gettaskAcceptedEty == null || TextUtils.isEmpty(gettaskAcceptedEty.getScreenshots())) {
            G.showToast("任务截图为空");
            return;
        }
        Jump2View.getInstance().showImgs(activity, 0, gettaskAcceptedEty.getScreenshots());
    }

    /**
     * 点击第二按钮
     */
    private void onClickSecondBtn() {
        if (gettaskAcceptedEty != null && gettaskAcceptedEty.getStatus() == 3 && taskEty.isGameTask()) {
            if (taskEty.getThird_task_id() != null) {
                ViewUtil.showGamePayAccount(activity, taskEty.getThird_task_id(), taskReleaseEty.getName());
            }
        } else if (taskEty.isGameTask()) {
            if (taskEty.isGameReservationCantDownload()) {
                CommonUtil.getInstance().reservationGameTask(activity, taskReleaseEty, new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        isFresh = true;
                        freshData();
                    }
                });
            } else {
                accepteReceiveAward();
            }
        } else if (taskEty.isAppAutoCommitTask()) {//应用自动审核任务
            try {
                checkAndCommitTask();
            } catch (Exception e) {
                e.printStackTrace();
                G.showToast(e.getMessage());
            }
        } else {//截图任务
            commitScreenShot();
        }
    }

    /**
     * 点击第一按钮
     */
    private void onClickFirstBtn() {
        switch (type) {
            case TASK_TYPE_INIT:
                if (taskReleaseEty.getAccepted_task_id() > 0) {
                    Jump2View.getInstance()
                            .goNoticeAct(activity, new DialogEntity(null,
                                    "是否放弃正在运行中的任务?",
                                    "是",
                                    "否",
                                    null));
                } else {
                    acceptedTask();
                }
                break;
            case DownloadUtil.STATUS_INIT://开始下载
                final DownloadTask task;
                if (TextUtils.isEmpty(taskEty.getDownload_link()) || !taskEty.getDownload_link().contains("http")) {
                    G.showToast(R.string.error_download_link);
                    return;
                }
                task = DownloadUtil.getTask(taskEty);
                final StatusUtil.Status statusOnStore = StatusUtil.getStatus(task);
                final DownLoadInfo downLoadInfo = downloadUtil.getDownloadTaskByUrl(taskEty);
                switch (statusOnStore) {
                    case RUNNING:
                    case PENDING://等待的
                        OkDownload.with().downloadDispatcher().cancel(task);
                        break;
                    case IDLE://空闲的
                    case UNKNOWN:
                        downloadUtil.start(downLoadInfo);
                        break;
                    case COMPLETED://有可能之前已经下载完成，但是数据库里已经没有数据了，这时只需要修改状态
                        if (task.getFile() != null) {
                            if(downloadUtil.checkFinish(downLoadInfo)) {//检查文件是否真的完成
                                downloadUtil.setDownloadTaskFinish(task.getUrl(), task.getFile().getAbsolutePath());
                            } else {//重新开始下载
                                downloadUtil.delete(downLoadInfo);
                                downloadUtil.start(downloadUtil.getDownloadTaskByUrl(taskEty));
                                downloadUtil.setDownloadTaskStatus(taskEty.getDownload_link(), DownloadUtil.STATUS_INIT);
                            }
                        }
                        updateBottom();
                        break;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (downloadUtil.addDownloadTask(downLoadInfo)) {
                            //发送红点信息
                            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.TIPS_DOWN_ICON));
                        }
                    }
                }).start();
                UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_DOWNLOAD);
                break;
            case DownloadUtil.STATUS_FINISH:
                ApkUtils.installApk(SheepApp.getInstance(), PackageUtil.isExistsFile(taskEty.getPackage_names(), taskEty.getDownload_link()));
                break;
            case DownloadUtil.STATUS_INSTALLED:
                PackageUtil.startApp(SheepApp.getInstance(), taskEty.getPackage_names());
                break;
            case TASK_TYPE_COMMON_H5://h5任务跳转h5页面
                Ext ext;
                if (taskEty == null || (ext = EntityUtils.getExtInfo(taskEty.getExt())) == null || TextUtils.isEmpty(ext.getUrl())) {
                    G.showToast(R.string.service_data_error);
                } else {
                    Jump2View.getInstance().goWeb(activity, ext.getUrl());
                }
                break;
            case TASK_TYPE_SUCCESSION_H5_OUT://连续任务中的h5任务跳转h5页面,这里服务器返回的连接放到了下载链接里
                if (taskEty == null || TextUtils.isEmpty(taskEty.getDownload_link())) {
                    G.showToast(R.string.service_data_error);
                } else {
                    Jump2View.getInstance().goWeb(activity, taskEty.getDownload_link());
                }
                break;
            case TASK_TYPE_SUCCESSION_H5_IN://连续任务中的h5任务跳转h5页面,这里服务器返回的连接放到了下载链接里
                if (taskEty == null || TextUtils.isEmpty(taskEty.getDownload_link())) {
                    G.showToast(R.string.service_data_error);
                } else {
                    Jump2View.getInstance().goWeb(activity, taskEty.getDownload_link(), taskEty.getTask_name());
                }
                break;
        }
    }

    /**
     * 发起选择图片来上传截图
     */
    private void commitScreenShot() {
        switch (taskEty.getTask_type()) {
            case TASK_TYPE_SUCCESSION://连续任务
                commitScreenShotTaskId = taskEty.getCanCommitChildRelease_task_id();
                break;
            default:
                commitScreenShotTaskId = gettaskAcceptedEty.getId();
                break;
        }
        if (commitScreenShotTaskId > 0) {
            if(!TextUtils.isEmpty(taskEty.getUnique_identification())){//需要提交自定义字段
                Jump2View.getInstance().goActInputAndPickerImg(this, taskEty.getUnique_identification());
            }else {
                if (DataUtil.IS_USE_ALL_IMAGE) {//可以上传任意图片
                    showChooseDialog(false, true, DEFAULT_MAX_COUNT);
                } else if ((DataUtil.IS_USE_SCREEN_SHOT || DataUtil.IS_LISTEN_SCREEN_SHOT) && taskEty.needShotScreen()) {//小绵羊截图方案与监听方案
                    if (ListenerShotService.IS_RECORD_PATH) {//使用记录的方式来获取用户的截图
                        List<ScreenShotRecord> list = DDProviderHelper.getInstance().getScreenShotRecordList(taskEty.getPackage_names());
                        showChooseListDialog(false, true, DEFAULT_MAX_COUNT, ListUtil.asList(new ListUtil.CallBack<ScreenShotRecord, String>() {
                            @Override
                            public String call(ScreenShotRecord screenShotRecord) {
                                return screenShotRecord.getPath();
                            }
                        }, list, new ListUtil.CallBack<ScreenShotRecord, Boolean>() {
                            @Override
                            public Boolean call(ScreenShotRecord screenShotRecord) {
                                return new File(screenShotRecord.getPath()).exists();
                            }
                        }));
                    } else {
                        File dir = DataUtil.getScreenShotsDir(taskEty.getPackage_names());
                        showChooseDialog(false, true, DEFAULT_MAX_COUNT, dir);
                    }
                } else {//用户手动截图方案
                    ArrayList<String> imageUriList = DataUtil.getAllScreenShotList();

                    showChooseDialog(false, true, DEFAULT_MAX_COUNT, imageUriList);
                }
            }
        } else {
            G.showToast("暂无任务可以上传");
        }
        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_UPLOAD_PICTURE);
    }

    /**
     * 尝试提交应用自动审核任务
     */
    private void checkAndCommitTask() {
        if (taskEty != null && taskReleaseEty != null) {
            if (TextUtils.isEmpty(taskEty.getPackage_names())) {
                G.showToast(R.string.error_package_link);
                return;
            }
            String gps = LocationUtils.getInstance().getLongitudeLatitude();
            JSONObject object = new JSONObject();
            object.put("gps", gps);
            if (AutoCheckService.IS_USE_THIS_SERVICE) {
                ProcessRecord processRecord = DDProviderHelper.getInstance().getProcessRecord(taskEty.getPackage_names());
                object.put("task_time", processRecord.getRunTime());
                LogUtil.println(1, "checkAndCommitTask", processRecord.getRunTime());
                if (processRecord.getId() != null) {
                    processRecord.setRunTime(0);
                    DDProviderHelper.getInstance().addOrUpdateProcessRecord(processRecord);//重置记录 5.0及以下使用
                }
            } else {
                long runTime = AppUsageManager.getInstance().getTotalTimeInForeground(taskEty.getPackage_names());
                if (runTime == AppUsageManager.NOT_OPEN_USAGE_STATS) {//获取不到应用使用情况，提示用户开启权限
                    AppUsageManager.getInstance().showAccessibilityDialog();
                    return;
                }
                AcceptTaskRecord acceptTaskRecord = DDProviderHelper.getInstance().getAcceptTaskRecord(taskEty.getPackage_names());
                if (acceptTaskRecord == null) {
                    object.put("task_time", 0);
                    LogUtil.println(2, "checkAndCommitTask", 0);
                    acceptTaskRecord = new AcceptTaskRecord();
                    acceptTaskRecord.setPackageName(taskEty.getPackage_names());
                    acceptTaskRecord.setUserId(DataUtil.getInstance().getUserId());
                    acceptTaskRecord.setAcceptTime(System.currentTimeMillis());
                    acceptTaskRecord.setRunTime(runTime);
                    DDProviderHelper.getInstance().addAcceptTaskRecord(acceptTaskRecord);//重置记录 5.1及以上使用
                } else {
                    object.put("task_time", runTime < 0 || runTime < acceptTaskRecord.getRunTime() ? 0 : (runTime - acceptTaskRecord.getRunTime()) / 1000L);
                    LogUtil.println(3, "checkAndCommitTask", runTime, acceptTaskRecord.getRunTime());
                    acceptTaskRecord.setRunTime(runTime);
                    DDProviderHelper.getInstance().updateAcceptTaskRecord(acceptTaskRecord);//重置记录 5.1及以上使用
                }
            }

            object.put("release_task_id", taskReleaseEty.getId());
            object.put("create_time", System.currentTimeMillis() / 1000L);//这里添加时间戳，防止用户抓包后重复使用
            addCanCommitTaskChildId(object, taskEty);
            SheepApp.getInstance().getNetComponent().getApiService().commitAutoTask(object)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(getApplicationContext()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            CommonUtil.getInstance().updateAutoCheck(null);
                            //这里领取了奖励，要刷新用户信息
                            CommonUtil.getInstance().updateUserInfo(null);
                            String amount = taskReleaseEty.getBonusText();
                            try {
                                Map h = JSON.parseObject(baseMessage.getData() + "");

                                amount = h.get("amount") + "";
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            G.showToast(String.format(Locale.CHINA, "恭喜你，任务已完成，获得奖励%s元", TextUtils.isEmpty(amount) ? taskReleaseEty.getBonusText() : amount));
                            finish();
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            G.showToast(baseMessage);
                        }
                    });
        } else {
            G.showToast(R.string.unknown_error);
        }
    }

    /**
     * 连续任务在自动审核任务领取任务时添加子任务id参数
     *
     * @param object
     * @param taskEty
     */
    private void addCanAcceptedTaskChildId(JSONObject object, TaskEty taskEty) {
        switch (taskEty.getTask_type()) {
            case TASK_TYPE_SUCCESSION://连续任务
                int task_child_id = taskEty.getCanAcceptedChildId();
                object.put("task_child_id", task_child_id);
                break;
        }
    }

    /**
     * 连续任务在自动审核任务领取奖励时添加子任务id参数
     *
     * @param object
     * @param taskEty
     */
    private void addCanCommitTaskChildId(JSONObject object, TaskEty taskEty) {
        switch (taskEty.getTask_type()) {
            case TASK_TYPE_SUCCESSION://连续任务
                TaskChild task_child = taskEty.getCanCommitChild(STATUS_RUNNING);
                if (task_child != null)
                    object.put("task_child_id", task_child.getId());
                break;
        }
    }

    /**
     * 任务进度
     */
    private void taskSchedule() {
        llInfos.removeAllViews();
        if (taskEty != null) {
            int thisRun = taskEty.getRunTask();
            if (thisRun == 1) {//接受了任务
                llInfos.addView(getStep(CommonUtil.GET_TASK, "已完成", 0));
                if (taskEty.getTask_type() == TASK_TYPE_CREDIT_CARD) {//信用卡
                    llInfos.addView(getStep("信用卡注册", "待完成", 0));
                } else if (PackageUtil.isAppInstalled(SheepApp.getInstance(), taskEty.getPackage_names())) {
                    llInfos.addView(getStep("APP下载", "已完成", 0));
                    llInfos.addView(getStep("完成任务", "进行中", 1));
                } else {
                    llInfos.addView(getStep("APP下载", "待完成", 2));
                }
            } else {
                llInfos.addView(getStep(CommonUtil.GET_TASK, "待完成", 2));
            }
        } else {
            llInfos.addView(getStep(CommonUtil.GET_TASK, "待完成", 2));
        }
    }


    private View getStep(String step, String state, int color) {
        View view = View.inflate(this, R.layout.task_step_info, null);
        ImageView img = view.findViewById(R.id.img_tab);
        TextView tvStep = view.findViewById(R.id.tv_step);
        TextView tvStatus = view.findViewById(R.id.tv_status);
        if (color == 0) {
            img.setImageResource(R.drawable.garden_green);
            tvStep.setTextColor(getResources().getColor(R.color.green));
            tvStatus.setTextColor(getResources().getColor(R.color.green));
        } else if (color == 1) {
            img.setImageResource(R.drawable.garden_yellow);
            tvStep.setTextColor(getResources().getColor(R.color.yellow_text_light));
            tvStatus.setTextColor(getResources().getColor(R.color.yellow_text_light));
        } else {
            img.setImageResource(R.drawable.garden_gray);
            tvStep.setTextColor(getResources().getColor(R.color.black_text_gray));
            tvStatus.setTextColor(getResources().getColor(R.color.black_text_gray));
        }

        tvStep.setText(step);
        tvStatus.setText(state);
        return view;
    }


    @Override
    public void taskStatusSuccess(BaseMessage baseMessage) {
        setLoaddingText("完成");
//                            onGetNetImageUrl(data);
        dismissLoaddingDialog();
        G.showToast("提交成功，等待审核!");
        if ((DataUtil.IS_USE_SCREEN_SHOT || DataUtil.IS_LISTEN_SCREEN_SHOT) && taskEty.needShotScreen()) {//小绵羊截图方案或者监听方案：上传截图成功后删除之前的截图
            if (!TextUtils.isEmpty(taskEty.getPackage_names())) {
                DataUtil.getInstance().clearScreenShots(taskEty.getPackage_names());
            }
        }
        UMConfigUtils.finishTask();
        if (taskEty.hasCommitLast(commitScreenShotTaskId)) {//非自动审核任务中的连续任务已经提交了最后一个子任务，或者普通任务提交截图成功
            if (isFromTaskList)//之前界面为任务记录界面，需要回调刷新任务记录列表
                setResult(RESULT_OK);
            finish();
        } else {
            isFresh = true;
            freshData();
        }
    }

    @Override
    public void taskStatusFaile(BaseMessage baseMessage) {
        updateError("失败");
        G.showToast(baseMessage.getMsg() + "");

    }

    @Override
    public void taskDescSuccess(BaseMessage baseMessage) {
        hideProgress();
        empty_view.setVisibility(View.GONE);
        taskReleaseEty = baseMessage.getData(Release_task.class);
        loadData();
    }

    @Override
    public void taskDescFaile(BaseMessage baseMessage) {
        hideProgress();
        G.showToast(baseMessage.getMsg() + "");
        CommonUtil.getInstance().updateEmptyView(empty_view, true);
    }


    @Override
    protected void onNotGetImage(String msg) {
        G.showToast(msg);

    }

    @Override
    protected void onGetImage(String path) {

    }

    private ICallBack<Boolean> callBack = new ICallBack<Boolean>() {
        @Override
        public Boolean call(@CALL_BACK_TYPE int type, Object... args) {
            String imagePath = (String) args[0];
            switch (type) {
                case IS_RECORD:
                    if (DDProviderHelper.getInstance().getScreenShotRecord(taskEty.getPackage_names(), imagePath) != null) {
                        return true;
                    }
                    break;
                case DECODE_PNG:
                    int size = (int) args[1];
                    int index = (int) args[2];
                    try {
                        //加密文本内容：包名;签名md5;试玩应用包名;试玩应用签名md5;用户token;任务id;图片总数;图片位置
                        PngUtil.decodePng(imagePath, taskEty.getPackage_names(), String.format(Locale.CHINA, "%s;%d;%d;%d", SpUtils.getToken(SheepApp.getInstance()), commitScreenShotTaskId, size, index));
                        return true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
            return false;
        }
    };

    /**
     * 上传图片前的回调
     *
     * @return
     */
    protected ICallBack<Boolean> getCallBack() {
        if ((DataUtil.IS_USE_SCREEN_SHOT || DataUtil.IS_LISTEN_SCREEN_SHOT) && taskEty.needShotScreen()) {//小绵羊截图方案或者监听方案：上传截图成功后删除之前的截图
            return callBack;
        }
        return null;
    }

    private int commitScreenShotTaskId;

    private String unique_identification;
    @Override
    protected void onSetNetImageUrl(String data) {
        setLoaddingText("提交中");
        commitScreenShotData(data, unique_identification);
        unique_identification = null;
    }
    //提交截图数据
    private void commitScreenShotData(String data, String unique_identification) {
        presenter.taskStatus(commitScreenShotTaskId, data+"", "",taskEty.getPackage_names(), String.valueOf(TaskAcceptedEty.STATUS_SUBMIT), SysAppUtil.getUserAgentOrDeviceInfo(), unique_identification);
        taskEty.setScreenshots(data);
    }

    @Override
    protected void onGetNetImageUrl(String url) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    if (taskReleaseEty != null && taskReleaseEty.getAccepted_task_id() > 0) {
                        取消任务(taskReleaseEty.getAccepted_task_id(), new Action1<Integer>() {
                            @Override
                            public void call(Integer integer) {
                                taskReleaseEty.setAccepted_task_id(0);
                                CommonUtil.getInstance().updateAutoCheck(null);
                                acceptedTask();
                            }
                        });
                    }
                }
                break;
            case 101:
                //图片展示
                isFresh = true;
                break;
            case RequestCodeConstants.REQUEST_CODE_GE_DATA:
                if(resultCode == RESULT_OK) {
                    Object object = DataUtil.getInstance().getData(InputAndUrlList.class.getSimpleName());
                    if(TestUtil.isDev()) LogUtil.println("GET_DATA", JSONObject.toJSONString(object));
                    if(object instanceof InputAndUrlList) {
                        unique_identification = ((InputAndUrlList) object).getInput();
                        //上传图片
                        photoCount = DEFAULT_MAX_COUNT;
                        photos = ((InputAndUrlList) object).getList();
                        upImages();
                    } else
                        G.showToast(R.string.coming_soon);
                }
                break;
            default:
                DataUtil.getInstance().onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    private void 取消任务(int id, final Action1<Integer> action1) {
        showProgress(true);
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .giveUpTask(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage);
                    }

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

    /**
     * 领取任务
     */
    private void acceptedTask() {
        showProgress(true);
        int release_task_id = taskReleaseEty.getId();
        String device_id = DeviceUtil.getDeviceId(SheepApp.getInstance());
        UMConfigUtils.Event.TASK_ACCEPT.onEvent("device_id", device_id, "release_task_id", release_task_id);
        JSONObject object = new JSONObject();
        object.put("device_id", device_id);
        object.put("release_task_id", release_task_id);
        object.put("create_time", System.currentTimeMillis() / 1000L);//这里添加时间戳，防止用户抓包后重复使用
        object.put("app_version", String.valueOf(BuildConfig.VERSION_CODE));
        addCanAcceptedTaskChildId(object, taskEty);
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .acceptedTask(object)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage.getErrorMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {//领取任务成功
                        hideProgress();
                        taskReleaseEty.setIs_running(true);
                        taskReleaseEty.getTask().setRelease_task_id(taskReleaseEty.getId());
                        CommonUtil.getInstance().updateAutoCheck(taskReleaseEty.getTask());

                        getAcceptedTaskDetail(releaseTaskId);

                    }
                });
    }


    public void freshData() {
        if (releaseTaskId != -1 && isFresh) {
            isFresh = false;
            getAcceptedTaskDetail(releaseTaskId);
        }
    }

    private int onResumeCount = 0;

    @Override
    protected void onResume() {
        super.onResume();
        if (onResumeCount > 0) {//第一次不加载
            if (taskReleaseEty == null || isFresh) {
                isFresh = true;
                freshData();
            } else {
                updateBottom();
            }
        }
        onResumeCount++;
    }

    /**
     * 子任务模块显示
     */
    TaskdetailSonListviewAdp sonListviewAdp;

    private void setSonVuewShow() {
        boolean isSuccession = false;
        item_layout.setBackgroundResource(R.drawable.sp_bg_white_solid_top);
        detail_task_recyclerview.setVisibility(View.GONE);
        ems_game_layout.setVisibility(View.GONE);
        taskdetail_user_use_layout.setVisibility(View.GONE);
        taskdetail_explain_layout.setVisibility(View.GONE);
        switch (taskEty.getTask_type()) {
            case TASK_TYPE_SUCCESSION://连续任务
                if (taskEty.getChild() != null && taskEty.getChild().size() > 0 && taskEty.getChild().get(0).getDescEntityList() != null) {
                    detail_task_recyclerview.setVisibility(View.VISIBLE);
                    detail_item_layout_2.setVisibility(View.GONE);
                    detail_item_layout_3.setVisibility(View.GONE);
                    detail_task_listview.setVisibility(View.GONE);

                    taskdetail_explain_layout.setVisibility(View.VISIBLE);
                    item_exlpain_conetent.setText(getString(R.string.supplement_explain));
                    sonListviewAdp = new TaskdetailSonListviewAdp(taskEty.getChild(), activity);
                    TaskHelper.setSelectFlag(taskEty);
                    detail_task_recyclerview.setAdapter(sonListviewAdp);
                    isSuccession = true;
                } else {

                    isSuccession = false;
                }

                break;
            case TASK_TYPE_GAME_SHEEP:
            case TASK_TYPE_GAME_TECENT:
            case TASK_TYPE_GAME_XIAO_MI://游戏任务
                ems_game_layout.setVisibility(View.VISIBLE);
                detail_shrae_friend_layout.setVisibility(View.GONE);
                item_layout.setBackgroundResource(R.drawable.x_shap_shadow_bg_rectgangle_white);
                taskdetail_explain_layout.setVisibility(View.VISIBLE);
                item_notice.setVisibility(View.VISIBLE);
                item_exlpain_title.setText(getString(R.string.warm_prompt_n));
                item_exlpain_conetent.setText(getString(R.string.warm_prompt_content));
                break;
            default:

                break;
        }

        //非连续任务且非游戏任务且应用自动审核时长任务  使用TaskdetailSonListviewAdp显示单个任务详情
        if (!isSuccession && !ListUtil.isEmpty(taskEty.getDescEntityList())) {
            List<TaskChild> descEntityArrayList = new ArrayList<>();
            TaskChild taskChild = new TaskChild();
            taskChild.setDescEntityList(taskEty.getDescEntityList());
            if (!taskEty.isGameTask() && !taskEty.isAppAutoCommitTask()) {
                List<ScreenshotsEntity> listS = new ArrayList<>();
                if (taskEty.getDescEntityList() != null && taskEty.getDescEntityList().size() > 0) {
                    listS.clear();
                    for (TaskDescEntity descEntity : taskEty.getDescEntityList()) {
                        if (!TextUtils.isEmpty(descEntity.getImg())) {
                            ScreenshotsEntity screenshotsEntity = new ScreenshotsEntity();
                            screenshotsEntity.setImg(descEntity.getImg());
                            screenshotsEntity.setDesc(descEntity.getDesc());
                            listS.add(screenshotsEntity);
                        }
                    }
                }
                if (listS.size() > 0) {
                    taskChild.setScreenshotsList(listS);
                } else {
                    taskChild.setScreenshotsList(taskEty.getScreenshotsList());
                }
            }
            descEntityArrayList.add(taskChild);
            detail_task_recyclerview.setVisibility(View.VISIBLE);
            detail_item_layout_2.setVisibility(View.GONE);
            detail_item_layout_3.setVisibility(View.GONE);
            detail_task_listview.setVisibility(View.GONE);
            sonListviewAdp = new TaskdetailSonListviewAdp(descEntityArrayList, activity);
            detail_task_recyclerview.setAdapter(sonListviewAdp);
            if (taskEty.isApplet()) {
                sonListviewAdp.addTaskEntity(taskReleaseEty);
            }
        }

        //截至时间
        if (gettaskAcceptedEty != null && taskReleaseEty != null && gettaskAcceptedEty.isIs_running() && gettaskAcceptedEty.getEnd_time() > 0) {
            CommonUtil.getInstance().getHashMap(end_of_time_tv);

            end_of_time_tv.setVisibility(View.VISIBLE);
            SelfCountDownTimer selfCountDownTimer = CommonUtil.getInstance().getCountDownTimer(gettaskAcceptedEty.getEnd_time(), end_of_time_tv, "");
            selfCountDownTimer.reset((int) gettaskAcceptedEty.getEnd_time());
            selfCountDownTimer.start();

            CommonUtil.getInstance().addTimerHashMap(end_of_time_tv, selfCountDownTimer);
        } else {
            end_of_time_tv.setVisibility(View.GONE);
        }


    }

    /**
     * 领取奖励
     */
    private void accepteReceiveAward() {
        showProgress();
        RECEIVE_AWARD_GAME_TASK.onEvent();
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .receive_award(taskReleaseEty.getAccepted_task_id())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage.getErrorMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        hideProgress();
//                        G.showToast(taskReleaseEty.getBonusText() + "元");
                        //这里领取了奖励，要刷新用户信息
                        CommonUtil.getInstance().updateUserInfo(null);
                        ViewUtil.showMsgDialog(activity,
                                "恭喜你获得" + taskReleaseEty.getBonusText() + "元奖励",
                                "提示",
                                true);
//                        finish();
//                        initData();

//                        taskReleaseEty.getTask().setRelease_task_id(taskReleaseEty.getId());
                    }
                });
    }

    /**
     * 获取接受的任务详情
     */
    private void getAcceptedTaskDetail(final int releaseTaskId) {
        showProgress();
        CommonUtil.getInstance().getTaskAllDetail(releaseTaskId, new Action1<BaseMessage>() {
            @Override
            public void call(BaseMessage baseMessage) {
                if (baseMessage.getCode() == 0)
                    gettaskAcceptedEty = baseMessage.getData(TaskAcceptedEty.class);
                if (gettaskAcceptedEty != null)
                    taskReleaseEty = gettaskAcceptedEty.getRelease_task();
                if (taskReleaseEty == null) {
                    initTaskReleaseEty();
                } else {
                    hideProgress();
                    if (empty_view == null) {
                        return;
                    }
                    empty_view.setVisibility(View.GONE);
                    loadData();
                }
            }
        });
    }

    private void initTaskReleaseEty() {
        taskReleaseEty = DataUtil.getInstance().getCacheResult(ApiKey.releaseTaskDesc(releaseTaskId), Release_task.class);
        hideProgress();
        if (taskReleaseEty != null) {
            if (empty_view == null) {
                return;
            }
            empty_view.setVisibility(View.GONE);
            loadData();
        }
        presenter.taskDesc(releaseTaskId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        CommonUtil.getInstance().cancelAllTimers(CommonUtil.getInstance().timerHashMap);
    }


    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        if (btnTaskItem != null && event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            if (taskEty != null && TextUtils.equals(task.getMDownloadUrl(), taskEty.getDownload_link())) {
                switch (event.getEventTypes()) {
                    case DOWNLOAD_RUNNING:
                        try {
                            btnTaskItem.setText(String.format(Locale.CHINA, "%d%%(%s)", Math.abs(task.getMPercent()), task.getAverageSpeed()));//添加下载速度
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case DOWNLOAD_STOP:
                        btnTaskItem.setText(CommonUtil.CONTINUE_DOWNLOAD);
                        break;
                    case DOWNLOAD_COMPLETE:
                        //在这里处理任务完成的状态
                        btnTaskItem.setText(CommonUtil.START_INSTALL);
                        updateBottom();
                        break;
                    case DOWNLOAD_CANCEL:
                        btnTaskItem.setText("已经取消");
                        break;
                    case DOWNLOAD_FAIL:
                        btnTaskItem.setText(CommonUtil.FAIL_DOWNLOAD);
                        break;
                }
            }
        }
    }
}
