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.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.duanduan.ActDownloadMgr;
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.di.components.DaggerTaskDialogComponent;
import com.sheep.gamegroup.di.modules.TaskDialogModule;
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.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.TaskState;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.presenter.TaskDialogContract;
import com.sheep.gamegroup.presenter.TaskDialogPresenter;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DeviceUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.adapter.TaskStateAdapter;
import com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;


import org.greenrobot.eventbus.EventBus;

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

/**
 * 弹框activity
 * Created by ljy on 2018/3/20.
 */

public class DialogActivity extends Activity implements TaskDialogContract.View {

    @BindView(R.id.dialog_item_icon_iv)
    ImageView dialogItemIconIv;
    @BindView(R.id.dialog_item_name_tv)
    TextView dialogItemNameTv;
    @BindView(R.id.dialog_item_size_tv)
    TextView dialogItemSizeTv;
    @BindView(R.id.doalog_item_get_rewards_tv)
    TextView doalogItemGetRewardsTv;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.start_task_tv)
    TextView start_task_tv;
    @BindView(R.id.listview)
    MyListview listview;
    private TaskEty taskEty;
    private TaskAcceptedEty task_accepted_entity;
    private List<TaskState> stateList = new ArrayList<>();//状态列表
    private TaskStateAdapter stateAdapter;

    private int type;//0,领取任务 1,开始试玩 2,开始下载 3，开始安装;4,信用卡跳转
    private boolean isDownLoad = false;//是否下载
    private String buttonStr = CommonUtil.GET_TASK;
    private Activity activity;

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

    @Inject
    TaskDialogPresenter preference;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_item_dialog);
        ButterKnife.bind(this);
        activity = this;

        initViews();
        initDatas();
        Aria.download(this).register();
        mDownloadTaskService = new DownloadTaskService(this);
        downLoadInfo = mDownloadTaskService.getDownloadTaskByUrl(taskEty);
    }

    private void initDatas() {
        webview.loadUrl(taskEty.getBoot_address());
        Glide.with(this)
                .load(taskEty.getIcon())
                .apply(new RequestOptions().dontAnimate())
                .into(dialogItemIconIv);
        dialogItemNameTv.setText(taskEty.getName());
        dialogItemSizeTv.setText( taskEty.getPackage_size() + "M");
        isDownLoad = PackageUtil.isAppInstalled(SheepApp.mContext, taskEty.getPackage_names());

        preference.getTaskState(taskEty.getRelease_task_id());

    }

    @Override
    protected void onResume() {
        super.onResume();
        setBtnState();
    }

    private void initViews() {

        taskEty = (TaskEty) getIntent().getSerializableExtra("task_entity");
        task_accepted_entity = (TaskAcceptedEty) getIntent().getSerializableExtra("task_accepted_entity");
        if (taskEty == null) {
            finish();
            return;
        }
        DaggerTaskDialogComponent.builder()
                .netComponent(SheepApp.get(DialogActivity.this).getNetComponent())
                .taskDialogModule(new TaskDialogModule(this))
                .build()
                .inject(DialogActivity.this);
        webview.setWebChromeClient(new WebChromeClient() {

        });
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });

        stateAdapter = new TaskStateAdapter(activity, stateList);
        listview.setAdapter(stateAdapter);
        stateAdapter.notifyDataSetChanged();


    }

    @OnClick({R.id.doalog_item_get_rewards_tv, R.id.dialog_item_x, R.id.start_task_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.doalog_item_get_rewards_tv:
                Jump2View.getInstance()
                        .goWithdrawal(activity, null);
                finish();
                break;
            case R.id.dialog_item_x:
                finish();
                break;
            case R.id.start_task_tv:
                startStask();
                break;
        }
    }

    /**
     * 开始任务或者下载游戏、试玩
     */
    private void startStask() {
        DownloadTarget task = null;
        //Todo 暂时判断信用卡，也许以后会增加其他类型，服务器传过来
        if(taskEty.needDownloadApp()){
            if(TextUtils.isEmpty(taskEty.getDownload_link()) || !taskEty.getDownload_link().contains("http")){
                G.showToast(R.string.error_download_link);
                return;
            }
            task = Aria.download(this).load(taskEty.getDownload_link());
        }

        String filePath = DIR+ File.separator+taskEty.getPackage_names()+ ClassFileHelper.FILE_SUFFIX;
        try{
            switch (type){
                case 0://领取任务
                    if(taskEty.getAcceptedTaskId() < 1){//没有正在进行的任务
                        acceptedTask();
                    } else {//先取消正在进行的任务

                        Jump2View.getInstance()
                                .goNoticeAct(activity, new DialogEntity(null,
                                        "是否放弃正在运行中的任务?",
                                        "是",
                                        "否",
                                        null));

                    }
                    break;
                case 1://开始试玩
                    toTestPlay();
                    break;
                case 2://开始下载
                    if(task.getTaskState() == IEntity.STATE_RUNNING){
                        task.stop();
                    } else if(task.getTaskState() == IEntity.STATE_FAIL){
                        task.cancel(true);
                        task.resetState();
                        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 3://开始安装
                    isDownLoad = PackageUtil.isAppInstalled(SheepApp.mContext, taskEty.getPackage_names());
                    if(isDownLoad){
                        if(taskEty.getTask_type() != 3){
                            start_task_tv.setText(CommonUtil.OPEN_APPLY);
                        }else {
                            start_task_tv.setText(CommonUtil.START_PLAY);
                        }
                        type = 1;
                        toTestPlay();
                        return;
                    }else if(!TextUtils.isEmpty(PackageUtil.isExistsFile(activity, taskEty.getPackage_names(), ""))){
                        ApkUtils.installApk(activity, filePath);
                    }else{
                        task.resetState();
//                        task.setFilePath(filePath);
//                        task.start();
                        mDownloadTaskService.start(downLoadInfo);
                        type = 2;
                    }
                    break;
                case 4://信用卡
                    Jump2View.getInstance()
                            .goHomePageView(activity, 3);
//                    finish();
                    break;
                case 10://信用卡
                    Ext ext;
                    if(taskEty == null) {
                        G.showToast("服务器数据错误，请联系客服或者稍候重试");
                    } else if((ext = EntityUtils.getExtInfo(taskEty.getExt())) == null || TextUtils.isEmpty(ext.getUrl())){
                        Jump2View.getInstance().goTaskDetailView(activity,  taskEty.getId());
                    } else {
                        Jump2View.getInstance().goWeb(activity, ext.getUrl());
                    }
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void acceptedTask() {
        JSONObject object = new JSONObject();
        object.put("device_id",DeviceUtil.getDeviceId(activity));
        object.put("release_task_id", Integer.valueOf(taskEty.getRelease_task_id()+""));
        preference.acceptedTask(object);
        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_ACCEPT);
    }

    /**
     * 去试玩
     */
    private void toTestPlay(){
        PackageUtil.startApp(activity, taskEty.getPackage_names());
    }

    /**
     * 按钮状态
     */
    private void setBtnState(){
        type = 0;
        if(taskEty.getRunTask() == 0){//领取任务
            buttonStr = CommonUtil.GET_TASK;
            type = 0;
        }else if(taskEty.getTask_type() == 2){//信用卡业务
            type = 4;
            buttonStr = CommonUtil.START_TASK;
            dialogItemSizeTv.setVisibility(View.INVISIBLE);
        }else if(taskEty.getTask_type() == 4){//h5
            type = 10;
            buttonStr = CommonUtil.START_TASK;
            dialogItemSizeTv.setVisibility(View.INVISIBLE);
        }
        else{
            //Todo 以后整理，现在加了个type=3
            if(isDownLoad && taskEty.getTask_type() != 3){
                buttonStr = CommonUtil.START_PLAY;;
                type = 1;
            } else {
                type = 2;
                DownloadTarget task = Aria.download(this).load(taskEty.getDownload_link());
                String filePath = DIR+ File.separator+taskEty.getPackage_names()+ ClassFileHelper.FILE_SUFFIX;
                int taskState = task.getTaskState();
                switch (taskState){
                    case IEntity.STATE_RUNNING:
                        buttonStr = task.getPercent() +"%";
                        break;
                    case IEntity.STATE_STOP:
                        buttonStr = CommonUtil.CONTINUE_DOWNLOAD;
                        break;
                    case IEntity.STATE_COMPLETE:
                        isDownLoad = PackageUtil.isAppInstalled(SheepApp.mContext, taskEty.getPackage_names());
                        if(isDownLoad){
                            buttonStr = CommonUtil.START_PLAY;
                            type = 1;
                        }else if(!TextUtils.isEmpty(PackageUtil.isExistsFile(activity, taskEty.getPackage_names(), ""))){
                            buttonStr = CommonUtil.START_INSTALL;
                            type = 3;
                        }else{
                            task.resetState();
                            buttonStr = CommonUtil.START_DOWNLOAD;
                        }
                        break;
                    case IEntity.STATE_FAIL:
                        buttonStr = CommonUtil.FAIL_DOWNLOAD;
                        break;
                    default:
                        buttonStr = CommonUtil.START_DOWNLOAD;
                        break;
                }
            }
        }
        start_task_tv.setText(buttonStr);
    }

    /**
     * 接收任务 成功
     * @param o
     */
    @Override
    public void startTaskUpdataView(Object o) {
        try{
            BaseMessage baseMessage = (BaseMessage) o;
            if(baseMessage.getCode() == 200){
                taskEty.setRunTask(1);
                setBtnState();
                G.showToast("接收任务成功");
                CommonUtil.getInstance().setTAskEnty(taskEty);
            }
            EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.ONFRESH_TRYMAKEMANY_PAGE));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void startTaskFailView(Object o) {

        G.showToast(((BaseMessage)o).getMsg()+ "");

    }

    @Override
    public void getStateSuccess(Object o) {

        if(o == null){
            return;
        }
        BaseMessage baseMessage = (BaseMessage) o;

        List<TaskState> stateList = JSONArray.parseArray(JSON.toJSONString(baseMessage.getData()), TaskState.class);

        if(stateList != null && stateList.size()>0){
            this.stateList.clear();
            this.stateList.addAll(stateList);

            stateAdapter.notifyDataSetChanged();

        }


    }

    @Override
    public void getStatefail(Object o) {


    }

    @Download.onPre void onPre(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
            start_task_tv.setText("准备下载中");
        }
    }
    @Download.onTaskStart void taskStart(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
            start_task_tv.setText("开始下载中");
        }
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
            start_task_tv.setText("恢复下载中");
        }
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
            int p = task.getPercent();    //任务进度百分比
//            mDownloadTaskService.setDownloadTaskPercent(p, task.getCurrentProgress()/1024d/1024d,task.getFileSize()/1024d/1024d,0,task.getKey());
            String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
            long speed1 = task.getSpeed(); //原始byte长度速度
            start_task_tv.setText(p + "%");
            System.out.println("Aria p " + p + ", speed = " + speed);
        }
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
//            mDownloadTaskService.setDownloadTaskStatus(task.getKey(), DownloadTaskService.STATUS_PAUSE);
            start_task_tv.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
