package com.yidianling.course;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.base.BaseFragment;
import com.ydl.ydlcommon.bean.ShareData;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.course.courseNew.LoadMoreView;
import com.yidianling.course.net.CourseRetrofitUtils;
import com.yidianling.course.bean.Course;
import com.yidianling.course.router.CourseIn;
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;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * A simple {@link Fragment} subclass.
 * 咨询师课程列表页
 */
public class CourseListFragment extends BaseFragment implements PtrHandler, LoadMoreHandler {

    ListView lvContent;
    LoadMoreListViewContainer loadMoreListViewContainer;
    PtrFrameLayout storeHousePtrFrame;

    TextView emptyTv;
    ImageView ivEmptyView;


    private int page = 0;
    private boolean hasMore = true;
    private int tagId;
    private CourseListAdapter adapter;
    /**
     * 是否免费（默认付费）
     */
    private int childType = TYPE_PAY;
    /**
     * 1.免费 2.付费
     */
    private static final int TYPE_PAY = 2;
    private static final int TYPE_FREE = 1;
    private boolean isPrepared;

    public CourseListFragment() {
        // Required empty public constructor
    }

    public static CourseListFragment newInstance(int tagId) {
        Bundle args = new Bundle();
        args.putInt("tagId", tagId);
        CourseListFragment fragment = new CourseListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static CourseListFragment newInstance(int tagId, int childType) {
        Bundle args = new Bundle();
        args.putInt("tagId", tagId);
        args.putInt("childType", childType);
        CourseListFragment fragment = new CourseListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            tagId = getArguments().getInt("tagId");
            childType = getArguments().getInt("childType");
        }
    }


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

    @Override
    public void initDataAndEvent() {
        lvContent = rootView.findViewById(R.id.lv_content);
        loadMoreListViewContainer = rootView.findViewById(R.id.load_more_list_view_container);
        storeHousePtrFrame = rootView.findViewById(R.id.store_house_ptr_frame);
        emptyTv = rootView.findViewById(R.id.tv_course_list_empty_prompt);
        ivEmptyView = rootView.findViewById(R.id.iv_course_list_empty_view);


        lvContent.setOnItemClickListener((parent, view, position, id) -> itemClick(view, position));
    }

    @Override
    public void initDataAndEventLazy() {
        init();
    }

