package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
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.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTarget;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.inf.IEntity;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.absBase.AbsChooseImageActivity;
import com.sheep.gamegroup.di.components.DaggerTaskDetailComponent;
import com.sheep.gamegroup.di.modules.TaskDetailModule;
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.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.TaskReleaseEty;
import com.sheep.gamegroup.model.util.AutoTaskListUtil;
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.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LocationUtils;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.PngUtil;
import com.sheep.gamegroup.util.SelfCountDownTimer;
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.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
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 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.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.GAME_INSTEAD_OF_RECHARGE_GET;

/**
 * 任务详情页面
 * 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 TaskReleaseEty 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.get(activity).getNetComponent())
                .taskDetailModule(new TaskDetailModule(this))
                .build()
                .inject(this);
        TitleBarUtils.getInstance()
                .setTitle(activity, "任务详情")
                .setTitleFinish(activity);
        Aria.download(this).register();
        mDownloadTaskService = new DownloadTaskService(this);
        adpTaskDetailChildListview = new AdpTaskDetailChildListview(taskChildList, activity);
        detail_task_listview.setAdapter(adpTaskDetailChildListview);
        adpTaskDetailChildListview.notifyDataSetChanged();
        bottom_btn_layout.setVisibility(View.GONE);
        if (DataUtil.IS_USE_SCREEN_SHOT) {
            //如果要使用小绵羊截图方案，则在进入任务详情界面启动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("初始化截屏数据成功");
                }
            });
        }
    }

    @Override
    public void initListener() {

    }

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

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

        taskEty = taskReleaseEty.getTask();
        nameTv.setText(taskReleaseEty.getName() + "");
        priceTv.setText("+" + taskReleaseEty.getBonusText() + "元");
        if (!taskReleaseEty.getDeadline().equals("永久")) {
            dateTv.setText("截至日期：" + TimeUtil.getDate(TimeUtil.FORMAT, Long.valueOf(taskReleaseEty.getDeadline())) + "");
        } else {
            dateTv.setText("截至日期：" + taskReleaseEty.getDeadline());
        }
        num_tv.setText("剩" + 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() == 3) {

            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_H5 = 10;//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()) {//任务已经下线
            btnUpImag.setVisibility(View.GONE);//不显示第二按钮
            switch (taskEty.getTask_type()) {// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务 1004 小米游戏任务
                case 4://h5业务
                    btnTaskItem.setText(CommonUtil.TASK_OFFLINE);
                    btnTaskItem.setEnabled(false);
                    break;
                case 2:
                case 1001://信用卡与畅思任务不考虑
                    bottom_btn_layout.setVisibility(View.GONE);
                    break;
                case 1000://连续任务
                    setFirstBtnState();
                    break;
                case 1002:
                case 1003:
                case 1004://游戏任务
                    setFirstBtnState();
                    break;
                default://试玩任务直接设置下载状态
                    setFirstBtnState();
                    if (type == DownloadTaskService.STATUS_INSTALLED && gettaskAcceptedEty != null && gettaskAcceptedEty.getStatus() != 3) {//已经安装并且有任务未完成的情况下
                        if (TextUtils.isEmpty(gettaskAcceptedEty.getScreenshots()) || gettaskAcceptedEty.getLower_num() > 0) {//没有提交过截图或者已经提交过一次 下线失败后提交
                        } else {//提交过一次，但是审核失败或者没有审核就下线了
                            btnUpImag.setText("重新提交");
                            btnUpImag.setVisibility(View.VISIBLE);
                        }
                    }
                    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 4://h5业务
                        type = TASK_TYPE_H5;
                        btnTaskItem.setText(CommonUtil.START_TASK);
                        break;
                    case 2:
                    case 1001://信用卡与畅思任务不考虑
                        bottom_btn_layout.setVisibility(View.GONE);
                        break;
                    case 1002:
                    case 1003:
                    case 1004://游戏任务
                        if(taskEty.isGameReservationCantDownload()) {//游戏任务中还不可以下载任务(预约任务)-->预约游戏
                            type = TASK_TYPE_RESERVATION;
                            btnTaskItem.setText(CommonUtil.GAME_RESERVATION);
                            btnUpImag.setVisibility(View.GONE);//不显示第二按钮
                        } else {//游戏任务中可以下载的预约任务
                            setFirstBtnState();
                            setGameTaskFirstBtnState();
                        }
                        break;
                    default://其它任务先设置下载状态
                        setFirstBtnState();
                        setOtherTaskBtnState();
                        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 setSuccessionTaskBottomState() {
        int failChildPosition = taskEty.getFailChildPosition();//获取第一个审核失败子任务的位置
        boolean hasChildFail = failChildPosition > -1;//有子任务审核失败
        boolean hasChildRunning = taskEty.hasChildRunning();//有子任务正在进行
        boolean hasChildCanAccepted = taskEty.hasChildCanAccepted();//有子任务处于可领取状态

        if (hasChildFail) {
            btnUpImag.setText(String.format(Locale.CHINA, "重新上传截图（第%d天）", failChildPosition + 1));
        } 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 1:
                btnUpImag.setVisibility(View.GONE);
                break;
            case 2:
                switch (type){
                    case DownloadTaskService.STATUS_INIT:
                    case DownloadTaskService.STATUS_FINISH:
                        btnUpImag.setVisibility(View.GONE);
                        break;
                    default:
                        setOtherNormalTaskBtnState();
                        break;
                }
                break;
            case 3:
                btnUpImag.setText("领取奖励");
                switch (type){
                    case DownloadTaskService.STATUS_INIT:
                    case DownloadTaskService.STATUS_FINISH:
                        btnUpImag.setVisibility(View.GONE);
                        break;
                    default:
                        if(taskEty.getTask_type() == 1000)//连续任务
                            setAutoSuccessionTaskBottomState();
                        break;
                }
                break;
        }
    }

    /**
     * 设置连续任务与试玩任务两个按钮状态（任务未下线且有任务记录且是手动审核任务且已经安装应用）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setOtherNormalTaskBtnState() {
        boolean isSuccession = taskEty.isSuccession();
        if(isSuccession){//连续任务
            setSuccessionTaskBottomState();
        } else {
            switch (gettaskAcceptedEty.getStatus()) {
                case 1://"已接受任务";
                case 2:// "正在进行中";
                    break;
                case 6://试玩任务审核失败可以重新提交
                    btnUpImag.setText("重新提交");
                    break;
                case 7:// "提交审核";
                    btnUpImag.setVisibility(View.GONE);
                    break;
                case 3://完成任务
                    btnUpImag.setVisibility(View.GONE);
                    break;
            }
        }
    }

    /**
     * 设置游戏任务中两个按钮的状态和文字显示（任务未下线且有任务记录）
     * 注：前提是gettaskAcceptedEty不为空哦
     */
    private void setGameTaskFirstBtnState() {
        switch (type) {
            case DownloadTaskService.STATUS_INIT:
                btnUpImag.setVisibility(View.GONE);
                btnTaskItem.setText(CommonUtil.GAME_DOWNLOAD);
                break;
            case DownloadTaskService.STATUS_FINISH:
                btnUpImag.setVisibility(View.GONE);
                btnTaskItem.setText(CommonUtil.GAME_INSTALL);
                break;
            case DownloadTaskService.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, mDownloadTaskService, 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, DownloadTaskService mDownloadTaskService, Action1<Object> action1) {
        boolean isInstalled = PackageUtil.isAppInstalled(SheepApp.getInstance(), taskEty.getPackage_names());
        boolean isExistApk = !TextUtils.isEmpty(PackageUtil.isExistsFile(taskEty.getPackage_names()));
        String buttonStr;
        action1.call(true);
        if (isInstalled) {
            action1.call(DownloadTaskService.STATUS_INSTALLED);
            switch (taskEty.getTask_type()){// 1时间试玩任务 3应用下载 1000连续任务， 1002 1003游戏任务 1002平台游戏，1003 腾讯游戏，1004 小米游戏
                case 3:
                    buttonStr = CommonUtil.OPEN_APPLY;
                    break;
                default:
                    buttonStr = CommonUtil.GAME_OPEN;
                    break;
            }
        } else {
            if (taskEty.getDownload_link() == null || !taskEty.getDownload_link().startsWith("http")) {
                buttonStr = SheepApp.getInstance().getResources().getString(R.string.error_download_link);
                action1.call(false);
                action1.call(DownloadTaskService.STATUS_INIT);
            } else {
                DownLoadInfo downLoadInfo = mDownloadTaskService.getDownloadTaskByUrl(taskEty);
                Integer mStatus = downLoadInfo.getMStatus();
                int taskState = mStatus == null ? 0 : mStatus;
                switch (taskState) {
                    case DownloadTaskService.STATUS_ING:
                        action1.call(DownloadTaskService.STATUS_INIT);
                        buttonStr = Math.abs(downLoadInfo.getMPercent()) + "%";
                        break;
                    case DownloadTaskService.STATUS_PAUSE:
                        action1.call(DownloadTaskService.STATUS_INIT);
                        buttonStr = CommonUtil.CONTINUE_DOWNLOAD;
                        break;
                    case DownloadTaskService.STATUS_FINISH:
                        if (isExistApk) {
                            action1.call(DownloadTaskService.STATUS_FINISH);
                            buttonStr = CommonUtil.START_INSTALL;
                        } else {
                            action1.call(DownloadTaskService.STATUS_INIT);
                            buttonStr = CommonUtil.START_DOWNLOAD;
                        }
                        break;
                    case DownloadTaskService.STATUS_FAIL:
                        action1.call(DownloadTaskService.STATUS_INIT);
                        buttonStr = CommonUtil.FAIL_DOWNLOAD;
                        break;
                    default:
                        action1.call(DownloadTaskService.STATUS_INIT);
                        buttonStr = CommonUtil.START_DOWNLOAD;
                        break;
                }
            }
        }
        action1.call(buttonStr);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 下载模块修改
     */
    private DownloadTaskService mDownloadTaskService;

    @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:
                    Jump2View.getInstance().tryShare(activity, "task_desc_url", "task_id", releaseTaskId);
                    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().setTAskEnty(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.getInspect_type() == 3) {//应用自动审核任务
            try {
                checkAndCommitTask();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } 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 DownloadTaskService.STATUS_INIT://开始下载
                DownloadTarget task;
                if (TextUtils.isEmpty(taskReleaseEty.getTask().getDownload_link()) || !taskReleaseEty.getTask().getDownload_link().contains("http")) {
                    G.showToast(R.string.error_download_link);
                    return;
                }
                task = Aria.download(this).load(taskReleaseEty.getTask().getDownload_link());
                final DownLoadInfo downLoadInfo = mDownloadTaskService.getDownloadTaskByUrl(taskEty);
                if (task.getTaskState() == IEntity.STATE_RUNNING) {
                    task.stop();
                } else if (task.getTaskState() == IEntity.STATE_FAIL) {
                    task.cancel(true);
                    task.removeRecord();
                } else {
                    //                            task.setFilePath(filePath);
                    //                            task.start();
                    mDownloadTaskService.start(downLoadInfo);
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (mDownloadTaskService.addDownloadTask(downLoadInfo)) {
                            //发送红点信息
                            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.TIPS_DOWN_ICON));
                        }
                    }
                }).start();
                UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_DOWNLOAD);
                break;
            case DownloadTaskService.STATUS_FINISH:
                ApkUtils.installApk(SheepApp.mContext, PackageUtil.isExistsFile(taskEty.getPackage_names()));
                break;
            case DownloadTaskService.STATUS_INSTALLED:
                PackageUtil.startApp(SheepApp.mContext, taskEty.getPackage_names());
                break;
            case TASK_TYPE_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;
        }
    }

    /**
     * 发起选择图片来上传截图
     */
    private void commitScreenShot() {
        switch (taskEty.getTask_type()) {
            case 1000://连续任务
                commitScreenShotTaskId = taskEty.getCanCommitChildRelease_task_id();
                break;
            default:
                commitScreenShotTaskId = taskReleaseEty.getAccepted_task_id() == 0 && gettaskAcceptedEty != null ? gettaskAcceptedEty.getId() : taskReleaseEty.getAccepted_task_id();
                break;
        }
        if (commitScreenShotTaskId > 0) {
            if (DataUtil.IS_USE_SCREEN_SHOT || DataUtil.IS_LISTEN_SCREEN_SHOT) {//小绵羊截图方案
                File dir = DataUtil.getInstance().getScreenShotsDir(taskEty.getPackage_names());
                showChooseDialog(false, true, DEFAULT_MAX_COUNT, dir);
            } else {//用户手动截图方案
                showChooseDialog(false, true, DEFAULT_MAX_COUNT);
            }
        } 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);

            final long runTime = AppUsageManager.getInstance().getTotalTimeInForeground(taskEty.getPackage_names());
            if (runTime <= 0) {//时间小于等于0则不提交
                G.showToast("该任务时长未达到，请继续去体验应用哦！"+(TestUtil.isTest()?"时长为："+runTime+"毫秒":""));
                return;
            }
            MyDbManager.getInstance().removeAppRecord();//删除记录表 5.0及以下使用
            AutoTaskListUtil.getInstance().resetReceiveTaskTime();//重置比对时间  5.1及以上使用
            AppUsageManager.getInstance().needOpenLookAppUsageStatsPermisson(true);//重新保存应用使用情况的数据

            object.put("task_time", runTime / 1000);
            object.put("release_task_id", taskReleaseEty.getId());
            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().setTAskEnty(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("该任务时长未达到，请继续去体验应用哦！"+(TestUtil.isTest()?"时长为："+runTime/1000+"秒":""));
                        }
                    });
        } else {
            G.showToast(R.string.unknown_error);
        }
    }

    /**
     * 连续任务在自动审核任务领取任务时添加子任务id参数
     *
     * @param object
     * @param taskEty
     */
    private void addCanAcceptedTaskChildId(JSONObject object, TaskEty taskEty) {
        switch (taskEty.getTask_type()) {
            case 1000://连续任务
                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 1000://连续任务
                TaskChild task_child = taskEty.getCanCommitChild(TaskEty.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() == 2) {//信用卡
                    llInfos.addView(getStep("信用卡注册", "待完成", 0));
                } else if (PackageUtil.isAppInstalled(SheepApp.mContext, 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) {//小绵羊截图方案或者监听方案：上传截图成功后删除之前的截图
            //这里领取了奖励，要刷新用户信息
            CommonUtil.getInstance().updateUserInfo(null);
            if (DataUtil.IS_USE_SCREEN_SHOT) {//小绵羊截图方案：上传截图成功后删除之前的截图
                DataUtil.getInstance().clearScreenShots();
            }
        }
        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(TaskReleaseEty.class);
        initWigget();
    }

    @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<String> callBack = new ICallBack<String>() {
        @Override
        public String call(Object... args) {
            String pngFilePath = (String) args[0];
            int size = (int) args[1];
            int index = (int) args[2];
            try {
                //加密文本内容：包名;签名md5;试玩应用包名;试玩应用签名md5;任务id;图片总数;图片位置
                return PngUtil.decodePng(pngFilePath, taskEty.getPackage_names(), String.format(Locale.CHINA, "%d;%d;%d", commitScreenShotTaskId, size, index));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    };
    /**
     * 上传图片前的回调
     * @return
     */
    protected ICallBack<String> getCallBack(){
        return callBack;
    }
    private int commitScreenShotTaskId;

    @Override
    protected void onSetNetImageUrl(String data) {
        setLoaddingText("提交中");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", commitScreenShotTaskId);
        jsonObject.put("screenshots", data + "");
        jsonObject.put("remark", /*taskEty.getRemarks() +*/ "");
        jsonObject.put("package_name", taskEty.getPackage_names() + "");
        jsonObject.put("status", 7 + "");
        presenter.taskStatus(jsonObject);
        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) {
                                CommonUtil.getInstance().setTAskEnty(null);
                                acceptedTask();
                            }
                        });
                    }
                }
                break;
            case 101:
                //图片展示
                isFresh = true;
                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.mContext) {
                    @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);
        JSONObject object = new JSONObject();
        object.put("device_id", DeviceUtil.getDeviceId(activity));
        object.put("release_task_id", taskReleaseEty.getId());
        addCanAcceptedTaskChildId(object, taskEty);
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .acceptedTask(object)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @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().setTAskEnty(taskReleaseEty.getTask());

                        getAcceptedTaskDetail(releaseTaskId);

                    }
                });
        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_ACCEPT);
    }

    @Download.onPre
    void onPre(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            if (taskEty == null) {
                return;
            }
            btnTaskItem.setText("准备下载中");
        }
    }

    @Download.onTaskStart
    void taskStart(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            btnTaskItem.setText("开始下载中");
        }
    }

    @Download.onTaskResume
    void taskResume(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            btnTaskItem.setText("恢复下载中");
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        try {
            if (task.getKey().equals(taskEty.getDownload_link())) {
                int p = task.getPercent();    //任务进度百分比
                String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
//                long speed1 = task.getSpeed(); //原始byte长度速度
                btnTaskItem.setText(String.format(Locale.CHINA, "%d%%", Math.abs(p)));
                System.out.println("Aria p " + p + ", speed = " + speed);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Download.onTaskStop
    void taskStop(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            btnTaskItem.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            btnTaskItem.setText("已经取消");
        }
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            btnTaskItem.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        if (taskEty == null) {
            return;
        }
        if (task.getKey().equals(taskEty.getDownload_link())) {
            //在这里处理任务完成的状态
            btnTaskItem.setText(CommonUtil.START_INSTALL);
            updateBottom();
        }
    }


    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 1000://连续任务
                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_title.setText(getString(R.string.supplement_explain_n));
                    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 1002:
            case 1003:
            case 1004://游戏任务
                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 (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();
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .receive_award(taskReleaseEty.getAccepted_task_id())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.mContext) {
                    @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();
                    empty_view.setVisibility(View.GONE);
                    initWigget();
                }
            }
        });
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonUtil.getInstance().cancelAllTimers(CommonUtil.getInstance().timerHashMap);
        Aria.download(this).unRegister();
    }
}
