package com.mjsheng.myappstore.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
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.widget.ImageView;
import android.widget.TextView;


import com.blankj.utilcode.util.LogUtils;
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.adapter.SubjectMoreAdapter;
import com.mjsheng.myappstore.base.BaseFragmentActivity;
import com.mjsheng.myappstore.bean.AppDateInfo;
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.listener.AutoLoadListener;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.AppLimitApi;
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.ExecutorService;
import java.util.concurrent.Executors;
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 SubjectMoreActivity extends BaseFragmentActivity implements View.OnClickListener, Runnable {

    private String title, url, httpmethod;
    private TextView titleImgView;
    private ImageView mBackBtn;
    private List<AppDateInfo> mList = new ArrayList<>();
    private List<AppDateInfo> allList = new ArrayList<>();
    private RecyclerView mRecycleView;
    private SubjectMoreAdapter mAdapter;
    private TextView numberTV;
    private VaryViewHelper mVaryViewHelper;
    private Sound sound;
    private ExecutorService mExecutorService;
    private List<AppDateInfo> pageList = new ArrayList<>();
    private int page = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            switch (msg.what) {
                case Configure.SUCCESS:
                    String httTag = data.getString("httpTag");
                    if (httTag.equals(Configure.RANKING_TYPE_MOREAPP)) {
                        if (msg.obj != null) {
                            List<AppDateInfo> contentList = (List<AppDateInfo>) msg.obj;
                            Log.e("mjsheng", "contentList===" + contentList.size());
                            if (contentList.size() <= 0 || contentList == null) {
                                //                                Utils.showToast(SubjectMoreActivity.this, "没有数据！");
                                if (page == 1) {
                                    mVaryViewHelper.showEmptyView();
                                    numberTV.setText("0款应用");
                                }
                                return;
                            }
                            if (contentList.size() >= 8 && !title.equals("all_apps")) {
                                pageList.addAll(contentList.subList(0, 8));
                            } else {
                                pageList.addAll(contentList);
                            }
                            Log.e("mjsheng", "pageList===" + pageList.size());
                            setList(pageList);
                        }
                        break;
                    }
            }
        }
    };
    private String id;
    private RecycleGridLayoutManager mLayoutManager;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_subject_more);
        sound = new Sound(this);
        Bundle bundle = this.getIntent().getExtras();
        title = bundle.getString("title");
        url = bundle.getString("URL");
        id = bundle.getString("id");
        Log.e("mjsheng", "rul----------" + url);
        httpmethod = bundle.getString("HTTP");
        mList = (List<AppDateInfo>) bundle.getSerializable("AppDateInfo");
        mExecutorService = Executors.newCachedThreadPool();

        numberTV = (TextView) findViewById(R.id.subject_number_tv);
        if (title.equals("all_apps")) {
            numberTV.setVisibility(View.VISIBLE);
        } else numberTV.setVisibility(View.GONE);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mVaryViewHelper = new VaryViewHelper.Builder()
                .setContent(this)
                .setDataView(findViewById(R.id.subject_refreshLayout))//放数据的父布局，逻辑处理在该Activity中处理
                .setLoadingView(LayoutInflater.from(this).inflate(R.layout.layout_loadingview, null))//加载页，无实际逻辑处理
                .setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_emptyview, null))//空页面，无实际逻辑处理
                .setErrorView(LayoutInflater.from(this).inflate(R.layout.layout_errorview, null))//错误页面
                .setRefreshListener(new SubjectMoreActivity.ErrorClickListener())//错误页点击刷新实现
                .build();

        mVaryViewHelper.showLoadingView();
        initView();

        mExecutorService.execute(this);
    }

    private void initView() {
        int orientation = getResources().getConfiguration().orientation;

        mRecycleView = (RecyclerView) findViewById(R.id.subject_recycleView);

//        AutoLoadListener autoLoadListener = new AutoLoadListener(mCallBack);
//        mRecycleView.addOnScrollListener(autoLoadListener);

        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mLayoutManager = new RecycleGridLayoutManager(this, 1);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mLayoutManager = new RecycleGridLayoutManager(this, 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);

        titleImgView = (TextView) findViewById(R.id.tv_subject_img);
        if (title.equals("new_more")) {
            titleImgView.setText("最新上架");
        } else if (title.equals("recommend_more")) {
            titleImgView.setText("热门推荐");
        } else if (title.equals("top_special")) {
            titleImgView.setText("专题推荐");
        } else if (title.equals("top_brand")) {
            titleImgView.setText("品牌推荐");
        } else if (title.equals("search_result")) {
            titleImgView.setText("搜索应用");
        } else if (title.equals("all_apps")) {
            titleImgView.setText("全部应用");
        } else {
            titleImgView.setText(title);
        }


        //        mBackBtn = (ImageView) findViewById(R.id.iv_subject_back);
        //        mBackBtn.setOnClickListener(this);
        mAdapter = new SubjectMoreAdapter(SubjectMoreActivity.this, 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());
                }
            }
        });


    }

    AutoLoadListener.AutoLoadCallBack mCallBack = new AutoLoadListener.AutoLoadCallBack() {
        @Override
        public void execute() {
            if (title.equals("new_more") || title.equals("recommend_more")) {
                httpPostMethodHomePage(++page);
            } else {

                httpPostMethod(++page);
            }
            Log.e("mjsheng", "nextpage");
        }

        @Override
        public void stopLoad() {
            Glide.with(SubjectMoreActivity.this).pauseRequests();
        }

        @Override
        public void startLoad() {
            Glide.with(SubjectMoreActivity.this).resumeRequests();
        }
    };


    @Override
    public void run() {
        if (mList != null && !mList.isEmpty()) {
            setList(mList);
        } else {
            loadDatas();
        }

    }

    private void setList(final List<AppDateInfo> mList) {
        if (mList != null && !mList.isEmpty()) {
            allList.clear();
            allList.addAll(mList);
            if (mAdapter != null) {
                mRecycleView.setAdapter(mAdapter);
                mAdapter.setmDatas(allList);
                numberTV.setText(allList.size() + "款应用");
                mVaryViewHelper.showDataView();
            }
        } else {
            mVaryViewHelper.showEmptyView();
            numberTV.setText("0款应用");
        }


        //        runOnUiThread(new Runnable() {
        //            @Override
        //            public void run() {
        //                mRecycleView.setAdapter(mAdapter);
        //                if (allList != null && !allList.isEmpty()) {
        //                    mVaryViewHelper.showDataView();
        //                } else {
        //                    mVaryViewHelper.showEmptyView();
        //                    numberTV.setText("0款应用");
        //                }
        //            }
        //        });


        //                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(SubjectMoreActivity.this).pauseRequests();
        //                                Log.e("msjheng","------------SCROLL_STATE_SETTLING");
        //                                break;
        //                            case RecyclerView.SCROLL_STATE_IDLE:
        //                                // 当ListView处于静止状态时，继续加载图片
        //                                Glide.with(SubjectMoreActivity.this).resumeRequests();
        //                                Log.e("msjheng","------------SCROLL_STATE_IDLE");
        //                                break;
        //                        }
        //                    }
        //                });
    }

    private void loadDatas() {
        //        if (httpmethod == null || httpmethod.equals("")) {
        //            httpGetMethod();
        //        } else {
        //            httpPostMethod();
        //        }
        if (title.equals("new_more") || title.equals("recommend_more")) {
            httpPostMethodHomePage(page);
        } else {

            httpPostMethod(page);
        }
        lazyLoading();
    }

    private void httpPostMethod(int page) {

        OkGo.post(url)
                .tag(this)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
                .params("page", page)
                .params("id", id)
                .cacheKey(url + id)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        Message msg = new Message();
                        msg.what = Configure.SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.RANKING_TYPE_MOREAPP);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onCacheSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call) {
                        onSuccess(listLzyResponse, call, null);
                        if (!Utils.isIntent(SubjectMoreActivity.this)) {
                            Utils.showToast(SubjectMoreActivity.this, "网络连接不稳定，请稍后重试！");
                        }
                    }
                });
    }

    private void httpPostMethodHomePage(int page) {
        //不需要按页数
        OkGo.post(url)
                .tag(this)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
//                .params("page", page)
                .cacheKey(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) {
                        Message msg = new Message();
                        msg.what = Configure.SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.RANKING_TYPE_MOREAPP);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onCacheSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call) {
                        onSuccess(listLzyResponse, call, null);
                        if (!Utils.isIntent(SubjectMoreActivity.this)) {
                            Utils.showToast(SubjectMoreActivity.this, "网络连接不稳定，请稍后重试！");
                        }
                    }
                });
    }

    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(getContentResolver(), "qch_app_forbid", result);
        } else {
            Log.e("mjsheng", "writeAppPackageList is null:");

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_subject_back:
                sound.playSoundEffect();
                finish();
                break;
            default:
                break;
        }
    }


    public void getAppDetail(String appBaoming) {
        String detailTitle = new String();
        if (title.equals("new_more")) {
            detailTitle = "最新上架";
        } else if (title.equals("recommend_more")) {
            detailTitle = "热门推荐";
        } else if (title.equals("top_special")) {
            detailTitle = "应用专题";
        } else if (title.equals("top_brand")) {
            detailTitle = "应用品牌";
        } else if (title.equals("search_result")) {
            detailTitle = "搜索应用";
        } else if (title.equals("all_apps")) {
            detailTitle = "全部应用";
        } else {
            detailTitle = title;
        }
        Intent intent = new Intent(this, AppDetailDialog.class);
        intent.putExtra("title", detailTitle);
        intent.putExtra("appBaoming", appBaoming);
        startActivity(intent);
    }

    @Override

    protected void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.UnregisterReceiver();
        }
    }


    @Override
    public void finish() {
        super.finish();
        if (mAdapter != null) {
            mAdapter.UnregisterReceiver();
        }
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }


    private class ErrorClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            sound.playSoundEffect();
            switch (v.getId()) {
                case R.id.iv_errorview_layout:
                    if (url != null && !url.isEmpty()) {
                        loadDatas();
                    }
                    break;
                case R.id.iv_emptyview_layout:
                    if (url != null && !url.isEmpty()) {
                        loadDatas();
                    }
                    break;
            }
        }
    }
}
