package com.zhilin.patrol.ui.activity;

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

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhilin.patrol.R;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.bean.MyTaskEntity;
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 MyTaskTypeActivity 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<MyTaskEntity.InfoListBean> mList;
    private CommonAdapter<MyTaskEntity.InfoListBean> mAdapter;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_task);
        ButterKnife.bind(this);
        setTitle("普通任务");

        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getIntent().getSerializableExtra("userInfo");

        mIsAll = getIntent().getIntExtra("isAll", 0);
        init();

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

    @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(MyTaskTypeActivity.this);
            }

            @Override
            public void onResponse(MyTaskEntity entity, int id) {
                if (mIsFirst) {
                    showContentView();
                } else {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishRefreshLoadMore();
                }
                mIsFirst = false;
                if (entity == null) {
                    DialogUtil.showErrDialog(MyTaskTypeActivity.this, "返回信息为空");
                    return;
                }
                List<MyTaskEntity.InfoListBean> list = entity.getInfoList();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(MyTaskTypeActivity.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);
        mList = new ArrayList<>();
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.line_gray))
                .size(DensityUtil.dip2px(this, 1))
                .build());
        mAdapter = new CommonAdapter<MyTaskEntity.InfoListBean>(this, R.layout.item_my_task, mList) {
            @Override
            protected void convert(ViewHolder holder, final MyTaskEntity.InfoListBean bean, int position) {
                holder.setText(R.id.tv_add, bean.getDisName());
                final List<MyTaskEntity.Bean> sonArr = bean.getSonArr();
                if (sonArr != null) {
                    holder.setVisible(R.id.tv_check, true);
                    holder.setText(R.id.tv_check, sonArr.size() + "个巡查点");
                } else {
                    holder.setVisible(R.id.tv_check, false);
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//进去详细任务
                        Log.i("click","进去详细任务");
                        MyTaskActivity.toMyTask(MyTaskTypeActivity.this, (ArrayList<MyTaskEntity.Bean>) sonArr,mUserInfo,mIsAll);
                    }
                });
            }
        };
        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 toMyTask(Context context, LoginEntity.InfoListBean.UserInfoBean userInfo, int isAll) {
        Intent intent = new Intent(context, MyTaskTypeActivity.class);
        intent.putExtra("userInfo", userInfo);
        intent.putExtra("isAll", isAll);

        context.startActivity(intent);
    }

}
