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.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.CategoryTableAdapter;
import com.mjsheng.myappstore.base.MyApplication;
import com.mjsheng.myappstore.bean.CategoryInfo;
import com.mjsheng.myappstore.bean.CategoryPicBean;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.dialog.NoSnDialog;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.CategoryPicApi;
import com.mjsheng.myappstore.utils.Configure;
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;

public class CategoryPageFragment extends Fragment {

    private List<CategoryInfo> mCategoryTableInfos;

    private View view;
    private RecyclerView typeRlv;
    private CategoryTableAdapter mAdapter;
    private int[] typeImg;
    private Sound sound;
    private VaryViewHelper mVaryViewHelper;
    private RecycleGridLayoutManager mManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.category_page_layout, container,
                false);
        mVaryViewHelper = new VaryViewHelper.Builder()
                .setContent(getContext())
                .setDataView(view.findViewById(R.id.rlv_type_category))//放数据的父布局，逻辑处理在该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 ErrorClickListener())//错误页点击刷新实现
                .build();
        sound = new Sound(getContext());
        initView();
        mVaryViewHelper.showLoadingView();
        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //            mVaryViewHelper.showLoadingView();
            loadCategoryTable();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        typeRlv = (RecyclerView) view.findViewById(R.id.rlv_type_category);
        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);
        typeRlv.setLayoutManager(mManager);
        typeRlv.setNestedScrollingEnabled(false);
        typeRlv.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x)));
        ((DefaultItemAnimator) typeRlv.getItemAnimator()).setSupportsChangeAnimations(false);

        mAdapter = new CategoryTableAdapter(getContext(), mCategoryTableInfos, typeImg);
        typeRlv.setAdapter(mAdapter);
        mAdapter.click = new CategoryTableAdapter.BrandItemClick() {
            @Override
            public void brandItemClick(int position) {
                sound.playSoundEffect();
                showMoreSubject(Configure.HTTP_TAG_SYSTEMAPP, mCategoryTableInfos.get(position).getId(),
                        mCategoryTableInfos.get(position).getName());
            }
        };


        loadCategoryTable();
    }

    private void loadCategoryTable() {
        CategoryPicApi categoryPicApi = Network.getCategoryPicApi();
        categoryPicApi.getCategoryPicApi(Configure.HTTP_KEY, Utils.getSerial(), "1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CategoryPicBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

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

                    @Override
                    public void onError(Throwable e) {
                        Utils.showToast(getContext(), "无法连接网络！");
                        Log.e("mjsheng", "categoryPicApi---error----" + e.getMessage());

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void paraData(CategoryPicBean categoryPicBean) {
        int code = categoryPicBean.getCode();
        switch (code) {
            case 200:
                mCategoryTableInfos = categoryPicBean.getData();
                if (mCategoryTableInfos != null && mCategoryTableInfos.size() > 0) {
                    mAdapter.loadmore(mCategoryTableInfos);
                    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 id, String title) {
        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();
                    loadCategoryTable();
                    break;
                case R.id.iv_emptyview_layout:
                    mVaryViewHelper.showLoadingView();
                    loadCategoryTable();
                    break;
            }
        }
    }
}
