package com.tofly.ghrq_route.common.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.lcp.arecyclerview.widget.ARecyclerBaseAdapter;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.module.plan.PlanTool;
import com.tofly.ghrq_route.module.plan.domain.ChildPlanCountBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zombiexq on 2016/7/6.
 */
    public class PlanAdapter extends ARecyclerBaseAdapter<PlanAdapter.MyViewHolder, PlanBean> {

    private Context mContext;
    private List<PlanBean> mPlanlist;
    private Set<Integer> selectedPostions = new HashSet<>();
    private boolean isChoiceMode = false;
    private OnItemClickListener mItemClickListener;
    private PlanTool planTool;


    public PlanAdapter(Context context, List<PlanBean> planlist) {
        super(context, planlist);
        this.mContext = context;
        this.mPlanlist = planlist;
        planTool = PlanTool.getInstance();
    }

    public void setData(List<PlanBean> data){
        mPlanlist = data;
        notifyDataSetChanged();
    }

    public void setData(PlanBean data){
        for (int i = 0; i < mPlanlist.size(); i++){
            PlanBean planBean = mPlanlist.get(i);
            if (planBean != null && planBean.getPlan_id().equals(data.getPlan_id())){
                mPlanlist.set(i, data);
                notifyItemChanged(i);
                break;
            }
        }
    }


    public void setChoiceMode(){
        isChoiceMode = true;
        notifyDataSetChanged();
    }

    public boolean getChoiceMode(){
        return isChoiceMode;
    }

    public Set<Integer> getSelectedPositionSet() {
        return selectedPostions;
    }

    public void toggleSelection(int position){
        if (selectedPostions.contains(position)){
            selectedPostions.remove(position);
        }else {
            selectedPostions.add(position);
        }
        notifyItemChanged(position);
    }

    public void allSelected() {
        selectedPostions.clear();
        for (int i = 0; i < mPlanlist.size(); i++)
            selectedPostions.add(i);
        this.notifyDataSetChanged();
    }

    public void cancelSelected() {
        selectedPostions.clear();
        this.notifyDataSetChanged();
    }


    public void cancelSelectedExitChoice() {
        isChoiceMode = false;
        selectedPostions.clear();
        this.notifyDataSetChanged();
    }

    public void updateItemPercent(String plan_id, String percent){
        for (int i = 0; i < mPlanlist.size(); i++){
            PlanBean planBean = mPlanlist.get(i);
            if (planBean != null && planBean.getPlan_id().equals(plan_id)){
                planBean.setPercent1(percent);
                notifyItemChanged(i);
                break;
            }
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    public void setItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

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

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View rootView = LayoutInflater.from(mContext)
                .inflate(R.layout.listview_plan_item, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(rootView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder viewHolder, final int position) {
        PlanBean plan = mPlanlist.get(position);
        if (plan != null){
            int plan_mode = plan.getPlan_mode();
            viewHolder.imagePlanMode.setImageResource(plan_mode == UserBean.PATROL_TYPE_CAR ?
                    R.mipmap.profile_car_mode : R.mipmap.ic_schedule_pink_24dp);

            String periodName = plan.getPeriod_name();
            String deviceType = plan.getDevice_type_name();
            if (deviceType != null && !deviceType.isEmpty()){
                periodName = String.format("%s (%s)", periodName, deviceType);
            }
            viewHolder.textPlanType.setText(periodName);
            viewHolder.textPlanType.setTextColor(mContext.getResources().getColor(R.color.black));

            viewHolder.textTransferApply.setVisibility(View.GONE);
            int plan_state = plan.getPlan_state();
            if (plan_state == PlanBean.PlAN_STATE_TYPE.PLAN_STATE_UNSTARTED_TRANSFER_APPLY ||
            plan_state == PlanBean.PlAN_STATE_TYPE.PLAN_STATE_ING_TRANSFER_APPLY) {
                viewHolder.textTransferApply.setVisibility(View.VISIBLE);
            }

            String planName = "";
            if (plan.getPlan_name() != null && !plan.getPlan_name().isEmpty()){
                planName = plan.getPlan_name();
            }
            viewHolder.textPlanRemark.setText(planName);
            /*String strCreateTime, strBeginDate, strEndDate;
            strCreateTime = plan.getCreate_time()*//*DateUtils.formatTime(plan.getCreate_time())*//*;
            if (strCreateTime != null)
                viewHolder.textPlanCreateTime.setText(strCreateTime);
            strBeginDate = plan.getPlan_begindate();
            if (strBeginDate != null){
                strBeginDate = DateUtils.formatTimeYMD(strBeginDate);
                viewHolder.textPlanStartTime.setText(strBeginDate);
            }
            strEndDate = plan.getPlan_enddate();
            if (strEndDate != null){
                strEndDate = DateUtils.formatTimeYMD(strEndDate);
                viewHolder.textPlanEndTime.setText(strEndDate);
            }

            int status = plan.getPlan_state();
            String plan_process_name = plan.getProcess_name();
            if (plan_process_name != null && !plan_process_name.isEmpty()){
                viewHolder.textPlanStatus.setText(plan_process_name);
            }else {
                String inState[] = mContext.getResources().getStringArray(R.array.plan_process_state);
                if (status >= 0 && status < inState.length){
                    String strState = inState[status];
                    if (strState != null){
                        viewHolder.textPlanStatus.setText(strState);
                    }
                }
            }

            if (status != PlanBean.PLAN_STATE_OFF && status != PlanBean.PLAN_STATE_OVER){
                viewHolder.textPlanStatus.setTextColor(mContext.getResources().getColor(R.color.colorAccent));
            }else {
                viewHolder.textPlanStatus.setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
            }*/

            /*到位情况*/
            /*double percent_over = 0;
            if (plan.getPercent() != null){
                percent_over = Double.parseDouble(plan.getPercent());
            }
            if (percent_over >= 1)
                percent_over = 1;
            if (percent_over <= 0)
                percent_over = 0;
            String strOverPercent = (int)(percent_over * 100) + "%";
            viewHolder.textOverPercent.setText(strOverPercent);*/

                /*完成率*/
            double percent_finish = 0;
            if (plan.getPercent2() != null && !plan.getPercent2().isEmpty()){
                percent_finish = Double.parseDouble(plan.getPercent2());
            }
            if (percent_finish >= 1)
                percent_finish = 1;
            if (percent_finish <= 0)
                percent_finish = 0;
            String strFinishPercent = (int)Math.round(percent_finish * 100) + "%";
            viewHolder.textPlanPercent.setText(strFinishPercent);

            /*int valid = plan.getIsvalid();
            String validState[] = mContext.getResources().getStringArray(R.array.plan_valid_state);
            String strValid = validState[valid];
            if (strValid != null){
                viewHolder.textPlanValid.setText(strValid);
            }

            int check = plan.getCheck_state();
            String checkState[] = mContext.getResources().getStringArray(R.array.plan_check_state);
            if (check < checkState.length){
                String strCheck = checkState[check];
                if (strCheck != null){
                    viewHolder.textPlanCheck.setText(strCheck);
                }
            }*/

            viewHolder.textPlanUndown.setVisibility(View.GONE);
            if (isChoiceMode){
                viewHolder.checkBoxPlan.setVisibility(View.VISIBLE);
                boolean iscChecked = selectedPostions.contains(position);
                viewHolder.checkBoxPlan.setChecked(iscChecked);
            }else {
                viewHolder.checkBoxPlan.setVisibility(View.GONE);

                if (C.bPlanDetailNFCModual_debug){
                    int serverCount = plan.getPoint_num();
                    long localCount = planTool.getOfflinePathPlanCounts(plan.getPlan_id());
                    if (serverCount == 0 || (serverCount > 0 && localCount < serverCount)){
/*                    int unDonw = serverCount - (int) localCount;
                    String textUndown = String.format(mContext.getResources().getString(R.string.text_plan_undownloaded), unDonw);
                    viewHolder.textPlanUndown.setText(textUndown);
                    viewHolder.textPlanUndown.setVisibility(View.VISIBLE);*/
                        viewHolder.textPlanType.setTextColor(mContext.getResources().getColor(R.color.red2));
                    }
                }
            }

            viewHolder.itemView.setOnClickListener(v -> {
                //ToastUtil.showToast(mContext, "click " + planType);
                if (mItemClickListener != null){
                    mItemClickListener.onItemClick(v, position);
                }
            });

            viewHolder.checkBoxPlan.setOnClickListener(v -> {
                if (mItemClickListener != null){
                    mItemClickListener.onItemClick(v, position);
                }
            });
        }
    }

    private boolean getUndownCount(PlanBean plan, int[] unDown){
        boolean isUndown = false;
        List<ChildPlanCountBean> todayPlans = SharePreUtil.getPlanPointTodayPlan();
        if (todayPlans != null){
            ChildPlanCountBean retCountBean = null;
            for (ChildPlanCountBean countBean : todayPlans){
                if (countBean.getPlan_id().equals(plan.getPlan_id())){
                    retCountBean = countBean;
                    break;
                }
            }

            if (retCountBean != null){
                int serverCount = retCountBean.getCount();
                long localCount = planTool.getOfflinePathPlanCounts(retCountBean.getPlan_id());
                if (serverCount > 0 && localCount < serverCount){
                    unDown[0] = serverCount - (int)localCount;
                    isUndown = true;
                }
            }
        }
        return isUndown;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.imageview_plan_icon)
        ImageView imagePlanMode;
        @BindView(R.id.text_transfer_apply)
        TextView textTransferApply;
        @BindView(R.id.textview_plan_type)
        TextView textPlanType;
        @BindView(R.id.textview_plan_createTime)
        TextView textPlanCreateTime;
        @BindView(R.id.text_plan_startTime)
        TextView textPlanStartTime;
        @BindView(R.id.img_new)
        ImageView imgNew;
        @BindView(R.id.text_plan_endTime)
        TextView textPlanEndTime;
        @BindView(R.id.text_plan_status)
        TextView textPlanStatus;
        @BindView(R.id.text_over_percent)
        TextView textOverPercent;
        @BindView(R.id.text_plan_percent)
        TextView textPlanPercent;
        @BindView(R.id.text_plan_valid)
        TextView textPlanValid;
        @BindView(R.id.text_plan_check)
        TextView textPlanCheck;
        @BindView(R.id.textview_plan_remark)
        TextView textPlanRemark;
        @BindView(R.id.text_plan_undownloaded)
        TextView textPlanUndown;
        @BindView(R.id.checkbox_plan)
        CheckBox checkBoxPlan;

        public MyViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
