package com.mjsheng.myappstore.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
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 com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.activity.SubjectMoreActivity;
import com.mjsheng.myappstore.adapter.BrandListAdapter;
import com.mjsheng.myappstore.bean.CategoryPicBean;
import com.mjsheng.myappstore.bean.CommonPicBean;
import com.mjsheng.myappstore.bean.CommonPicData;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.bean.ProjectDateInfo;
import com.mjsheng.myappstore.bean.ProjectPicBean;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.dialog.NoSnDialog;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.CategoryPicApi;
import com.mjsheng.myappstore.network.api.ProjectPicApi;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SpacesItemDecoration;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.view.RecycleGridLayoutManager;
import com.mjsheng.myappstore.view.VaryViewHelper;
import com.mjsheng.myappstore.widget.Sound;

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

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.internal.Util;


public class ProjectFragment extends Fragment {


    private View view;
    private RecyclerView mRecyclerView;
    private BrandListAdapter mProjectListAdapter;
    private List<CommonPicData> allList = new ArrayList<>();
    private VaryViewHelper mVaryViewHelper;
    private Sound sound;

    private RecycleGridLayoutManager mManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.brand_fragment_layout, container, false);
        mVaryViewHelper = new VaryViewHelper.Builder()
                .setContent(getContext())
                .setDataView(view.findViewById(R.id.brand_fragment_recycleView))//放数据的父布局，逻辑处理在该Activity中处理
                .setLoadingView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_loadingview, null))//加载页，无实际逻辑处理
                .setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_emptyview, null))//空页面，无实际逻辑处理
                .setErrorView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_errorview, null))//错误页面
                .setRefreshListener(new ProjectFragment.ErrorClickListener())//错误页点击刷新实现
                .build();
        sound = new Sound(getContext());
        initView();
        mVaryViewHelper.showLoadingView();
        return view;
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            mVaryViewHelper.showLoadingView();
            loadDatas();
        }
    }
    public void initView() {
        mRecyclerView = view.findViewById(R.id.brand_fragment_recycleView);
        int orientation = getActivity().getResources().getConfiguration().orientation;
        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mManager = new RecycleGridLayoutManager(getContext(), 2);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mManager = new RecycleGridLayoutManager(getContext(), 3);
                break;
        }
        mManager.setOrientation(GridLayoutManager.VERTICAL);
        mManager.setSmoothScrollbarEnabled(true);
        mRecyclerView.setLayoutManager(mManager);
        mRecyclerView.setNestedScrollingEnabled(false);

        mRecyclerView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x)));
        ((DefaultItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        loadDatas();

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        // 当ListView处于滑动状态时，停止加载图片，保证操作界面流畅
                        Glide.with(getActivity()).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        // 当ListView处于静止状态时，继续加载图片
                        Glide.with(getActivity()).resumeRequests();
                        break;
                }
            }
        });
        mProjectListAdapter = new BrandListAdapter(allList, getActivity());
        mProjectListAdapter.click = new BrandListAdapter.BrandItemClick() {
            @Override
            public void brandItemClick(int position) {
                showMoreSubject(Configure.HTTP_TAG_PROJECT_DETAILS_URL, allList.get(position).getName(), allList.get(position).getId());
            }
        };
        mRecyclerView.setAdapter(mProjectListAdapter);

    }

    private void loadDatas() {
        ProjectPicApi projectPicApi = Network.getProjectPicApi();
        projectPicApi.getProjectPicApi(Configure.HTTP_KEY, Utils.getSerial(), "1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonPicBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CommonPicBean projectPicBean) {
                        paraData(projectPicBean);
                        Log.e("mjsheng", "projectPicBean---" + projectPicBean.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        mVaryViewHelper.showErrorView();
                        Log.e("mjsheng", "projectPicBean---error----" + e.getMessage());

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void paraData(CommonPicBean categoryPicBean) {
        int code = categoryPicBean.getCode();
        switch (code) {
            case 200:
                allList = categoryPicBean.getData();
                if (allList != null && allList.size() > 0) {
                    mProjectListAdapter.addData(allList);
                    mVaryViewHelper.showDataView();
                } else {
                    mVaryViewHelper.showEmptyView();
                }
                break;
            case -200:
                paraError(categoryPicBean.getMsg());
                mVaryViewHelper.showEmptyView();
                break;
        }
    }
    private NoSnDialog mNoSnDialog;
    private void paraError(String msg) {
        switch (msg) {
            case "没有找到SN码":
                if (mNoSnDialog == null) {
                    mNoSnDialog = new NoSnDialog(getActivity());
                }
                if (!mNoSnDialog.isShowing()) {

                    mNoSnDialog.show();
                }
                break;
            default:
                Utils.showToast(getContext(), msg);
                break;
        }
    }

    private void showMoreSubject(String url, String title, String id) {
        Intent intent = new Intent(getActivity(), SubjectMoreActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("URL", url);
        bundle.putString("title", title);
        bundle.putString("id", id);
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }


    private class ErrorClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            sound.playSoundEffect();
            switch (v.getId()) {
                case R.id.iv_errorview_layout:
                    mVaryViewHelper.showLoadingView();
                    loadDatas();
                    break;
                case R.id.iv_emptyview_layout:
                    mVaryViewHelper.showLoadingView();
                    loadDatas();
                    break;
            }
        }
    }


}
