package com.sheep.gamegroup.view.adapter;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.kfzs.duanduan.adp.AdpCommonRecy;
import com.sheep.gamegroup.model.entity.RecyleObj;
import com.sheep.gamegroup.model.entity.RecyleType;
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.TaskReleaseEty;
import com.sheep.gamegroup.presenter.TryMakeMoneyPresenter;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
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.jiuyan.samllsheep.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import static com.sheep.gamegroup.model.entity.RecyleType.RUN_TASK;

/**
 * Created by ljy on 2018/3/20.
 */

public class TryMakeMoneyAdp extends AdpCommonRecy<RecyleObj> {
    private final static int TAG_ID_TEMP = R.id.view_tag_1;
    private HashMap<View, SelfCountDownTimer> timerHashMap= new HashMap<>();
    @Inject
    TryMakeMoneyPresenter presenter;
    private Context context;
    private int type = 0;//0:推荐 1:热门 2:预约
    private int is_succession;//0:一般任务 1:连续任务

    public TryMakeMoneyAdp(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public int getViewIdByType(int type) {
        int resId = R.layout.empty;
        RecyleType recyleType = RecyleType.values()[type];
        switch (recyleType){
            case RELEASE_TASK:
                resId = R.layout.try_mkmy_release_task_list;
                break;
            case RUN_TASK:
                resId = R.layout.try_mkmy_release_task_list;
                break;
        }
        return resId;
    }

    @Override
    public void convert(ViewHolder holder, RecyleObj recyleObj) {

        switch (recyleObj.getRecyleType()){
            case RELEASE_TASK:
                bindReleaseTask(holder, (List<TaskReleaseEty>) recyleObj.getDataObj());
                break;
            case RUN_TASK:
//                List<TaskAcceptedEty> etyList = new ArrayList<>();
//                etyList.add((TaskAcceptedEty) recyleObj.getDataObj());
                bindRunTask(holder, (List<TaskAcceptedEty>) recyleObj.getDataObj());
                break;
        }

    }

    @Override
    public int getItemViewType(int position) {
        return getmListDatas().get(position).getRecyleType().ordinal();
    }
    /**
     * 传入presenter
     */
    public void addPresenter(TryMakeMoneyPresenter presenter){
        this.presenter = presenter;
    }
    /**
     * 传入type
     */
    public void addType(int type){
        this.type = type;
    }
    /**
     * 传入is_succession
     */
    public void setIs_succession(int is_succession){
        this.is_succession = is_succession;
    }
    /**
     * 传入正在运行的任务
     * @param taskAcceptedEty
     */
    public void setTaskAcceptedEty(TaskAcceptedEty taskAcceptedEty) {
        this.taskAcceptedEty = taskAcceptedEty;
    }
    private TaskAcceptedEty taskAcceptedEty;


    /**
     * 获取已发布的
     */
    private void bindReleaseTask(ViewHolder holder, final List<TaskReleaseEty> etyList){
        RecyclerView recyclerView = holder.getView(R.id.release_task_listview, RecyclerView.class);
        recyclerView.setHasFixedSize(true);
//        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,
//                StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(new RecyclerView.Adapter(){

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                LinearLayout view = (LinearLayout) LayoutInflater.from(context)
                        .inflate(R.layout.try_makemoney_item_recommend, viewGroup,false);
                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view) {
                    @Override
                    public String toString() {
                        return super.toString();
                    }
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
                if(etyList.get(i) == null || etyList.get(i).getTask() == null){
                    return;
                }
                    viewHolder.itemView.setTag(TAG_ID_TEMP, etyList.get(i).getId());
                    TextView detail_task_tv = viewHolder.itemView.findViewById(R.id.detail_task_tv);
                if(i == 0){
                    viewHolder.itemView.findViewById(R.id.item_title_tv).setVisibility(View.VISIBLE);
                    viewHolder.itemView.findViewById(R.id.item_title_iv).setVisibility(View.GONE);
                    String titleStr = "推荐";
                    int resourceId = R.mipmap.task_hot_icon;
                    switch (type){
                        case 0:
                            titleStr = "推荐";
                            break;
                        case 1:
                            titleStr = "热门任务";
                            viewHolder.itemView.findViewById(R.id.item_title_iv).setVisibility(View.VISIBLE);
                            Glide.with(context)
                                    .load(resourceId)
                                    .apply(new RequestOptions().placeholder(resourceId))
                                    .into((ImageView) viewHolder.itemView.findViewById(R.id.item_title_iv));
                            break;
                        case 2:
                            titleStr = "即将开始";
                            break;
                        default:
                            titleStr = "推荐";
                            break;
                    }
                    ((TextView)viewHolder.itemView.findViewById(R.id.item_title_tv)).setText(titleStr+"");

                }else{
                    viewHolder.itemView.findViewById(R.id.item_title_tv).setVisibility(View.GONE);
                    viewHolder.itemView.findViewById(R.id.item_title_iv).setVisibility(View.GONE);
                }
                if(i == getItemCount()-1){
                    viewHolder.itemView.findViewById(R.id.line_tv).setVisibility(View.GONE);
                }else {
                    viewHolder.itemView.findViewById(R.id.line_tv).setVisibility(View.VISIBLE);
                }
                switch (type){
                    case 2://即将开始
                        detail_task_tv.setText("即将开始");
                        detail_task_tv.setBackground(context.getResources().getDrawable(R.drawable.sp_rectangle_bg_gray_radius));
                        detail_task_tv.setEnabled(false);
                        viewHolder.itemView.setEnabled(false);
                        ((TextView)viewHolder.itemView.findViewById(R.id.item_date_tv)).setText(
                                "开始时间:" + TimeUtil.getDate(TimeUtil.FORMAT, Long.valueOf(etyList.get(i).getOnline_time()))+"");
                        break;
                    default:
                        detail_task_tv.setText("领取任务");
                        detail_task_tv.setBackground(context.getResources().getDrawable(R.drawable.sp_bg_gradient_rectangle_blue));
                        detail_task_tv.setEnabled(true);
                        viewHolder.itemView.setEnabled(true);
                        ((TextView)viewHolder.itemView.findViewById(R.id.item_date_tv)).setText(
                                "截止时间:" + TimeUtil.getDate(TimeUtil.FORMAT, Long.valueOf(etyList.get(i).getDeadline()))+"");
                        break;
                }
                viewHolder.itemView.findViewById(R.id.cancel_task_tv).setVisibility(View.GONE);

                //CommonUtil.getInstance().getCharSequence(context, etyList.get(i).getName(), "")
                ((TextView)viewHolder.itemView.findViewById(R.id.item_anem_tv)).setText(etyList.get(i).getName()+"");
                TextView task_type_tv = viewHolder.itemView.findViewById(R.id.task_type_tv);
                //设置标签颜色task_type_tv
                if(!TextUtils.isEmpty(etyList.get(i).getChild_task_name())){
                    task_type_tv.setVisibility(View.VISIBLE);
                    task_type_tv.setText(etyList.get(i).getChild_task_name() + "");
                    CommonUtil.getInstance()
                            .setViewBackground(
                                    task_type_tv,
                                    etyList.get(i).getLabel_color()+"");
                }else {
                    task_type_tv.setVisibility(View.INVISIBLE);
                }


                ((TextView)viewHolder.itemView.findViewById(R.id.item_num_tv)).setText("剩余"+ etyList.get(i).getLast_num()+"份");
                ((TextView)viewHolder.itemView.findViewById(R.id.item_money)).setText("+"+ etyList.get(i).getBonus() +"元");

                viewHolder.itemView.findViewById(R.id.detail_task_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(!ListUtil.hasIndex(etyList, i)){
                            return;
                        }
                        TaskEty taskEty = etyList.get(i).getTask();
                        taskEty.setRunTask(0);
                        taskEty.setRelease_task_id(etyList.get(i).getId());
                        taskEty.setName(etyList.get(i).getName());
                        taskEty.setAcceptedTaskId(etyList.get(i).getAccepted_task_id());
                        Jump2View.getInstance().goDialogActivityView(context, taskEty, taskAcceptedEty);
                    }
                });
                Glide.with(context)
                        .load(etyList.get(i).getTask().getIcon()+"")
                        .apply(new RequestOptions().placeholder(R.mipmap.x_ic_def_head))
                        .into((ImageView) viewHolder.itemView.findViewById(R.id.item_icon_iv));
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(!ListUtil.hasIndex(etyList, i)){
                            return;
                        }
                        TaskEty taskEty = etyList.get(i).getTask();
                        taskEty.setRunTask(0);
                        taskEty.setBonus(etyList.get(i).getBonus());
                        taskEty.setRelease_task_id(etyList.get(i).getId());
                        taskEty.setName(etyList.get(i).getName());
                        Jump2View.getInstance().goTaskDetailView(context,  etyList.get(i).getId());
                    }
                });
                TestUtil.setDebugDownLoad(context, viewHolder.itemView, etyList.get(i).getTask());

            }

            @Override
            public int getItemCount() {
                return etyList.size();
            }
        });
    }

    /**
     * 暂时这么处理，也许以后也是列表了
     * @param holder
     * @param etyList
     */
    private void bindRunTask(ViewHolder holder, final List<TaskAcceptedEty> etyList){
        RecyclerView recyclerView = holder.getView(R.id.release_task_listview, RecyclerView.class);
        recyclerView.setHasFixedSize(true);
//        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,
//                StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(new RecyclerView.Adapter(){

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                LinearLayout view = (LinearLayout) LayoutInflater.from(context)
                        .inflate(R.layout.try_makemoney_item_recommend, viewGroup,false);
                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view) {
                    @Override
                    public String toString() {
                        return super.toString();
                    }
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
                if(etyList.get(i) == null
                        || etyList.get(i).getRelease_task() == null
                        || etyList.get(i).getRelease_task().getTask() == null){
                    return;
                }
                    viewHolder.itemView.setTag(TAG_ID_TEMP, etyList.get(i).getId());
                if(i == 0){

                    viewHolder.itemView.findViewById(R.id.item_title_tv).setVisibility(View.VISIBLE);
                    ((TextView)viewHolder.itemView.findViewById(R.id.item_title_tv)).setText("进行中");
                }else{
                    viewHolder.itemView.findViewById(R.id.item_title_tv).setVisibility(View.GONE);
                    viewHolder.itemView.findViewById(R.id.item_title_iv).setVisibility(View.GONE);
                }
                viewHolder.itemView.findViewById(R.id.line_tv).setVisibility(View.GONE);

                viewHolder.itemView.findViewById(R.id.cancel_task_tv).setVisibility(View.GONE);

                ((TextView)viewHolder.itemView.findViewById(R.id.item_anem_tv)).setText(etyList.get(i).getRelease_task().getName()+"");
                ((TextView)viewHolder.itemView.findViewById(R.id.item_num_tv)).setText("剩余"+ etyList.get(i).getRelease_task().getLast_num()+"份");
                ((TextView)viewHolder.itemView.findViewById(R.id.item_money)).setText("+"+ etyList.get(i).getRelease_task().getBonus() +"元");
                ((TextView)viewHolder.itemView.findViewById(R.id.item_date_tv)).setText(
                        "截止时间:" + TimeUtil.getDate(TimeUtil.FORMAT, Long.valueOf(etyList.get(i).getRelease_task().getDeadline()))+"");

                ((TextView)viewHolder.itemView.findViewById(R.id.detail_task_tv)).setText("取消任务");

                if((is_succession == 1 || is_succession == 3)
                        &&  (etyList.get(i).getChild_task_id() > 1
                                || (etyList.get(i).getChild_task_id() == 1
                        && (etyList.get(i).getStatus() == 6 || etyList.get(i).getStatus() == 9)))
                        ){
                    viewHolder.itemView.findViewById(R.id.detail_task_tv).setVisibility(View.GONE);
                }else {

                    viewHolder.itemView.findViewById(R.id.detail_task_tv).setVisibility(View.VISIBLE);
                }


                TextView task_type_tv = viewHolder.itemView.findViewById(R.id.task_type_tv);

                //设置标签颜色task_type_tv
                if(!TextUtils.isEmpty(etyList.get(i).getRelease_task().getChild_task_name())){
                    task_type_tv.setVisibility(View.VISIBLE);
                    task_type_tv.setText(etyList.get(i).getRelease_task().getChild_task_name() + "");
                    CommonUtil.getInstance()
                            .setViewBackground(
                                    task_type_tv,
                                    etyList.get(i).getRelease_task().getLabel_color()+"");
                }else {
                    task_type_tv.setVisibility(View.INVISIBLE);
                }
                viewHolder.itemView.findViewById(R.id.detail_task_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        presenter.giveUpTask(etyList.get(i).getId());
                        //暂停下载
                        CommonUtil.getInstance().stopDownloadTask(mContext, etyList.get(i).getRelease_task().getTask().getDownload_link());

                    }
                });
                Glide.with(context)
                        .load(etyList.get(i).getRelease_task().getTask().getIcon()+"")
                        .apply(new RequestOptions().placeholder(R.mipmap.x_ic_def_head))
                        .into((ImageView) viewHolder.itemView.findViewById(R.id.item_icon_iv));
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        TaskEty taskEty = etyList.get(i).getRelease_task().getTask();
                        taskEty.setRunTask(1);
                        taskEty.setBonus(etyList.get(i).getRelease_task().getBonus());
                        taskEty.setRelease_task_id(etyList.get(i).getRelease_task().getId());
                        taskEty.setAcceptedTaskId(etyList.get(i).getId());
                        taskEty.setName(etyList.get(i).getRelease_task().getName());
                        Jump2View.getInstance().goTaskDetailView(context,  etyList.get(i).getRelease_task().getId());
                        UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_DETAIL);
                    }
                });
                TestUtil.setDebugDownLoad(context, viewHolder.itemView, etyList.get(i).getRelease_task().getTask());

                /**
                 * 倒计时
                 */
                final TextView countdown_tv = viewHolder.itemView.findViewById(R.id.countdown_tv);
                if(etyList.get(i).getEnd_time() > 0){
                    SelfCountDownTimer scTimer = timerHashMap.get(countdown_tv);
                    if(scTimer != null){
                        scTimer.cancel();
                        scTimer = null;
                    }

                    countdown_tv.setVisibility(View.VISIBLE);
                    String sr = "若<font color='#ff2d4b'><small>" + "" + "</small></font>后任务未完成，该任务自动取消，您可以重新接受该任务";
                    countdown_tv.setText(sr+"");
                    SelfCountDownTimer selfCountDownTimer = new SelfCountDownTimer( etyList.get(i).getEnd_time() * 1000, 1000, etyList.get(i).getRelease_task().getCancel_duration()) {
                        @Override
                        public void onTimerRest() {
                            countdown_tv.setText("");
                        }

                        @Override
                        public void onTimerTick(long millisUntilFinished, int counTime) {
                            countdown_tv.setText(Html.fromHtml(CommonUtil.getInstance().assemblyString(TimeUtil.getHours(millisUntilFinished))+""));
                        }

                        @Override
                        public void onTimerFinish() {
                            countdown_tv.setVisibility(View.GONE);
//                            presenter.giveUpTask(etyList.get(i).getId());
//                            //暂停下载
//                            CommonUtil.getInstance().stopDownloadTask(mContext, etyList.get(i).getRelease_task().getTask().getDownload_link());
                        }
                    };
                    selfCountDownTimer.reset(etyList.get(i).getRelease_task().getCancel_duration());
                    selfCountDownTimer.start();
                    timerHashMap.put(countdown_tv, selfCountDownTimer);
                }else {
                    countdown_tv.setVisibility(View.GONE);
                }

            }

            @Override
            public int getItemCount() {
                return etyList.size();
            }
        });
    }

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

    public void refreshAdapter(){
        notifyDataSetChanged();
    }

    public boolean isEmpty() {
        switch (type){
            case 0://推荐任务

                if(getmListDatas().get(0) != null
                        && getmListDatas().get(0).getRecyleType() == RUN_TASK
                        && ((List<TaskAcceptedEty>)getmListDatas().get(0).getDataObj()).size() > 0){
                    return false;
                }else {
                    return true;
                }
            case 2://即将开始
                return true;
        }
        return false;
    }
}
