package com.yidianling.course;


import android.graphics.Color;
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.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.course.courseNew.LoadMoreView;
import com.yidianling.course.courseNew.courseList.BaseLazyFragment;
import com.yidianling.course.coursePlay.common.net.Command;
import com.yidianling.course.coursePlay.common.net.RetrofitUtils;
import com.yidianling.course.coursePlay.moudle.Course;
import com.yidianling.course.router.CourseIn;
import com.yidianling.ydlcommon.data.ShareData;
import com.yidianling.ydlcommon.h5.H5Params;
import com.yidianling.ydlcommon.h5.NewH5Activity;
import com.yidianling.ydlcommon.tool.BuryPointUtils;
import com.yidianling.ydlcommon.utils.UMEventUtils;

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

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;
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;

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

    @BindView(R2.id.lv_content)
    ListView lvContent;
    @BindView(R2.id.load_more_list_view_container)
    LoadMoreListViewContainer loadMoreListViewContainer;
    @BindView(R2.id.store_house_ptr_frame)
    PtrFrameLayout storeHousePtrFrame;

    @BindView(R2.id.tv_course_list_empty_prompt)
    TextView emptyTv;
    @BindView(R2.id.iv_course_list_empty_view)
    ImageView ivEmptyView;

    @BindView(R2.id.ll_pay_type)
    LinearLayout llPayType;
    @BindView(R2.id.tv_pay_type_free)
    TextView payTypeFree;
    @BindView(R2.id.tv_paied_type)
    TextView paiedCourse;

    private int page = 0;
    private boolean hasMore = true;
    private int tagId;
    private CourseListAdapter adapter;
    private int childType = -1;
    private boolean isPrepared;

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

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

    public static MyCourseListFragment newInstance(int tagId, int childType) {
        Bundle args = new Bundle();
        args.putInt("tagId", tagId);
        args.putInt("childType", childType);
        MyCourseListFragment fragment = new MyCourseListFragment();
        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 void afterViewCreated(View view, Bundle savedInstanceState) {
        isPrepared = true;      //View创建完成
        LogUtil.i("afterViewCreated id: " + tagId);
        if (!isUseLazyMode) {
            isVisible = true;
        }
        lazyLoad();
    }

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

    @Override
    public void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        LogUtil.i("lazy load tagid: " + tagId);
        if (childType == 2) { //付费
            llPayType.setVisibility(View.VISIBLE);
            payTypeFree.setSelected(false);
            payTypeFree.setTextColor(Color.parseColor("#909599"));
            paiedCourse.setSelected(true);
            paiedCourse.setTextColor(Color.parseColor("#ffffff"));
        } else if (childType == 1) { //免费
            llPayType.setVisibility(View.VISIBLE);
            payTypeFree.setSelected(true);
            payTypeFree.setTextColor(Color.parseColor("#ffffff"));
            paiedCourse.setSelected(false);
            paiedCourse.setTextColor(Color.parseColor("#909599"));
        }
        init();
        isPrepared = false;
    }

    private void init() {
        // header
        final MaterialHeader header = new MaterialHeader(getActivity());
        int[] colors = getResources().getIntArray(R.array.ydl_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);
    }

    private void getCourses(final boolean loadMore) {
        Command.GetCourse command;
        if (tagId >= 10) {
            command = new Command.GetCourse(page, tagId, childType);
        } else {
            command = new Command.GetCourse(page, tagId + 1);
        }
        //todo heti 待修改
        RetrofitUtils.getCourseList(command)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                    if (resp.code != 0) {
                        ToastUtil.toastShort(resp.msg);
                        hasMore = false;
                        isShowEmptyView();
                        return;
                    }
                    lvContent.setVisibility(View.VISIBLE);
                    emptyTv.setVisibility(View.GONE);
                    ivEmptyView.setVisibility(View.GONE);
                    if (getActivity() instanceof CourseActivity)
                        ((CourseActivity) getActivity()).disPro();
                    if (loadMoreListViewContainer != null) {
                        loadMoreListViewContainer.loadMoreFinish(false, true);
                    }
                    try {
                        List<Course> courses = resp.data;
                        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);
                        }
                        isShowEmptyView();

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

    private void isShowEmptyView() {
        if (getParentView() == null) {
            return;
        }
        if (adapter.mDataList == null || adapter.mDataList.size() <= 0) {
            emptyTv.setVisibility(View.VISIBLE);
            ivEmptyView.setVisibility(View.VISIBLE);
            lvContent.setVisibility(View.GONE);
            ivEmptyView.setImageResource(R.drawable.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);
    }

    @OnClick({R2.id.tv_pay_type_free, R2.id.tv_paied_type})
    void doClick(View view) {
        if (view.getId() == R.id.tv_paied_type) {
            if (paiedCourse.isSelected()) {
                return;
            }
            childType = 2; //付费
            payTypeFree.setSelected(false);
            payTypeFree.setTextColor(Color.parseColor("#909599"));
            paiedCourse.setSelected(true);
            paiedCourse.setTextColor(Color.parseColor("#ffffff"));
            getCourses(false);
        } else if (view.getId() == R.id.tv_pay_type_free) {
            if (payTypeFree.isSelected()) {
                return;
            }
            childType = 1; //付费
            payTypeFree.setSelected(true);
            payTypeFree.setTextColor(Color.parseColor("#ffffff"));
            paiedCourse.setSelected(false);
            paiedCourse.setTextColor(Color.parseColor("#909599"));
            getCourses(false);
        }
    }

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

    @OnItemClick(R2.id.lv_content)
    void onItemClick(View v, int position) {
        Course course = adapter.getDataList().get(position);
        if (course != null) {

            H5Params h5Params = new H5Params(CourseConstants.Companion.getCOURSE_DETAIL_H5() + course.id, getActivity().getString(R.string.course_detail));
            if (!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");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.i("destroy view id: " + tagId);
        parentView = null;
    }
}
