package com.zhilin.patrol.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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.LoginEntity;
import com.zhilin.patrol.bean.PatrolRecordEntity;
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.ui.activity.PatrolRecordActivity;
import com.zhilin.patrol.ui.activity.PatrolUploadActivity;
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;

/**
 * 巡查记录的fragment
 */
public class PatrolRecordFragment extends Fragment {

    public static final String TYPE = "type";
    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    MaterialRefreshLayout mRefreshLayout;

    private int itemPosition;
    /**
     * 类型
     */
    private int mType;
    private int mPage = 1;

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        mType = arguments.getInt(TYPE);
        Log.i("aaa","aaa"+mType);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_patrol_record, container, false);
        ButterKnife.bind(this, view);
        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getActivity().getIntent().getSerializableExtra("userInfo");
        init();
        request();
        return view;
    }

    public void request() {
        String ipAddress = IpUtils.getIpAddress(getActivity());
        OkHttpUtils.post()
                .url(HttpUrl.TASK_LIST_URL)
                .addParams("userCode", mUserInfo.getUserCode())
//                .addParams("userCode", "20180619114559kc2tputyb445frazsq")
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("taskType", mType + "")
                .addParams("page", mPage + "")
                .addParams("userIP", ipAddress)
                .build().execute(new Callback<PatrolRecordEntity>() {
            @Override
            public PatrolRecordEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (PatrolRecordEntity) JsonUtils.parseJson2Obj(jsonStr, PatrolRecordEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mRefreshLayout.finishRefresh();
                mRefreshLayout.finishRefreshLoadMore();
                DialogUtil.showNetFailDialog(getActivity());
            }

            @Override
            public void onResponse(PatrolRecordEntity entity, int id) {
                mRefreshLayout.finishRefresh();
                mRefreshLayout.finishRefreshLoadMore();
                if (entity == null) {
                    DialogUtil.showErrDialog(getActivity(), "返回信息为空");
                    return;
                }
                List<PatrolRecordEntity.InfoListBean> list = entity.getInfoList();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(getActivity(), entity.getReturnMsg());
                    return;
                }
                if (list == null) {
                    mRefreshLayout.setLoadMore(false);
                    return;
                }
                if (list.size() < 10) {
                    mRefreshLayout.setLoadMore(false);
                } else {
                    mRefreshLayout.setLoadMore(true);
                }
                if (mPage == 1) {
                    mList.clear();
                }
                mList.addAll(list);
                mAdapter.notifyDataSetChanged();
                mPage++;
            }
        });
    }

    private void init() {
        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();
            }
        });
        FragmentActivity activity = getActivity();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .size(DensityUtil.dip2px(activity, 8))
                .color(getResources().getColor(R.color.bg_gray))
                .build());
        mList = new ArrayList<>();
        mAdapter = new CommonAdapter<PatrolRecordEntity.InfoListBean>(activity, R.layout.item_patrol_record, mList) {
            @Override
            protected void convert(ViewHolder holder, final PatrolRecordEntity.InfoListBean record, int position) {
                TextView statusTv = holder.getView(R.id.tv_status);
                int passState = record.getPassState();
                holder.setText(R.id.tv_add, record.getAddress());
                holder.setText(R.id.tv_date, record.getSubTime());
                if (!TextUtils.isEmpty(record.getQuestion())) {
                    holder.setVisible(R.id.tv_question_type, true);
                    holder.setText(R.id.tv_question_type, record.getQuestion());
                } else {
                    holder.setVisible(R.id.tv_question_type, false);
                }
                //有问题
                if (0 == record.getIsQuestion()) {//没问题
                    holder.setText(R.id.tv_question, "没问题");
                } else {
                    holder.setText(R.id.tv_question, "有问题");
                }
                //指派任务
                holder.setVisible(R.id.tv_assign, 1 == record.getIsAssign());
                //审核状态
                if (-1 == passState) {
                    holder.setVisible(R.id.ll_fail, false);
                    holder.setVisible(R.id.tv_reason, false);
                    holder.setVisible(R.id.tv_desc, false);
                    statusTv.setText("待审核");
                    statusTv.setBackground(getResources().getDrawable(R.drawable.bg_yellow_solid_conner));
                } else if (0 == passState) {
                    statusTv.setText("不通过");
                    statusTv.setBackground(getResources().getDrawable(R.drawable.bg_red_solid_conner));
                    holder.setVisible(R.id.ll_fail, true);
                    String infoExt = record.getInfoExt();
                    if (!TextUtils.isEmpty(infoExt)) {
                        holder.setText(R.id.tv_desc, infoExt);
                        holder.setVisible(R.id.tv_desc, true);
                        holder.setVisible(R.id.line_desc, true);
                    } else {
                        holder.setVisible(R.id.tv_reason, false);
                        holder.setVisible(R.id.line_desc, false);
                    }
                    String reason = record.getReason();
                    if (!TextUtils.isEmpty(reason)) {
                        holder.setText(R.id.tv_reason, "不通过原因: " + reason);
                        holder.setVisible(R.id.tv_reason, true);
                    } else {
                        holder.setVisible(R.id.tv_reason, false);
                    }
                } else if (1 == passState) {
                    statusTv.setText("已通过");
                    holder.setVisible(R.id.ll_fail, false);
                    holder.setVisible(R.id.tv_reason, false);
                    holder.setVisible(R.id.tv_desc, false);
                    statusTv.setBackground(getResources().getDrawable(R.drawable.bg_blue_solid_conner));
                }
                holder.setOnClickListener(R.id.tv_re_upload, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 跳转到上传
                        ((PatrolRecordActivity) getActivity()).toActivityReUpload(PatrolUploadActivity.class, mUserInfo,record.getPlanCode(),record.getPbCode(),record.getAddress());
                    }
                });
                NineGridTestLayout nineGridTestLayout = holder.getView(R.id.nineTestlayout);
                nineGridTestLayout.setItemPosition(position);
                nineGridTestLayout.setIsShowAll(false); //当传入的图片数超过9张时，是否全部显示
                nineGridTestLayout.setSpacing(5); //动态设置图片之间的间隔
                nineGridTestLayout.setUrlList(record.getImgs());
                nineGridTestLayout.setListener(new OnItemPictureClickListener() {
                    @Override
                    public void onItemPictureClick(int item, int position, String url, List<String> urlList, ImageView imageView) {
                        itemPosition = item;
                        Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
                        intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
                        intent.putExtra(P.START_ITEM_POSITION, itemPosition);
                        intent.putExtra(P.START_IAMGE_POSITION, position);
//                        ActivityOptions compat = ActivityOptions.makeSceneTransitionAnimation(getActivity(), imageView, imageView.getTransitionName());
//                        startActivity(intent, compat.toBundle());
                        startActivity(intent);
                        getActivity().overridePendingTransition(0, 0);
                    }
                });
            }
        };
        mRecyclerView.setAdapter(mAdapter);
    }

    public static PatrolRecordFragment newInstance(int type) {
        PatrolRecordFragment fragment = new PatrolRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }
}
