package com.mjsheng.myappstore.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
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.blankj.utilcode.util.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.adapter.SubjectMoreAdapter;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppInfoBean;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.callback.MyItemClickListener;
import com.mjsheng.myappstore.dialog.AppDetailDialog;
import com.mjsheng.myappstore.dialog.NoSnDialog;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.AppLimitApi;
import com.mjsheng.myappstore.network.api.RankAppApi;
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 org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

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.ResponseBody;
import rx.Observable;
import rx.functions.Action1;

public class RankingPageFragment extends Fragment {

    private static final int SHOW_DATAVIEW = 101;
    private RecyclerView mRecycleView;
    private SubjectMoreAdapter mAdapter;

    private View view;
    private VaryViewHelper mVaryViewHelper;
    private List<AppDateInfo> allList = new ArrayList<>();
    private Sound sound;
    private RecycleGridLayoutManager mLayoutManager;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.ranking_page_layout, container,
                false);
        mVaryViewHelper = new VaryViewHelper.Builder()
                .setContent(getContext())
                .setDataView(view.findViewById(R.id.ranking_refreshLayout))//放数据的父布局，逻辑处理在该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();

        //        mExecutorService = Executors.newCachedThreadPool();
        //        mExecutorService.execute(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getRankAppInfo();
        lazyLoading();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.UnregisterReceiver();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //            mVaryViewHelper.showLoadingView();
            getRankAppInfo();
            lazyLoading();
        }
    }
    private void lazyLoading() {
        Observable.timer(2000, TimeUnit.MILLISECONDS)
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        getAppLimitApi();
                    }
                });
    }

    private void getAppLimitApi() {
        AppLimitApi appLimitApi = Network.getAppLimitApi();
        appLimitApi.getAppLimitApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String responString = responseBody.string();
                            Log.e("mjhseng", responString);
                            JSONObject jsonObject = new JSONObject(responString);
                            Integer code = jsonObject.optInt("code");
                            switch (code) {
                                case 200:
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String result = data.optString("result");
                                    writeAppPackageList(result);
                                    break;
                                default:
                                    Log.e("mjhseng", "getAppLimitApi---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("mjhseng", "getAppLimitApi---woring----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "getAppLimitApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void writeAppPackageList(String result) {
        if (!TextUtils.isEmpty(result)) {
            LogUtils.e(result);
            Settings.System.putString(getActivity().getContentResolver(), "qch_app_forbid", result);
        } else {
            Log.e("mjsheng", "writeAppPackageList is null:");

        }
    }
    private void initView() {

        mRecycleView = (RecyclerView) view.findViewById(R.id.ranking_recycleView);
        int orientation = getActivity().getResources().getConfiguration().orientation;
        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mLayoutManager = new RecycleGridLayoutManager(getContext(), 2);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mLayoutManager = new RecycleGridLayoutManager(getContext(), 3);
                break;
        }
        mLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mRecycleView.setLayoutManager(mLayoutManager);
        mRecycleView.setNestedScrollingEnabled(false);
        mRecycleView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x)));
        ((DefaultItemAnimator) mRecycleView.getItemAnimator()).setSupportsChangeAnimations(false);

        mRecycleView.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;
                }
            }
        });
    }

    private void getRankAppInfo() {
        RankAppApi rankAppApi = Network.getRankAppApi();
        rankAppApi.getRankAppApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AppInfoBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("mjhseng", "getRankAppInfo---onSubscribe");

                    }

                    @Override
                    public void onNext(AppInfoBean appInfoBean) {
                        paraData(appInfoBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "onError:" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("mjhseng", "getRankAppInfo---onComplete");
                    }
                });
    }

    private void paraData(AppInfoBean appInfoBean) {
        int code = appInfoBean.getCode();
        switch (code) {
            case 200:
                List<AppDateInfo> data = appInfoBean.getData();
                if (data != null && data.size() > 0) {
                    mAdapter = new SubjectMoreAdapter(getContext(), data, new MyItemClickListener() {
                        @Override
                        public void onItemClick(View view, int postion) {

                            sound.playSoundEffect();
                            AppDateInfo info = mAdapter.getData(postion);
                            if (info != null) {
                                getAppDetail(info.getApp_baoming(), "热门应用");
                            }
                        }
                    });
                    mRecycleView.setAdapter(mAdapter);
                    mVaryViewHelper.showDataView();
                } else {
                    mVaryViewHelper.showEmptyView();
                }
                break;
            case -200:
                paraError(appInfoBean.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 loadContentData() {

        OkGo.post(Configure.HTTP_TAG_RECOMM_URL)
                .tag(this)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
                .cacheKey(Configure.HTTP_TAG_RECOMM_URL)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        if (listLzyResponse.data != null && !listLzyResponse.data.isEmpty()) {
                            allList.addAll(listLzyResponse.data);
                            mAdapter = new SubjectMoreAdapter(getContext(), allList, new MyItemClickListener() {
                                @Override
                                public void onItemClick(View view, int postion) {

                                    sound.playSoundEffect();
                                    AppDateInfo info = mAdapter.getData(postion);
                                    if (info != null) {
                                        getAppDetail(info.getApp_baoming(), "热门应用");
                                    }
                                }
                            });
                            mRecycleView.setAdapter(mAdapter);
                        }

                        if (listLzyResponse.data != null && !listLzyResponse.data.isEmpty()) {
                            mVaryViewHelper.showDataView();
                        } else {
                            mVaryViewHelper.showEmptyView();
                        }
                    }

                    @Override
                    public void onCacheError(Call call, Exception e) {
                        super.onCacheError(call, e);
                        Utils.showToast(getContext(), "网络连接不稳定，请稍后重试！");
                    }
                });
    }


    public void getAppDetail(String appBaoming, String title) {
        Intent intent = new Intent(getActivity(), AppDetailDialog.class);
        intent.putExtra("title", title);
        intent.putExtra("appBaoming", appBaoming);
        startActivity(intent);
    }


    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();
                    //                    loadContentData();
                    getRankAppInfo();
                    break;
                case R.id.iv_emptyview_layout:
                    mVaryViewHelper.showLoadingView();
                    //                    loadContentData();
                    getRankAppInfo();
                    break;
            }
        }
    }
}

