package com.zhilin.patrol.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.fuyin.constans.P;
import com.fuyin.interfaces.OnItemPictureClickListener;
import com.fuyin.ui.ImagePreviewActivity;
import com.fuyin.views.NineGridTestLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhilin.patrol.R;
import com.zhilin.patrol.bean.FinishTaskEntity;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.bean.MyTaskEntity;
import com.zhilin.patrol.bean.TaskTypeEntity;
import com.zhilin.patrol.http.HttpUrl;
import com.zhilin.patrol.tool.DensityUtil;
import com.zhilin.patrol.tool.DialogUtil;
import com.zhilin.patrol.tool.IpUtils;
import com.zhilin.patrol.tool.JsonUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 抽样，整改，逾期类型任务
 */
public class TaskTypeActivity extends BaseActivity {

    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    MaterialRefreshLayout mRefreshLayout;

    private boolean mIsFirst;

    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    private List<TaskTypeEntity.InfoListBean> mList;
    private CommonAdapter<TaskTypeEntity.InfoListBean> mAdapter;

    private int mPage = 1;
    /**
     * 0-未完成任务
     * 1-普通任务
     */
    private int type;
    private String planCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_task);
        ButterKnife.bind(this);

        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getIntent().getSerializableExtra("userInfo");
        type = getIntent().getIntExtra("type", 0);
        planCode = getIntent().getStringExtra("planCode");
        if (type == 4) {
            setTitle("抽样任务");
        } else if (type == 3) {
            setTitle("整改任务");
        } else if (type == 5) {
            setTitle("逾期任务");
        }else if (type == 6) {
            setTitle("任务点位");
        }
        else if (type == 7) {
            setTitle("上月整改不通过任务");
        }
        init();

        showLoadingView();
        mIsFirst = true;
        request();
    }

    @Override
    public void request() {
        String ipAddress = IpUtils.getIpAddress(this);

        Log.i("1111","_________");
        Log.i("1111","userCode="+mUserInfo.getUserCode());
        Log.i("1111","userRole="+mUserInfo.getUserRole());
        Log.i("1111","page="+mPage);
        Log.i("1111","planType="+type);
        Log.i("1111","planCode="+planCode);
        Log.i("1111","userIP="+ipAddress);
        OkHttpUtils.post()
                .url(HttpUrl.GET_REUPLOAD_LIST_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("page", mPage + "")
                .addParams("planType", type + "")
                .addParams("planCode", planCode)
                .addParams("userIP", ipAddress)
                .build().execute(new Callback<TaskTypeEntity>() {
            @Override
            public TaskTypeEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (TaskTypeEntity) JsonUtils.parseJson2Obj(jsonStr, TaskTypeEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (mIsFirst) {
                    showFailView();
                } else {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishRefreshLoadMore();
                }
                DialogUtil.showNetFailDialog(TaskTypeActivity.this);
            }

            @Override
            public void onResponse(TaskTypeEntity entity, int id) {
                if (mIsFirst) {
                    showContentView();
                } else {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishRefreshLoadMore();
                }
                mIsFirst = false;
                if (entity == null) {
                    DialogUtil.showErrDialog(TaskTypeActivity.this, "返回信息为空");
                    return;
                }
                List<TaskTypeEntity.InfoListBean> list = entity.getInfoList();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(TaskTypeActivity.this, entity.getReturnMsg());
                    return;
                }
                if (list == null) {
                    mRefreshLayout.setLoadMore(false);
                    return;
                }
                if (list.size() < 10) {
                    mRefreshLayout.setLoadMore(false);
                }
                if (mPage == 1) {
                    mList.clear();
                }
                mList.addAll(list);
                mAdapter.notifyDataSetChanged();
                mPage++;
                if (mList.isEmpty()) {
                    showEmptyView();
                }
            }
        });
    }
    /*public void request2() {
        TaskTypeEntity.InfoListBean bean=null;
        Log.i("1111","_________结束任务接口");
        Log.i("111","mUserInfo.getUserCode()="+mUserInfo.getUserCode());
        Log.i("111","mbean.getPCode()="+planCode);
        OkHttpUtils.post()
                .url(HttpUrl.FINISH_TASK)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("pCode", planCode)
                .build().execute(new Callback<FinishTaskEntity>() {
            @Override
            public FinishTaskEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                Log.i("1111","json=="+jsonStr);
                return (FinishTaskEntity) JsonUtils.parseJson2Obj(jsonStr, FinishTaskEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                DialogUtil.showNetFailDialog(TaskTypeActivity.this);
            }

            @Override
            public void onResponse(FinishTaskEntity response, int id) {
                if (response == null) {
                    DialogUtil.showErrDialog(TaskTypeActivity.this, "返回信息为空");
                    return;
                }
                if (!"1000".endsWith(response.getReturnCode())) {
                    DialogUtil.showErrDialog(TaskTypeActivity.this, response.getReturnMsg());
                    return;
                }
                if ("1000".endsWith(response.getReturnCode())) {
                    DialogUtil.showErrDialog(TaskTypeActivity.this, "提交完成");
                    return;
                }
                Log.i("111","response.getReturnCode()=="+response.getReturnCode());
            }
        });
    }*/
    private void init() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);
        mList = new ArrayList<>();
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.line_gray))
                .size(DensityUtil.dip2px(this, 1))
                .build());
        if (type == 3) {//整改任务
        /*    mAdapter = new CommonAdapter<TaskTypeEntity.InfoListBean>(this, R.layout.item_rectify_task, mList) {//item_rectify_task   item_type_task
                @Override
                protected void convert(ViewHolder holder, final TaskTypeEntity.InfoListBean bean, int position) {
//                    if(bean.getIsFinish().equals("0")){
                        holder.setText(R.id.tv_add, bean.getAddress());
                        holder.setOnClickListener(R.id.tv_add, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                            }
                        });
                        holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                List<String> questionArr = bean.getQuestionArr();
                                StringBuilder sb = new StringBuilder("");
                                if (questionArr != null && !questionArr.isEmpty()) {
                                    int size = questionArr.size();
                                    for (int i = 0; i < size; i++) {
                                        sb.append(" • ").append(questionArr.get(i));
                                        if (i != (size - 1)) {
                                            sb.append("\n");
                                        }
                                    }
                                }
                                String text = sb.toString();
//                                toActivityRecify(RecifyUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),text);
                            }
                        });
                        holder.setOnClickListener(R.id.tv_check, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                MapActivity.toMap(TaskTypeActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                            }
                        });

                        List<String> questionArr = bean.getQuestionArr();
                        StringBuilder sb = new StringBuilder("");
                        if (questionArr != null && !questionArr.isEmpty()) {
                            int size = questionArr.size();
                            for (int i = 0; i < size; i++) {
                                sb.append(" • ").append(questionArr.get(i));
                                if (i != (size - 1)) {
                                    sb.append("\n");
                                }
                            }
                        }
                        String text = sb.toString();
                        if (TextUtils.isEmpty(text)) {
                            holder.setVisible(R.id.tv_question, false);
                        } else {
                            holder.setVisible(R.id.tv_question, true);
                            holder.setText(R.id.tv_question, text);
                        }
                *//*    int taskNum=Integer.parseInt(bean.getTaskNum());
                    if (taskNum <= bean.getFinishNum()) {
//                            int n=(Integer) v.getTag();
                        holder.setVisible(R.id.tv_add, true);
                        holder.setVisible(R.id.btn_to_rl_upload2, true);
                        holder.setVisible(R.id.tv_check, true);
                    } else {
                        holder.setVisible(R.id.tv_add, false);
                        holder.setVisible(R.id.btn_to_rl_upload2, false);
                        holder.setVisible(R.id.tv_check, false);
                    }*//*
                      *//*  holder.setOnClickListener(R.id.tv_check3, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                int taskNum=Integer.parseInt(bean.getTaskNum());
                                int finishNum=bean.getFinishNum();
                                if(taskNum<=finishNum){
                                    request2();
                                    Log.i("111","整改任务完成*******");
                                }else{
                                    DialogUtil.showErrDialog(TaskTypeActivity.this, "未完成");
                                }
                            }
                        });*//*

                    *//*}else {
                        View view  = holder.getView(R.id.tv_add);
                        view.setVisibility(View.GONE);//VISIBLE
                        View view2  = holder.getView(R.id.btn_to_rl_upload2);
                        view2.setVisibility(View.GONE);
                        View view3  = holder.getView(R.id.tv_check);
                        view3.setVisibility(View.GONE);
                        View view4  = holder.getView(R.id.tv_question);
                        view4.setVisibility(View.GONE);
                        View view5  = holder.getView(R.id.tv_check3);
                        view5.setVisibility(View.GONE);
                    }*//*

                }
            };*/
        }
        else if(type==7) {//整改不通过任务
            mAdapter = new CommonAdapter<TaskTypeEntity.InfoListBean>(this, R.layout.item_type_task, mList) {
                @Override
                protected void convert(ViewHolder holder, final TaskTypeEntity.InfoListBean bean, int position) {
//                    if(bean.getIsFinish().equals("0")){
                    holder.setText(R.id.tv_add, bean.getAddress() + "(需巡" + bean.getTaskNum() + "次|" + "已巡" + bean.getPostNum() + "次)");
                    holder.setOnClickListener(R.id.tv_add, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            toActivity(PatrolUploadActivity.class, mUserInfo, bean.getPCode(), bean.getAddress(),type);
                        }
                    });
                    holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            toActivity(PatrolUploadActivity.class, mUserInfo, bean.getPCode(), bean.getAddress(),type);
                        }
                    });
                    holder.setOnClickListener(R.id.tv_check, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MapActivity.toMap(TaskTypeActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                        }
                    });
                }
            };
        }
        else if(type==4){//抽样任务
            mAdapter = new CommonAdapter<TaskTypeEntity.InfoListBean>(this, R.layout.item_type_task, mList) {
                @Override
                protected void convert(ViewHolder holder, final TaskTypeEntity.InfoListBean bean, int position) {
//                    if(bean.getIsFinish().equals("0")){
                    holder.setText(R.id.tv_add, bean.getAddress() + "(需巡"+bean.getTaskNum()+"次|"+"已巡"+bean.getPostNum()+"次)");
                    holder.setOnClickListener(R.id.tv_add, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                        }
                    });
                    holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                        }
                    });
                    holder.setOnClickListener(R.id.tv_check, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MapActivity.toMap(TaskTypeActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                        }
                    });
           /*         int taskNum=Integer.parseInt(bean.getTaskNum());
                    if (taskNum <= bean.getFinishNum()) {
//                            int n=(Integer) v.getTag();
                        holder.setVisible(R.id.tv_add, true);
                        holder.setVisible(R.id.btn_to_rl_upload2, true);
                        holder.setVisible(R.id.tv_check, true);
                    } else {
                        holder.setVisible(R.id.tv_add, false);
                        holder.setVisible(R.id.btn_to_rl_upload2, false);
                        holder.setVisible(R.id.tv_check, false);
                    }*/
                    /*holder.setOnClickListener(R.id.tv_check3, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int taskNum=Integer.parseInt(bean.getTaskNum());
                            int finishNum=bean.getFinishNum();
                            if(taskNum<=finishNum){
                                request2();
                                Log.i("111","抽样任务完成*******");
                            }else{
                                DialogUtil.showErrDialog(TaskTypeActivity.this, "未完成");
                            }
                        }
                    });*/