//            mDownloadTaskService.deleteDownloadTaskByDownloadUrl(task.getKey());
            start_task_tv.setText("已经取消");
        }
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
//            mDownloadTaskService.setDownloadTaskStatus(task.getKey(), DownloadTaskService.STATUS_FAIL);
            start_task_tv.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        if(task.getKey().equals(taskEty.getDownload_link())) {
//            mDownloadTaskService.setDownloadTaskFinish(task.getKey(), task.getDownloadPath());
            //在这里处理任务完成的状态
            start_task_tv.setText(CommonUtil.START_INSTALL);
            type = 3;
//            PackageUtil.installApk(activity, task.getDownloadPath());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == RESULT_OK && taskEty != null){
            SheepApp.getInstance().getNetComponent().getApiService().giveUpTask(taskEty.getAcceptedTaskId())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {

                            //暂停下载---这么改就不能暂停了
//                            CommonUtil.getInstance().stopDownloadTask(activity, task_accepted_entity.getRelease_task().getTask().getDownload_link());
                            if(BuildConfig.DEBUG)
                                System.out.println("baseMessage onNext "+ JSON.toJSONString(baseMessage));
                            acceptedTask();
                            task_accepted_entity = null;
                            CommonUtil.getInstance().setTAskEnty(null);
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            if(BuildConfig.DEBUG)
                                System.out.println("baseMessage onError "+JSON.toJSONString(baseMessage));
                            G.showToast(TextUtils.isEmpty(baseMessage.getMsg()) ? "服务器错误，请稍候再试" : baseMessage.getMsg());
                        }
                    });
        }
    }
}