    private void init() {
        // header
        final MaterialHeader header = new MaterialHeader(getActivity());
        int[] colors = getResources().getIntArray(R.array.course_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        int padding = (int) getActivity().getResources().getDimension(R.dimen.default_dis_size);
        header.setPadding(0, padding, 0, padding);
        header.setPtrFrameLayout(storeHousePtrFrame);
        storeHousePtrFrame.setHeaderView(header);
        storeHousePtrFrame.setPtrHandler(this);
        storeHousePtrFrame.addPtrUIHandler(header);

        // 使用默认样式
//        loadMoreListViewContainer.useDefaultHeader();
        LoadMoreView footerView = new LoadMoreView(getContext());
        loadMoreListViewContainer.setLoadMoreView(footerView);
        loadMoreListViewContainer.setLoadMoreUIHandler(footerView);
        footerView.onLoading(loadMoreListViewContainer);
        loadMoreListViewContainer.setLoadMoreHandler(this);
        adapter = new CourseListAdapter(getActivity());
        lvContent.setAdapter(adapter);
        getData(false);
    }

    private void getData(boolean loadMore) {
        switch (tagId) {
            case 1:
            case 2:
                if (!CourseIn.INSTANCE.isLogin()) {
                    return;
                }
                break;
            default:
                break;
        }
        if (loadMore && !hasMore) {
            loadMoreListViewContainer.loadMoreFinish(false, false);
            return;
        }
        if (loadMore) {
            page++;
        } else {
            page = 1;
            hasMore = true;
        }
        getCourses(loadMore);
    }

    @SuppressLint("CheckResult")
    private void getCourses(final boolean loadMore) {
        StringBuffer sb = new StringBuffer();
        if (tagId >= 10) {
            sb.append("&page=").append(page).append("&listType=").append(tagId);
            if (childType != -1) {
                sb.append("&isFree=").append(childType);
            }
        } else {
            sb.append("&page=").append(page)
                    .append("&listType=").append(tagId + 1);
        }
        String urlParams = NetworkParamsUtils.getCommonParam() + sb.toString();
        CourseRetrofitUtils.getCourseList(urlParams).compose(RxUtils.resultJavaData()).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    lvContent.setVisibility(View.VISIBLE);
                    emptyTv.setVisibility(View.GONE);
                    ivEmptyView.setVisibility(View.GONE);
                    if (loadMoreListViewContainer != null) {
                        loadMoreListViewContainer.loadMoreFinish(false, true);
                    }
                    try {
                        List<Course> courses = new ArrayList<>();
                        courses.addAll(resp.getList());
                        if (courses == null || courses.size() < CourseConstants.COURSE_PAGE_SIZE) {
                            hasMore = false;
                        }
                        if (!loadMore) {
                            if (courses != null) {
                                //更新缓存
                                adapter.setDataList(courses);
                                adapter.notifyDataSetChanged();
                            }
                        } else if (courses != null) {
                            adapter.addDataList(courses);
                            adapter.notifyDataSetChanged();
                        }
                        isShowEmptyView();

                    } catch (Exception e) {
                        LogUtil.e(e.toString());
                    }
                }, throwable -> {
                    if (throwable instanceof TimeoutException || throwable instanceof ConnectException || throwable instanceof UnknownHostException) {
                        if (adapter.mDataList == null || adapter.mDataList.size() <= 0) {
                            emptyTv.setVisibility(View.VISIBLE);
                            ivEmptyView.setVisibility(View.VISIBLE);
                            lvContent.setVisibility(View.GONE);
                            emptyTv.setText("网络不给力哦，下拉刷新重试");
                            ivEmptyView.setImageResource(R.drawable.course_no_net);
                        } else {
                            CourseRetrofitUtils.handleError(getActivity(), throwable);
                        }
                    } else {
                        CourseRetrofitUtils.handleError(getActivity(), throwable);
                        isShowEmptyView();
                    }
                });
    }

    private void isShowEmptyView() {
        if (adapter.mDataList == null || adapter.mDataList.size() <= 0) {
            emptyTv.setVisibility(View.VISIBLE);
            ivEmptyView.setVisibility(View.VISIBLE);
            lvContent.setVisibility(View.GONE);
            ivEmptyView.setImageResource(R.drawable.course_blank);
            emptyTv.setText("还没有相应的课程哦~");
        } else {
            lvContent.setVisibility(View.VISIBLE);
            emptyTv.setVisibility(View.GONE);
            ivEmptyView.setVisibility(View.GONE);
        }
    }

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

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (storeHousePtrFrame != null) {
                    storeHousePtrFrame.refreshComplete();
                }
            }
        }, 1800);
        getData(false);
    }


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

    private void itemClick(View v, int position) {
        Course course = adapter.getDataList().get(position);
        if (course != null) {

            H5Params h5Params = new H5Params(CourseConstants.Companion.getCOURSE_DETAIL_H5() + course.id, "课程详情");
            if (null != course.share && !TextUtils.isEmpty(course.share.getShare_url())) {
                ShareData shareData = new ShareData(course.share.getShare_url(), course.share.getTitle(), course.share.getCover(), course.share.getDesc());
                h5Params.setShareData(shareData);
            }

            NewH5Activity.start(getActivity(), h5Params);
            BuryPointUtils.getInstance().createMap()
                    .put("curriculum_name", course.title == null ? "" : course.title)
                    .put("curriculum_ID", course.id)
                    .burryPoint("Curriculum_click");
        }
    }

}
