package com.zhilin.patrol.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhilin.patrol.R;
import com.zhilin.patrol.bean.FinishTaskEntity;
import com.zhilin.patrol.bean.HomeEntity;
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.zhilin.patrol.tool.SPUtil;
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 android.util.Log;
import okhttp3.Call;
import okhttp3.Response;

/**
 *普通任务
 */
public class MyTaskActivity extends BaseActivity {



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

    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    private int mIsAll;

    private List<MyTaskEntity.Bean> mList = new ArrayList<>();
    private CommonAdapter<MyTaskEntity.Bean> mAdapter;
    public int position=0;
    private int mPage = 1;
    private boolean mIsFirst;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_task);
        ButterKnife.bind(this);
        setTitle("普通任务");
        List<MyTaskEntity.Bean> list = (List<MyTaskEntity.Bean>) getIntent().getSerializableExtra("MyTaskBean");
        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getIntent().getSerializableExtra("userInfo");
        mIsAll = getIntent().getIntExtra("isAll", 0);

        if (list != null) {
            mList.addAll(list);
            Log.i("mlist","********");
        }
        request();
        init();
    }
    @Override
    public void request() {
        String ipAddress = IpUtils.getIpAddress(this);
        Log.i("11111","mUserInfo.getUserCode()="+mUserInfo.getUserCode());
        Log.i("11111","mUserInfo.getUserRole()="+mUserInfo.getUserRole());
        Log.i("11111","mPage="+mPage);
        Log.i("11111","mIsAll="+mIsAll);
        Log.i("11111","ipAddress="+ipAddress);
        OkHttpUtils.post()
                .url(HttpUrl.MY_TASK_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("page", mPage + "")
                .addParams("isAll", mIsAll + "")
                .addParams("userIP", ipAddress)
                .build().execute(new Callback<MyTaskEntity>() {
            @Override
            public MyTaskEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (MyTaskEntity) JsonUtils.parseJson2Obj(jsonStr, MyTaskEntity.class);
            }

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

            @Override
            public void onResponse(MyTaskEntity entity, int id) {
                if (mIsFirst) {
                    showContentView();
                } else {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishRefreshLoadMore();
                }
                mIsFirst = false;
                if (entity == null) {
                    DialogUtil.showErrDialog(MyTaskActivity.this, "返回信息为空");
                    return;
                }
                List<MyTaskEntity.Bean> list = entity.getInfoList().get(0).getSonArr();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(MyTaskActivity.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();
                }
            }
        });
    }

    private void init() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.line_gray))
                .size(DensityUtil.dip2px(this, 1))
                .build());
        mAdapter = new CommonAdapter<MyTaskEntity.Bean>(this, R.layout.item_my_task2, mList) {
            @Override
            protected void convert(final ViewHolder holder, final MyTaskEntity.Bean bean, int position) {
//                if (bean.getIsFinish()==0) {

//                holder.setText(R.id.tv_add, bean.getAddress() + "(巡查" + bean.getFinishNum() + "/" + bean.getTaskNum() + "次)");
//                holder.itemView.setTag(position);
                Log.i("111", "qitaxun///***");
                holder.setText(R.id.tv_add2, bean.getAddress() + "(需巡" + bean.getTaskNum() + "次|"+"已巡"+bean.getPostNum()+"次)");
                holder.setOnClickListener(R.id.btn_to_rl_upload2, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("clickMytaskActivity", "跳转上传页面");
                        Intent intent = new Intent(MyTaskActivity.this, PatrolUploadActivity.class);
                        intent.putExtra("userInfo", mUserInfo);
                        intent.putExtra("isAssign", mIsAll);
                        intent.putExtra("pbCode", "null");
                        intent.putExtra("address",bean.getAddress());
                        intent.putExtra("pCode",bean.getPCode());
                        startActivity(intent);
                    }
                });

                holder.setOnClickListener(R.id.tv_check2, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MapActivity.toMap(MyTaskActivity.this, Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude()), bean.getAddress());
                    }
                });
            }
        };
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setLoadMore(false);
        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                //refreshing...
                mPage = 1;
                mRefreshLayout.finishRefresh();
                request();
            }

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

    public static void toMyTask(Context context, ArrayList<MyTaskEntity.Bean> list,LoginEntity.InfoListBean.UserInfoBean userInfo, int isAll) {
        Intent intent = new Intent(context, MyTaskActivity.class);
        intent.putExtra("MyTaskBean", list);
        intent.putExtra("userInfo", userInfo);
        intent.putExtra("isAssign", isAll);
        context.startActivity(intent);
    }

}
