package com.sheep.gamegroup.helper;

import android.app.Activity;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.OrienteeringDetail;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.TaskChild;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.RxjavaCountDownTimer;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.List;
import java.util.Locale;

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

import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_APP;
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.model.entity.TaskEty.TASK_TYPE_TIME;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.FIND_TASK;

/**
 * Created by realicing on 2018/7/3.
 * realicing@sina.com
 */
public class TaskHelper {
    private Action1<Integer> action1;

    public TaskHelper(Action1<Integer> action1) {
        this.action1 = action1;
    }

    private TaskAcceptedEty taskAcceptedEty;
    private int release_task_id;
    private Activity activity;

    public void initAcceptedTask(Activity activity, final int release_task_id) {
        this.activity = activity;
        this.release_task_id = release_task_id;

        SheepApp.getInstance().getNetComponent().getApiService().getAcceptedTaskDetail(release_task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        taskAcceptedEty = baseMessage.getData(TaskAcceptedEty.class);
                        initTask(release_task_id);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        initTask(release_task_id);
                    }
                });
    }

    private Release_task taskReleaseEty;

    private void initTask(int release_task_id) {
        SheepApp.getInstance().getNetComponent().getApiService().taskDesc(release_task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        taskReleaseEty = baseMessage.getData(Release_task.class);
                        if (action1 != null)
                            action1.call(1);//刷新界面

                    }

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

    private OrienteeringDetail orienteeringDetail;

    private void initGameTask(final View itemView, String third_task_id) {
        SheepApp.getInstance().getNetComponent().getApiService().getMyGame(third_task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        orienteeringDetail = baseMessage.getData(OrienteeringDetail.class);
                        loadTask(itemView);

                    }

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

    public boolean hasTask() {
        return taskReleaseEty != null && taskReleaseEty.getTask() != null;
    }

    private RxjavaCountDownTimer timer;

    public void loadTask(final View itemView) {
        itemView.setVisibility(View.VISIBLE);
        if (taskReleaseEty == null) {
            return;
        }
        final TaskEty taskEty = taskReleaseEty.getTask();
        if (taskEty == null) {
            return;
        }
        ImageView find_information_game_icon = (ImageView) itemView.findViewById(R.id.find_information_game_icon);
        TextView find_information_game_name = (TextView) itemView.findViewById(R.id.find_information_game_name);
        TextView find_information_game_surplus = (TextView) itemView.findViewById(R.id.find_information_game_surplus);
        TextView find_information_game_surplus1 = (TextView) itemView.findViewById(R.id.find_information_game_surplus1);
        TextView find_information_game_time = (TextView) itemView.findViewById(R.id.find_information_game_time);
        TextView find_information_game_yuan = (TextView) itemView.findViewById(R.id.find_information_game_yuan);
        TextView find_information_game_task0 = (TextView) itemView.findViewById(R.id.find_information_game_task_top);
        TextView find_information_game_task = (TextView) itemView.findViewById(R.id.find_information_game_task_bottom);
        final TextView find_information_game_task_end_time = (TextView) itemView.findViewById(R.id.find_information_game_task_end_time);
        if (orienteeringDetail != null) {//已经完成的游戏任务
            find_information_game_task.setVisibility(View.VISIBLE);
            find_information_game_task0.setVisibility(View.VISIBLE);
            find_information_game_yuan.setVisibility(View.INVISIBLE);
            find_information_game_surplus.setText(String.format(Locale.CHINA, "可定向消费:%.1f元", orienteeringDetail.getBalance()));
            find_information_game_surplus.setTextColor(activity.getResources().getColor(R.color.red_fd2d54));
            find_information_game_surplus1.setVisibility(View.GONE);
            find_information_game_task.setText("去充值");
            find_information_game_task.setEnabled(true);
            downloadHelper.updateDownloadTaskView(activity, taskEty, find_information_game_task0);
            find_information_game_task.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ViewUtil.showGamePayAccount(activity, orienteeringDetail.getGame_id(), orienteeringDetail.getName());
                }
            });
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    reloadDataType = 1;//回来后将刷新界面数据 taskAcceptedEty
                    Jump2View.getInstance().goGameTaskDetailView(activity, release_task_id, orienteeringDetail.getGame_id(), 1);
                }
            });
            return;
        }
        GlideImageLoader.setGameImage(find_information_game_icon, taskEty.getIcon());
        ViewUtil.setText(find_information_game_name, taskReleaseEty.getName());
        setTaskTypeText(find_information_game_surplus, taskReleaseEty);
        find_information_game_surplus1.setVisibility(View.VISIBLE);
        setNumText(find_information_game_surplus1, taskReleaseEty);
        ViewUtil.setText(find_information_game_time, String.format(Locale.CHINA, "截止日期：%s", taskReleaseEty.getDeadline().equals("永久") ? taskReleaseEty.getDeadline() : TimeUtil.TimeStamp2Date(NumberFormatUtils.parseLong(taskReleaseEty.getDeadline()), "yyyy/MM/dd HH:mm")));
        ViewUtil.setText(find_information_game_yuan, String.format(Locale.CHINA, "+%s元", taskReleaseEty.getBonusText()));
        find_information_game_task0.setVisibility(View.GONE);
        find_information_game_yuan.setVisibility(View.VISIBLE);
        switch (taskEty.getTask_type()) {// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务
            case TASK_TYPE_CREDIT_CARD://信用卡任务
                find_information_game_task.setVisibility(View.GONE);
                find_information_game_task_end_time.setVisibility(View.GONE);
                find_information_game_yuan.setGravity(Gravity.END);
                String[] remarks = new String[0];
                if (!TextUtils.isEmpty(taskEty.getRemarks())) {
                    remarks = taskEty.getRemarks().split(";");
                }
                find_information_game_time.setText(remarks.length > 0 ? remarks[0] : "");
                find_information_game_surplus.setText(remarks.length > 1 ? remarks[1] : "");
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Jump2View.getInstance().goCreditCardTaskDetail(activity, taskReleaseEty.getId());
                    }
                });
                break;
            case TASK_TYPE_CHANG_SI:
                break;
            case TASK_TYPE_TIME://时间试玩任务
            case TASK_TYPE_APP://应用下载
            case TASK_TYPE_H5://h5业务
            case TASK_TYPE_SUCCESSION://连续任务
            case TASK_TYPE_GAME_SHEEP://游戏任务
            case TASK_TYPE_GAME_TECENT://游戏任务
            default:
                find_information_game_yuan.setGravity(Gravity.CENTER);
                if (taskAcceptedEty != null) {
                    switch (taskAcceptedEty.getStatus()) {
                        case 1://"已接受任务";
                        case 2:// "正在进行中";
                            if (taskReleaseEty.getDeadline().equals("永久")) {
                                find_information_game_task_end_time.setVisibility(View.GONE);
                            } else {
                                find_information_game_task_end_time.setVisibility(View.VISIBLE);
                                find_information_game_task_end_time.setText(TimeUtil.getHours(taskAcceptedEty.getEnd_time() * 1000));
                                timer = RxjavaCountDownTimer.getInstance(taskAcceptedEty.getEnd_time())
                                        .setOnTickListener(new RxjavaCountDownTimer.OnTickListener() {
                                            @Override
                                            public void onFinish() {
                                                find_information_game_task_end_time.setVisibility(View.GONE);
                                                refreshTask();
                                            }

                                            @Override
                                            public void onTicker(long time) {
                                                find_information_game_task_end_time.setText(TimeUtil.getHours(time * 1000));
                                            }
                                        }).start();
                            }
                            find_information_game_task.setText("取消任务");
                            find_information_game_task.setEnabled(true);
                            find_information_game_task.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    FIND_TASK.onEvent("release_task_id", release_task_id, "action", "取消任务");
                                    SheepApp.getInstance().getNetComponent().getApiService().giveUpTask(taskAcceptedEty.getId())
                                            .subscribeOn(Schedulers.io())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                                                @Override
                                                public void onNext(BaseMessage baseMessage) {
                                                    CommonUtil.getInstance().updateAutoCheck(null);
                                                    refreshTask();
                                                }

                                                @Override
                                                public void onError(BaseMessage baseMessage) {
                                                    G.showToast(baseMessage);
                                                }
                                            });
                                    //暂停下载
                                    CommonUtil.getInstance().stopDownloadTask(activity, taskEty.getDownload_link());
                                }
                            });
                            break;
                        case 6://审核失败
                            find_information_game_task_end_time.setVisibility(View.GONE);
                            find_information_game_task.setVisibility(View.VISIBLE);
                            find_information_game_task.setText("审核失败");
                            find_information_game_task.setEnabled(false);
                            break;
                        //不可操作
                        case 7:// "提交审核";
                            find_information_game_task_end_time.setVisibility(View.GONE);
                            find_information_game_task.setVisibility(View.VISIBLE);
                            find_information_game_task.setText("正在审核");
                            find_information_game_task.setEnabled(false);
                            break;
                        case 3://完成任务
                            find_information_game_task_end_time.setVisibility(View.GONE);
                            find_information_game_task.setVisibility(View.VISIBLE);
                            find_information_game_task.setText("已经完成");
                            find_information_game_task.setEnabled(false);
                            if (taskEty.isGameTask()) {
                                initGameTask(itemView, taskEty.getThird_task_id());
                            }
                            break;
                        case 8://任务已经下线
                            find_information_game_task_end_time.setVisibility(View.GONE);
                            find_information_game_task.setVisibility(View.VISIBLE);
                            find_information_game_task.setText("已经下线");
                            find_information_game_task.setEnabled(false);
                            break;
                        case 9:// "至少完成一个任务了";
                        default:
                            find_information_game_task_end_time.setVisibility(View.GONE);
                            find_information_game_task.setVisibility(View.GONE);
                            break;
                    }
                } else if (taskReleaseEty.isOffline()) {//任务已经下线
                    find_information_game_task_end_time.setVisibility(View.GONE);
                    find_information_game_task.setVisibility(View.VISIBLE);
                    find_information_game_task.setText("已经下线");
                    find_information_game_task.setEnabled(false);
                } else if ("0".equals(taskReleaseEty.getLast_num())) {
                    find_information_game_task_end_time.setVisibility(View.GONE);
                    find_information_game_task.setVisibility(View.VISIBLE);
                    find_information_game_task.setText("任务已抢光");
                    find_information_game_task.setEnabled(false);
                } else {
                    find_information_game_task_end_time.setVisibility(View.GONE);
                    find_information_game_task.setVisibility(View.VISIBLE);
                    find_information_game_task.setText("领取任务");
                    find_information_game_task.setEnabled(true);
                    find_information_game_task.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            taskEty.setRunTask(0);
                            taskEty.setRelease_task_id(taskReleaseEty.getId());
                            taskEty.setName(taskReleaseEty.getName());
                            taskEty.setAcceptedTaskId(taskReleaseEty.getAccepted_task_id());
                            Jump2View.getInstance().goTaskDetailView(activity, release_task_id);
//                            Jump2View.getInstance().goDialogActivityView(activity, taskEty);
                            FIND_TASK.onEvent("release_task_id", release_task_id, "action", "领取任务");
                        }
                    });
                }
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        reloadDataType = 1;//回来后将刷新界面数据 taskAcceptedEty
                        Jump2View.getInstance().goTaskDetailView(activity, release_task_id);
                    }
                });
                break;
        }
    }

    //刷新界面
    public void refreshTask() {
        clear();
        taskAcceptedEty = null;
        taskReleaseEty = null;
        initTask(release_task_id);
    }

    private int reloadDataType;//0 不刷新数据 1刷新 taskAcceptedEty

    public void onResume() {
        switch (reloadDataType) {
            case 1:
                refreshTask();
                break;
        }
    }

    /**
     * 清理计时器
     */
    public void clear() {
        if (timer != null)
            timer.clear();
        timer = null;
        action1 = null;
    }
    /**
     * 退出
     */
    public void onDestroy() {
        clear();
        action1 = null;
        activity = null;
    }

    public void destroy() {
        if (timer != null)
            timer.clear();
        timer = null;
        action1 = null;
        activity = null;
    }


    private DownloadHelper downloadHelper = new DownloadHelper();

    public void updateState(int status) {
        downloadHelper.updateState(status);
    }


    /**
     * 设置剩余份数文本
     *
     * @param textView
     * @param taskReleaseEty
     */
    public static void setNumText(TextView textView, Release_task taskReleaseEty) {
        textView.setVisibility(View.VISIBLE);
        ViewUtil.setText(textView, String.format(Locale.CHINA, "剩余%s份", taskReleaseEty.getLast_num()));
    }

    /**
     * 设置游戏类型文本
     *
     * @param textView
     * @param taskReleaseEty
     */
    public static void setTaskTypeText(TextView textView, Release_task taskReleaseEty) {
        textView.setVisibility(View.VISIBLE);
        String[] textColor = getTaskTypeTextColor(taskReleaseEty.getTask());
        ViewUtil.setColorMapText(textView, String.format(Locale.CHINA, "%s", textColor[0]), textColor[0], textColor[1]);
        textView.setBackgroundResource(R.drawable.shape_blue_stroke_rectangle_no_lb);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
        int padding = textView.getContext().getResources().getDimensionPixelSize(R.dimen.content_padding_2);
        textView.setPadding(4 * padding, padding, 4 * padding, padding);
    }

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

    //    private int task_type = 1;// 1时间试玩任务 2 信用卡任务 3应用下载 4h5业务 1001畅思 1000连续任务， 1002 1003游戏任务 1002平台游戏，1003 腾讯游戏，1004 小米游戏
    private static String[] getTaskTypeTextColor(TaskEty task) {
        switch (task.getTask_type()) {
            case TASK_TYPE_GAME_SHEEP:
            case TASK_TYPE_GAME_TECENT:
            case TASK_TYPE_GAME_XIAO_MI:
                return new String[]{"游戏任务", "#4889FF"};//已经修改为一种颜色了
            case TASK_TYPE_SUCCESSION:
                return new String[]{"连续任务", "#4889FF"};
            default:
                return new String[]{"试玩任务", "#4889FF"};
        }
    }

    /**
     * 设置当前子任务为选中状态
     * 1、 任务未开启时——即将开启
     * 2、 任务未领取时——可领取
     * 3、 任务已领取待完成时——进行中
     * 4、 任务已提交待审核——待审核
     * 5、 任务审核通过——已完成
     * 6、 任务审核失败——审核失败
     * 7、任务已过期未完成——已过期
     *
     * @param taskEty
     */
    public static void setSelectFlag(TaskEty taskEty) {
        List<TaskChild> taskChildList;
        if (taskEty == null || ListUtil.isEmpty(taskChildList = taskEty.getChild()))
            return;
        TaskChild selectTaskChild = null;
        outFor:
        for (TaskChild taskChild : taskChildList) {
            switch (taskChild.getStatus()) {
                case 2:
                case 4:
                case 3:
                case 6://找到可领取或者进行中或者审核失败或者审核中则直接退出循环
                    selectTaskChild = taskChild;
                    break outFor;
                case 0:
                case 1:
                case 5:
                    if (selectTaskChild == null)
                        selectTaskChild = taskChild;
                    break;
            }
        }
        if (selectTaskChild != null)
            selectTaskChild.setSelectFlag(true);
    }
}
