package com.yidianling.fm;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.ui.LogoLoadingView;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.yidianling.fm.param.FMParam;
import com.yidianling.fm.router.FMIn;

import org.jetbrains.annotations.NotNull;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class FMListViewFragment extends BaseFragment implements PtrHandler, LoadMoreHandler {


    FMListAdapter adapter;

    int page = 0;
    boolean hasMore = true;

    int tagId;

    //    @BindView(R.id.lv_content)
    private ListView lv_content;
    //    @BindView(R.id.load_more_list_view_container)
    private LoadMoreListViewContainer load_more_list_view_container;
    //    @BindView(R.id.store_house_ptr_frame)
    private PtrFrameLayout store_house_ptr_frame;

    private TextView ll_empty_txt;
    private LinearLayout ll_empty;
    private LogoLoadingView v_loading;

    @Override
    public int layoutResId() {
        return R.layout.fm_fragment_fm_list_view;
    }

    @Override
    public void initDataAndEventLazy() {

    }

    @Override
    public void initDataAndEvent() {
        if (getRootView() != null) {
            lv_content = getRootView().findViewById(R.id.lv_content);
            ll_empty_txt = getRootView().findViewById(R.id.ll_empty_txt);
            ll_empty = getRootView().findViewById(R.id.ll_empty);
            v_loading = getRootView().findViewById(R.id.v_loading);
            load_more_list_view_container = getRootView().findViewById(R.id.load_more_list_view_container);
            store_house_ptr_frame = getRootView().findViewById(R.id.store_house_ptr_frame);
        }
        final MaterialHeader header = new MaterialHeader(getActivity());
        int color = getResources().getColor(R.color.platform_main_theme);
        header.setColorSchemeColors(new int[]{color});
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        int padding = (int) getActivity().getResources().getDimension(R.dimen.platform_default_dis_size);
        header.setPadding(0, padding, 0, padding);
        header.setPtrFrameLayout(store_house_ptr_frame);
        store_house_ptr_frame.setHeaderView(header);
        store_house_ptr_frame.setPtrHandler(this);
        store_house_ptr_frame.addPtrUIHandler(header);

        // 使用默认样式
        //load_more_list_view_container.useDefaultHeader();
        load_more_list_view_container.setLoadMoreHandler(this);
        adapter = new FMListAdapter(getActivity());

        lv_content.setAdapter(adapter);

        initNetLossView();

        lv_content.setVisibility(View.GONE);
        v_loading.setVisibility(View.VISIBLE);
        ll_empty.setVisibility(View.GONE);
        if (tagId == 1) {
            if (FMIn.INSTANCE.isLogin()) {
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null);
            } else {
                v_loading.setVisibility(View.GONE);
                ll_empty.setVisibility(View.VISIBLE);
            }
        } else {
            v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null);
        }

        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), FMDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("id", adapter.mDataList.get(position).getId());
                intent.putExtra("bundle", bundle);
                startActivity(intent);
                click_play();
                BuryPointUtils.getInstance().createMap()

                        .put("FM_name", adapter.mDataList.get(position).getName())
                        .burryPoint("FM_play");
            }
        });

        if (tagId == 1 && !FMIn.INSTANCE.isLogin()) {
            return;
        }
        getData(false);
    }

    private void initNetLossView() {
        v_loading.setListener(new LogoLoadingView.LogoLoadingListener() {
            @Override
            public void onDataResetClick() {
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null);
                if (tagId == 1) {
                    collectList(false);
                }else {
                    allList(false);
                }
            }

            @Override
            public void onBackClick() {
                getActivity().finish();
            }
        });
    }

    public void click_play() {
    }


    public FMListViewFragment setTagId(int tagId) {
        this.tagId = tagId;
        return this;
    }


    void getData(final boolean loadMore) {
        if (loadMore && !hasMore) {
            if (load_more_list_view_container != null) {
                load_more_list_view_container.loadMoreFinish(false, false);
            }
            return;
        }
        if (loadMore) {
            page++;
        } else {
            page = 1;
        }
        switch (tagId) {
            case 0:
                allList(loadMore);
                break;

            case 1:
                collectList(loadMore);
                break;
        }
    }

    private void collectList(final boolean loadMore) {
        FmDataManager.INSTANCE.getHttp().getFavFMs(new FMParam(String.valueOf(page), "20"))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultJavaData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fms -> {
                    if (fms.getList().size() == 0) {
                        lv_content.setVisibility(View.GONE);
                        v_loading.setVisibility(View.GONE);
                        ll_empty.setVisibility(View.VISIBLE);
                    }else {
                        lv_content.setVisibility(View.VISIBLE);
                        v_loading.setVisibility(View.GONE);
                        ll_empty.setVisibility(View.GONE);
                        load_more_list_view_container.loadMoreFinish(false, true);
                        if (fms == null || fms.getList().size() < 20) {
                            hasMore = false;
                        }
                        if (!loadMore)
                            adapter.setDataList(fms.getList());
                        else if (fms != null)
                            adapter.addDataList(fms.getList());
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        lv_content.setVisibility(View.GONE);
                        v_loading.setVisibility(View.VISIBLE);
                        ll_empty.setVisibility(View.GONE);
                        v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, msg);
                        if (msg.equals("还没有喜欢的电台内容")) {
                            return;
                        }
                    }
                });

    }

    private void allList(final boolean loadMore) {
        FmDataManager.INSTANCE.getHttp().getAllFMs(new FMParam(String.valueOf(page), "20"))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultJavaData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fms -> {
                    if (fms.getList().size() == 0) {
                        lv_content.setVisibility(View.GONE);
                        v_loading.setVisibility(View.GONE);
                        ll_empty.setVisibility(View.VISIBLE);
                        ll_empty_txt.setText("这里还没有数据哦");
                    } else {
                        lv_content.setVisibility(View.VISIBLE);
                        v_loading.setVisibility(View.GONE);
                        ll_empty.setVisibility(View.GONE);
                        load_more_list_view_container.loadMoreFinish(false, true);
                        if (fms == null || fms.getList().size() < 20) {
                            hasMore = false;
                        }
                        if (!loadMore)
                            adapter.setDataList(fms.getList());
                        else if (fms != null)
                            adapter.addDataList(fms.getList());
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        lv_content.setVisibility(View.GONE);
                        v_loading.setVisibility(View.VISIBLE);
                        ll_empty.setVisibility(View.GONE);
                        v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, msg);
                    }
                });

    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, lv_content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                store_house_ptr_frame.refreshComplete();
            }
        }, 1500);
        getData(false);
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        getData(true);
    }

}
