package com.mjsheng.myappstore.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
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.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.example.library.banner.BannerLayout;
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.RecommendAdapter;
import com.mjsheng.myappstore.adapter.TopRecyclerViewAdapter;
import com.mjsheng.myappstore.adapter.WebBannerAdapter;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.CommonPicBean;
import com.mjsheng.myappstore.bean.CommonPicData;
import com.mjsheng.myappstore.bean.HomePageInfo;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
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.BrankPicApi;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.utils.update.ToastTool;
import com.mjsheng.myappstore.view.MyGridView;
import com.mjsheng.myappstore.view.RecycleLinearLayoutManager;
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;

import static android.view.View.OnClickListener;

public class HomePageFragment extends Fragment implements OnClickListener {

    private View view;
    private RecyclerView mTopRlView;
    private TopRecyclerViewAdapter mAdapter;
    //轮播图
    private BannerLayout recyclerBanner;
    private WebBannerAdapter webBannerAdapter;


    //贴心推荐
    private MyGridView newGridView, hotGridView;
    private RecommendAdapter newAdapter, hotAdapter;
    private Sound sound;

    private RelativeLayout home_rl_all;
    private Handler mHandler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            switch (msg.what) {
                case Configure.SUCCESS:
                    if (data != null) {
                        String httpTag = data.getString("httpTag");
                        if (TextUtils.isEmpty(httpTag))
                            return;
                        if (null == msg.obj)
                            return;
                        if (httpTag.equals(Configure.HTTP_TYPE_HOMEPAGE)) {
                            List<AppDateInfo> list = (List<AppDateInfo>) msg.obj;
                            List<AppDateInfo> newlist = new ArrayList<>();
                            if (list != null && list.size() > 0) {
                                if (list.size() > 3) {
                                    newlist = list.subList(0, 3);
                                } else {
                                    newlist = list;
                                }
                            }
//                            List<AppDateInfo> hotlist = new ArrayList<>();
//                            for (int i = 0; i < list.size(); i++) {
//                                if (list.get(i).getType().equals("1")) {
//                                    if (newlist.size() == 3) {
//                                        continue;
//                                    }
//                                    newlist.add(list.get(i));
//                                }
//                                else {
//                                    if (hotlist.size() == 3) {
//                                        continue;
//                                    }
//                                    hotlist.add(list.get(i));
//                                }
//
//                            }
                            newAdapter = new RecommendAdapter(newlist, HomePageFragment.this.getActivity());
                            newAdapter.itemClick = new RecommendAdapter.RecommendItemClick() {
                                @Override
                                public void itemClick(AppDateInfo info) {
                                    getAppDetail(info.getApp_baoming(), "最新上架");
                                }
                            };
                            newGridView.setAdapter(newAdapter);
                            newAdapter.notifyDataSetChanged();

//                            hotAdapter = new RecommendAdapter(hotlist, HomePageFragment.this.getActivity());
//                            hotAdapter.itemClick = new RecommendAdapter.RecommendItemClick() {
//                                @Override
//                                public void itemClick(AppDateInfo info) {
//                                    getAppDetail(info.getApp_baoming(), "热门推荐");
//                                }
//                            };
//                            hotGridView.setAdapter(hotAdapter);
//                            hotAdapter.notifyDataSetChanged();

                        } else if (httpTag.equals(Configure.HTTP_TYPE_BRAND)) {
                            if (msg.obj != null) {
                                final List<HomePageInfo> homePageInfos = (List<HomePageInfo>) msg.obj;
                                List<String> list = new ArrayList<>();
                                for (int i = 0; i < homePageInfos.size(); i++) {
                                    list.add(homePageInfos.get(i).getImg());
                                }
                                webBannerAdapter = new WebBannerAdapter(getContext(), list);
                                webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                                    @Override
                                    public void onItemClick(int position) {
                                        loadProjectByType(Configure.HTTP_TAG_BRAND_DETAILS_URL, homePageInfos.get(position).getId(), homePageInfos.get(position).getName());

                                    }
                                });
                                recyclerBanner.setAdapter(webBannerAdapter);
                                mAdapter = new TopRecyclerViewAdapter(getActivity(), "home", list, new TopRecyclerViewAdapter.HorizontalScrollViewListener() {
                                    @Override
                                    public void onClick(String iconUrl, int position) {
                                        sound.playSoundEffect();
                                        //                                        if (homePageInfos.get(position).getType().equals("pinpai")) {
                                        loadProjectByType(Configure.HTTP_TAG_BRAND_DETAILS_URL, homePageInfos.get(position).getId(), homePageInfos.get(position).getName());
                                        //                                        } else {
                                        //                                            loadProjectByType(Configure.HTTP_TAG_PROJECT_DETAILS_URL + homePageInfos.get(position).getId(), "top_special");
                                        //                                        }
                                    }
                                });
                                mTopRlView.setAdapter(mAdapter);
                            }
                        }
                    }
                    break;
                case 201:
                    if (data != null) {
                        String httpTag = data.getString("httpTag");
                        if (TextUtils.isEmpty(httpTag))
                            return;
                        if (null == msg.obj)
                            return;
                        if (httpTag.equals(Configure.HTTP_TYPE_HOMEPAGE)) {
                            List<AppDateInfo> list = (List<AppDateInfo>) msg.obj;
                            List<AppDateInfo> hotlist = new ArrayList<>();
                            if (list != null && list.size() > 0) {
                                if (list.size() > 3) {
                                    hotlist = list.subList(0, 3);
                                } else {
                                    hotlist = list;
                                }
                            }
                            hotAdapter = new RecommendAdapter(hotlist, HomePageFragment.this.getActivity());
                            hotAdapter.itemClick = new RecommendAdapter.RecommendItemClick() {
                                @Override
                                public void itemClick(AppDateInfo info) {
                                    getAppDetail(info.getApp_baoming(), "热门推荐");
                                }
                            };
                            hotGridView.setAdapter(hotAdapter);
                            hotAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private NoSnDialog mNoSnDialog;
    private SwipeRefreshLayout recommend_srl;


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadDatas();
            loadHeadImg(Configure.HTTP_TAG_HOME_PAGE_URL);
            if (newAdapter != null && hotAdapter != null) {
                newAdapter.notifyDataSetChanged();
                hotAdapter.notifyDataSetChanged();
            }
            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 loadProjectByType(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);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.home_page_layout, container,
                false);
        sound = new Sound(getContext());
        initView();
        return view;
    }

    private void initView() {

        mTopRlView = view.findViewById(R.id.main_RecyclerView);
        recyclerBanner = view.findViewById(R.id.recycler);


        this.recommend_srl = (SwipeRefreshLayout) view.findViewById(R.id.recommend_srl);
        this.recommend_srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public void onRefresh() {
                HomePageFragment.this.loadDatas();
                HomePageFragment.this.recommend_srl.setRefreshing(false);
            }
        });
        recommend_srl.setColorSchemeColors(Color.BLACK, Color.GREEN, Color.RED, Color.YELLOW, Color.BLUE);

        RecycleLinearLayoutManager manager = new RecycleLinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        manager.setSmoothScrollbarEnabled(true);
        mTopRlView.setLayoutManager(manager);
        mTopRlView.setNestedScrollingEnabled(false);

        newGridView = (MyGridView) view.findViewById(R.id.gv_new_more);
        hotGridView = (MyGridView) view.findViewById(R.id.gv_recommend_more);

        view.findViewById(R.id.new_more_ll).setOnClickListener(this);
        view.findViewById(R.id.recommend_more_ll).setOnClickListener(this);
        home_rl_all = view.findViewById(R.id.home_rl_all);
        home_rl_all.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showMoreSubject("all_apps", Configure.HTTP_TAG_HOMEPAGE_URL);

            }
        });

        loadDatas();
        loadHeadImg(Configure.HTTP_TAG_HOME_PAGE_URL);
        lazyLoading();
    }


    private void loadHeadImg(String URL) {
        BrankPicApi brankPicApi = Network.getBrankPicApi();
        brankPicApi.getBrankPicApi(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", "brankPicApi---" + projectPicBean.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Utils.showToast(getContext(), "网络出错！");
                        Log.e("mjsheng", "brankPicApi---error----" + e.getMessage());

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    private void paraData(CommonPicBean categoryPicBean) {
        int code = categoryPicBean.getCode();
        switch (code) {
            case 200:
                final List<CommonPicData> data = categoryPicBean.getData();
                if (data != null && data.size() > 0) {
                    List<String> list = new ArrayList<>();
                    for (int i = 0; i < data.size(); i++) {
                        list.add(data.get(i).getImg());
                    }
                    webBannerAdapter = new WebBannerAdapter(getActivity(), list);
                    webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            loadProjectByType(Configure.HTTP_TAG_BRAND_DETAILS_URL, data.get(position).getId(), data.get(position).getName());
                        }
                    });
                    recyclerBanner.setAdapter(webBannerAdapter);
                    mAdapter = new TopRecyclerViewAdapter(getActivity(), "home", list, new TopRecyclerViewAdapter.HorizontalScrollViewListener() {
                        @Override
                        public void onClick(String iconUrl, int position) {
                            sound.playSoundEffect();
                            loadProjectByType(Configure.HTTP_TAG_BRAND_DETAILS_URL, data.get(position).getId(), data.get(position).getName());
                        }
                    });
                    mTopRlView.setAdapter(mAdapter);
                } else {
                    //                    Utils.showToast(getContext(), "数据为空！");
                    Log.e("mjsheng", "推荐页轮播图为空！");
                }
                break;
            case -200:
                paraError(categoryPicBean.getMsg());
                break;
        }
    }

    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 loadDatas() {
        //修改为获取所有应用
        OkGo.post(Configure.HTTP_TAG_HOMEPAGE_URL)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
                .params("page", "1")
                .tag(this)
                .cacheKey(Configure.HTTP_TAG_HOMEPAGE_URL + Utils.getSerial())
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        List<AppDateInfo> data = listLzyResponse.data;
                        if (data == null || data.size() <= 0) {
                            ToastTool.show("应用商城未上传应用");
                            return;
                        }
                        Message msg = new Message();
                        msg.what = Configure.SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.HTTP_TYPE_HOMEPAGE);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onCacheError(Call call, Exception e) {
                        super.onCacheError(call, e);
                        //                        Utils.showToast(getContext(), "网络连接不稳定，请稍后重试！");
                    }
                });
        //获取排行应用
        OkGo.post(Configure.HTTP_TAG_RECOMM_URL)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
                .params("page", "1")
                .tag(this)
                .cacheKey(Configure.HTTP_TAG_RECOMM_URL + Utils.getSerial())
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        List<AppDateInfo> data = listLzyResponse.data;
                        if (data == null || data.size() <= 0) {
                            ToastTool.show("应用商城未上传应用");
                            return;
                        }
                        Message msg = new Message();
                        msg.what = 201;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.HTTP_TYPE_HOMEPAGE);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }

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


    }


    @Override
    public void onClick(View v) {
        sound.playSoundEffect();
        switch (v.getId()) {
            case R.id.new_more_ll:
                if (Utils.isFastDoubleClick())
                    return;
                showMoreSubject("new_more", Configure.HTTP_TAG_HOMEPAGE_URL);
                break;
            case R.id.recommend_more_ll:
                if (Utils.isFastDoubleClick())
                    return;
                showMoreSubject("recommend_more", Configure.HTTP_TAG_RECOMM_URL);
                break;
        }
    }


    private void showMoreSubject(String title, String url) {
        Intent intent = new Intent(getActivity(), SubjectMoreActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("URL", url);
        bundle.putString("title", title);
        bundle.putString("HTTP", "post");
        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);
    }


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

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


}