//                }
                    /*else {
                        View view  = holder.getView(R.id.tv_add);
                        view.setVisibility(View.GONE);//VISIBLE
                        View view2  = holder.getView(R.id.btn_to_rl_upload2);
                        view2.setVisibility(View.GONE);
                        View view3  = holder.getView(R.id.tv_check);
                        view3.setVisibility(View.GONE);
                        View view5  = holder.getView(R.id.tv_check3);
                        view5.setVisibility(View.GONE);
                    }*/
                }
            };
        }
        else if(type==5){//逾期任务
            mAdapter = new CommonAdapter<TaskTypeEntity.InfoListBean>(this, R.layout.item_type_task2, mList) {
                @Override
                protected void convert(ViewHolder holder, final TaskTypeEntity.InfoListBean bean, int position) {
                    Log.i("111","getAddress=="+bean.getAddress());
                    if (bean!=null) {
                        holder.setText(R.id.tv_add, bean.getAddress()+"(需巡"+bean.getTaskNum()+"次|"+"已巡"+bean.getPostNum()+"次)");//
//                        holder.setOnClickListener(R.id.tv_add, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                toActivity(PatrolUploadActivity.class, mUserInfo);
//                            }
//                        });
                        holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                            }
                        });

                /*        int taskNum=Integer.parseInt(bean.getTaskNum());
                        if (taskNum <= bean.getFinishNum()) {
//                            int n=(Integer) v.getTag();
                            holder.setVisible(R.id.tv_add, true);
                            holder.setVisible(R.id.btn_to_rl_upload2, true);
                            holder.setVisible(R.id.tv_check, true);
                        } else {
                            holder.setVisible(R.id.tv_add, false);
                            holder.setVisible(R.id.btn_to_rl_upload2, false);
                            holder.setVisible(R.id.tv_check, false);
                        }*/
                        holder.setOnClickListener(R.id.tv_check, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                MapActivity.toMap(TaskTypeActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                            }
                        });
                    }
                }
            };
        }
        else if(type==6){//任务点位
            mAdapter = new CommonAdapter<TaskTypeEntity.InfoListBean>(this, R.layout.item_type_task, mList) {
                @Override
                protected void convert(ViewHolder holder, final TaskTypeEntity.InfoListBean bean, int position) {
                    holder.setText(R.id.tv_add, bean.getAddress() + "(需巡"+bean.getTaskNum()+"次|"+"已巡"+bean.getPostNum()+"次)");
                    holder.setOnClickListener(R.id.tv_add, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                        }
                    });
                    holder.setOnClickListener(R.id.tv_check, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MapActivity.toMap(TaskTypeActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                        }
                    });
                    holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            toActivity(PatrolUploadActivity.class, mUserInfo,bean.getPCode(),bean.getAddress(),type);
                        }
                    });
           /*         int taskNum=Integer.parseInt(bean.getTaskNum());
                    if (taskNum <= bean.getFinishNum()) {
//                            int n=(Integer) v.getTag();
                        holder.setVisible(R.id.tv_add, true);
                        holder.setVisible(R.id.btn_to_rl_upload2, true);
                        holder.setVisible(R.id.tv_check, true);
                    } else {
                        holder.setVisible(R.id.tv_add, false);
                        holder.setVisible(R.id.btn_to_rl_upload2, false);
                        holder.setVisible(R.id.tv_check, false);
                    }*/
                    /*holder.setOnClickListener(R.id.tv_check3, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int taskNum=Integer.parseInt(bean.getTaskNum());
                            int finishNum=bean.getFinishNum();
                            if(taskNum<=finishNum){
                                request2();
                            }else{
                                DialogUtil.showErrDialog(TaskTypeActivity.this, "未完成");
                            }
                        }
                    });*/
                }
            };
        }
        mRecyclerView.setAdapter(mAdapter);

        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                //refreshing...
                mPage = 1;
                mRefreshLayout.setLoadMore(true);
                request();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                //load more refreshing...
                request();
            }
        });
    }

    public static void toTypeTask(Context context, LoginEntity.InfoListBean.UserInfoBean userInfo, String planCode, int type) {
        Intent intent = new Intent(context, TaskTypeActivity.class);
        intent.putExtra("userInfo", userInfo);
        intent.putExtra("type", type);
        intent.putExtra("planCode", planCode);
        context.startActivity(intent);
    }

}
