package com.beanpodtech.allinone.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.FilterAdapter;
import com.beanpodtech.allinone.adapter.FilterClassAdapter;
import com.beanpodtech.allinone.adapter.VideoAdapter;
import com.beanpodtech.allinone.bean.FilterBean;
import com.beanpodtech.allinone.bean.SubjectFilterBean;
import com.beanpodtech.allinone.bean.VideoBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.LoadingView;
import com.beanpodtech.allinone.widget.flowlayout.FlowLayout;
import com.beanpodtech.allinone.widget.flowlayout.TagFlowLayout;
import com.lzy.okgo.model.Response;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 *
 */
public class PlayvideoActivity extends BaseActivity {
    private static final String CLASS_VIDEO = "classVideo";

    /**
     * 科目
     */
    private final static int TYPE_SUBJECT = 1;
    /**
     * 分类
     */
    private final static int TYPE_TYPE = 2;
    /**
     * 名师
     */
    private final static int TYPE_TEACHER = 3;
    /**
     * 大纲
     */
    private final static int TYPE_OUTLINE = 4;


    private RecyclerView mRecyclerView;
    private Context mContext = this;
    private VideoAdapter mAdapter;
    private List<VideoBean.ListBean> totalList = new ArrayList<>();
    private TagFlowLayout tflClasssubject;
    private TagFlowLayout tflSubject;
    private TagFlowLayout tflType;
    private TagFlowLayout tflTeacher;
    private TagFlowLayout tflOutline;
    private TagFlowLayout tflOutlineclass;
    private FilterClassAdapter adapterClassSubject;
    private FilterAdapter adapterSubject;
    private FilterAdapter adapterType;
    private FilterAdapter adapterTeacher;
    private FilterAdapter adapterOutline;
    private FilterAdapter adapterOutlineClass;
    private List<SubjectFilterBean.SubjectListBean> listClassSubject = new ArrayList<>();
    private List<FilterBean.SubjectsBean> listSubject = new ArrayList<>();
    private List<FilterBean.SubjectsBean.SortsBean> listFilter = new ArrayList<>();
    private List<FilterBean.SubjectsBean.SortsBean.TeachersBean> listTeacher = new ArrayList<>();
    private List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean> listOutline = new ArrayList<>();
    private List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean.OutlineClassificationBean> listOutlineClass = new ArrayList<>();
    private String userId;
    private LinearLayout rlClassdes;
    private TextView tvTitle;
    private String className;
    private String classId;
    private LoadingView loadingView;
    //课程Id
    private String subjectId;

    public static void startActivity(Context context, Bundle bundle) {
        Intent intent = new Intent(context, PlayvideoActivity.class);
        intent.putExtra(CLASS_VIDEO, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        BoxUtil.hideBottomUIMenu(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.rl_classdes:
                Bundle bundle = new Bundle();
                bundle.putString(Contants.CLASS_NAME, className);
                bundle.putString(Contants.CLASS_ID, classId);
                ClassTypeIntroductionActivity.startActivity(this, bundle);
                break;
            case R.id.iv_back:
                finish();
                break;

        }
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_playvideo;
    }

    @Override
    public void initView(View view) {
        loadingView = new LoadingView(this, R.style.CustomDialog);
        loadingView.setTitle(getResources().getString(R.string.waitloading));
        userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
//        userId = "1";
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra(CLASS_VIDEO);
        className = bundle.getString(Contants.CLASS_NAME);
        classId = bundle.getString(Contants.CLASS_ID);
        tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText(className);
        rlClassdes = findViewById(R.id.rl_classdes);
        rlClassdes.setVisibility(View.VISIBLE);
        tflSubject = findViewById(R.id.tfl_subject);
        tflType = findViewById(R.id.tfl_type);
        tflTeacher = findViewById(R.id.tfl_teacher);
        tflOutline = findViewById(R.id.tfl_outline);
        tflOutlineclass = findViewById(R.id.tfl_outlineclass);
        tflClasssubject = findViewById(R.id.tfl_classsubject);
        mRecyclerView = findViewById(R.id.id_recyclerview);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
//        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,
//                StaggeredGridLayoutManager.VERTICAL));
        mAdapter = new VideoAdapter(totalList, this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        ImageView back = findViewById(R.id.iv_back);
        back.setOnClickListener(this);
    }

    @Override
    public void initListener() {
        tflSubject.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(TYPE_SUBJECT, position);
                return true;
            }
        });
        tflType.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(TYPE_TYPE, position);
                return true;
            }
        });
        tflTeacher.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(TYPE_TEACHER, position);
                return true;
            }
        });
        tflOutline.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(TYPE_OUTLINE, position);
                return true;
            }
        });
        tflOutlineclass.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                getRequestData();
                return true;
            }
        });

        tflClasssubject.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                SubjectFilterBean.SubjectListBean subjectListBean = listClassSubject.get(position);
                subjectId = subjectListBean.getSubjectId();
                getFilterListFromNet(subjectListBean.getSubjectId());
                return true;
            }
        });
        rlClassdes.setOnClickListener(this);
    }

    /**
     * @param clickType 点的哪一个分类 1 科目  2 分类  3 名师 4 大纲 5 大纲下分类
     * @param position  点的分类下的index
     */
    private void doFilter(int clickType, int position) {
        List<FilterBean.SubjectsBean.SortsBean> sorts;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean> teachers;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean> outlines;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean.OutlineClassificationBean> outlineClassification;
        switch (clickType) {
            case TYPE_SUBJECT:
                sorts = listSubject.get(position).getSorts();
                listFilter.clear();
                if (sorts != null) {
                    listFilter.addAll(sorts);
                }
                adapterType.notifyDataChanged();
                if (listFilter != null && listFilter.size() != 0) {
                    teachers = listFilter.get(0).getTeachers();
                } else {
                    teachers = new ArrayList<>();
                }
                listTeacher.clear();
                if (teachers != null) {
                    listTeacher.addAll(teachers);
                }
                adapterTeacher.notifyDataChanged();
                if (listTeacher != null && listTeacher.size() != 0) {
                    outlines = listTeacher.get(0).getOutlines();
                } else {
                    outlines = new ArrayList<>();
                }
                listOutline.clear();
                if (outlines != null) {
                    listOutline.addAll(outlines);
                }
                adapterOutline.notifyDataChanged();
                if (listOutline != null && listOutline.size() != 0) {
                    outlineClassification = listOutline.get(0).getOutlineClassification();
                } else {
                    outlineClassification = new ArrayList<>();
                }
                break;
            case TYPE_TYPE:
                teachers = listFilter.get(position).getTeachers();
                listTeacher.clear();
                if (teachers != null) {
                    listTeacher.addAll(teachers);
                }
                adapterTeacher.notifyDataChanged();
                if (listTeacher != null && listTeacher.size() != 0) {
                    outlines = listTeacher.get(0).getOutlines();
                } else {
                    outlines = new ArrayList<>();
                }
                listOutline.clear();
                if (outlines != null) {
                    listOutline.addAll(outlines);
                }
                adapterOutline.notifyDataChanged();
                if (listOutline != null && listOutline.size() != 0) {
                    outlineClassification = listOutline.get(0).getOutlineClassification();
                } else {
                    outlineClassification = new ArrayList<>();
                }
                break;
            case TYPE_TEACHER:
                outlines = listTeacher.get(position).getOutlines();
                listOutline.clear();
                if (outlines != null) {
                    listOutline.addAll(outlines);
                }
                adapterOutline.notifyDataChanged();
                if (listOutline != null && listOutline.size() != 0) {
                    outlineClassification = listOutline.get(0).getOutlineClassification();
                } else {
                    outlineClassification = new ArrayList<>();
                }
                break;
            case TYPE_OUTLINE:
                outlineClassification = listOutline.get(position).getOutlineClassification();
                break;
            default:
                if (listOutline != null && listOutline.size() != 0) {
                    outlineClassification = listOutline.get(0).getOutlineClassification();
                } else {
                    outlineClassification = new ArrayList<>();
                }
                break;


        }
        if (outlineClassification != null && outlineClassification.size() != 0) {
            listOutlineClass.clear();
            listOutlineClass.addAll(outlineClassification);
            adapterOutlineClass.notifyDataChanged();
            tflOutlineclass.setVisibility(View.VISIBLE);
        } else {
            listOutlineClass.clear();
            adapterOutlineClass.notifyDataChanged();
            tflOutlineclass.setVisibility(View.GONE);
        }
        getRequestData();
    }


    /**
     * @param response 请求回来response
     */
    private void dealDataFromNet(Response<FilterBean> response) {
        List<FilterBean.SubjectsBean> subjects;
        List<FilterBean.SubjectsBean.SortsBean> sorts;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean> teachers;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean> outlines;
        List<FilterBean.SubjectsBean.SortsBean.TeachersBean.OutlinesBean.OutlineClassificationBean> outlineClassification;
        try {
            FilterBean body = response.body();
            if (body != null) {
                subjects = body.getSubjects();
            } else {
                subjects = new ArrayList<>();
            }
            if (body.getSubjects() != null && body.getSubjects().size() != 0) {
                sorts = body.getSubjects().get(0).getSorts();
            } else {
                sorts = new ArrayList<>();
            }
            if (sorts != null && sorts.size() != 0) {
                teachers = body.getSubjects().get(0).getSorts().get(0).getTeachers();
            } else {
                teachers = new ArrayList<>();
            }
            if (teachers != null && teachers.size() != 0) {
                outlines = body.getSubjects().get(0).getSorts().get(0).getTeachers().get(0).getOutlines();
            } else {
                outlines = new ArrayList<>();
            }
            if (outlines != null && outlines.size() != 0) {
                outlineClassification = body.getSubjects().get(0).getSorts().get(0).getTeachers().get(0).getOutlines().get(0).getOutlineClassification();
            } else {
                outlineClassification = new ArrayList<>();
            }
            if (subjects != null) {
                listSubject.clear();
                listSubject.addAll(subjects);
            }
            if (sorts != null) {
                listFilter.clear();
                listFilter.addAll(sorts);
            }
            if (teachers != null) {
                listTeacher.clear();
                listTeacher.addAll(teachers);
            }
            if (outlines != null) {
                listOutline.clear();
                listOutline.addAll(outlines);
            }
            if (outlineClassification != null && outlineClassification.size() != 0) {
                listOutlineClass.clear();
                listOutlineClass.addAll(outlineClassification);
                adapterOutlineClass.setSelectedList(0);
                tflOutlineclass.setVisibility(View.VISIBLE);
            } else {
                tflOutlineclass.setVisibility(View.GONE);
            }
            adapterSubject.notifyDataChanged();
            adapterType.notifyDataChanged();
            adapterTeacher.notifyDataChanged();
            adapterOutline.notifyDataChanged();
            adapterOutlineClass.notifyDataChanged();
            adapterSubject.setSelectedList(0);
            adapterType.setSelectedList(0);
            adapterTeacher.setSelectedList(0);
            adapterOutline.setSelectedList(0);
        } catch (NullPointerException e) {

        }

    }

    /**
     * 每次筛选条件改变的时候封装视频列表接口需要的参数
     */
    private void getRequestData() {
        Iterator<Integer> iteratorSubject = tflSubject.getSelectedList().iterator();
        Iterator<Integer> iteratorType = tflType.getSelectedList().iterator();
        Iterator<Integer> iteratorTeacher = tflTeacher.getSelectedList().iterator();
        Iterator<Integer> iteratorOutline = tflOutline.getSelectedList().iterator();
        Iterator<Integer> iteratorOutlineClass = tflOutlineclass.getSelectedList().iterator();
        String idSubject = "";
        String idType = "";
        String idTeacher = "";
        String idOutline = "";
        String idOutlineClass = "";
        while (iteratorSubject.hasNext()) {
            Integer next = iteratorSubject.next();
            if (listSubject != null && listSubject.size() != 0) {
                idSubject = listSubject.get(next).getFilterSubjectId();
            }
//            Log.i("TAG", "======subjectName=" + listSubject.get(next).getFilterSubjectName() + idSubject);
        }
        while (iteratorType.hasNext()) {
            Integer next = iteratorType.next();
            if (listFilter != null && listFilter.size() != 0) {
                idType = listFilter.get(next).getFilterTypeId();
            }
//            Log.i("TAG", "======typeName=" + listFilter.get(next).getFilterTypeName() + idType);
        }
        while (iteratorTeacher.hasNext()) {
            Integer next = iteratorTeacher.next();
            if (listTeacher != null && listTeacher.size() != 0) {
                idTeacher = listTeacher.get(next).getFilterTeacherId();
            }
//            Log.i("TAG", "======teacherName=" + listTeacher.get(next).getFilterTeacherName() + idTeacher);
        }
        while (iteratorOutline.hasNext()) {
            Integer next = iteratorOutline.next();
            if (listOutline != null && listOutline.size() != 0) {
                idOutline = listOutline.get(next).getFilterOutlineId();
            }
//            Log.i("TAG", "======outlineName=" + listOutline.get(next).getFilterOutlineName() + idOutline);
        }
        while (iteratorOutlineClass.hasNext()) {
            Integer next = iteratorOutlineClass.next();
            if (listOutlineClass != null && listOutlineClass.size() != 0) {
                idOutlineClass = listOutlineClass.get(next).getFilterOutlineClassificationId();
            }
//            Log.i("TAG", "======outlineClassName=" + listOutlineClass.get(next).getFilterOutlineClassificationName() + idOutlineClass);
        }
        getVideoListFromNet(idSubject, idType, idTeacher, idOutline, idOutlineClass);
    }

    /**
     * 根据classId获取上方第一栏课程选项
     */
    private void getClassSubject() {
        HashMap<String, String> map = new HashMap<>();
        map.put("classId", classId);
        map.put("userId", userId);
        OkGoBuilder.getInstance().Builder(this).url(UrlConfig.GET_SUBJECTS_FILTER).method(OkGoBuilder.PSOT).requestBody(HttpUtils.getRequestJson(map)).cls(SubjectFilterBean.class).callback(new OkGoUtil<SubjectFilterBean>(SubjectFilterBean.class) {
            @Override
            public void onSuccess(Response<SubjectFilterBean> response) {
                if (response.body() != null && response.body().getSubjectList() != null) {
                    if (response.body() instanceof SubjectFilterBean) {
                        SubjectFilterBean body = response.body();
                        if (body != null && body.getSubjectList() != null) {
                            listClassSubject.addAll(body.getSubjectList());
                            adapterClassSubject.notifyDataChanged();
                            adapterClassSubject.setSelectedList(0);
                            Iterator<Integer> iteratorClassSubject = tflClasssubject.getSelectedList().iterator();
                            String classSubjectId = "";
                            while (iteratorClassSubject.hasNext()) {
                                Integer next = iteratorClassSubject.next();
                                classSubjectId = listClassSubject.get(next).getSubjectId();
                                subjectId = classSubjectId;
                                getFilterListFromNet(classSubjectId);
//                        Log.i("TAG", "======subjectName=" + listSubject.get(next).getFilterSubjectName() + idSubject);
                            }
                        }
                    }
                } else {
//                    ToastUtils.show(mContext, "网络请求异常");
                    loadingView.dismiss();
                }

            }

            @Override
            public void onError(Response<SubjectFilterBean> response) {
                ToastUtils.show(mContext, getResources().getString(R.string.neterror));
                loadingView.dismiss();
                super.onError(response);
            }
        }).build();

    }

    /**
     * 根据选中的课程Id获取下面的筛选条件
     *
     * @param subjectId 选中的课程Id
     */
    private void getFilterListFromNet(String subjectId) {
        loadingView.show();
        HashMap<String, String> map = new HashMap<>();
        map.put("subjectId", subjectId);
        map.put("userId", userId);
        OkGoBuilder.getInstance().url(UrlConfig.GET_FILTER).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(FilterBean.class).callback(new OkGoUtil<FilterBean>(FilterBean.class) {
            @Override
            public void onSuccess(Response<FilterBean> response) {
                if (response.body().getSubjects() != null) {
                    if (response.body() instanceof FilterBean) {
                        dealDataFromNet(response);
                        getRequestData();
                    }
                } else {
                    listSubject.clear();
                    listFilter.clear();
                    listTeacher.clear();
                    listOutline.clear();
                    listOutlineClass.clear();
                    totalList.clear();
                    mAdapter.notifyDataSetChanged();
                    adapterSubject.notifyDataChanged();
                    adapterType.notifyDataChanged();
                    adapterTeacher.notifyDataChanged();
                    adapterOutline.notifyDataChanged();
                    adapterOutlineClass.notifyDataChanged();
//                    ToastUtils.show(mContext, "网络请求异常");
                    loadingView.dismiss();
                }
            }

            @Override
            public void onError(Response<FilterBean> response) {
                ToastUtils.show(mContext, "网络请求异常");
                loadingView.dismiss();
                super.onError(response);
            }
        }).build();
    }

    /**
     * 获取视频列表
     */
    private void getVideoListFromNet(String idSubject, String idType, String idTeacher, String idOutline, String idOutlineClass) {
        loadingView.show();
//        progressDialog.show();
        OkGoBuilder.getInstance().url(UrlConfig.GET_VIDEOLIST).Builder(this).requestBody(HttpUtils.getRequestJson(initVideoListRequestJson(classId, subjectId, userId, idSubject, idType, idTeacher, idOutline, idOutlineClass))).cls(VideoBean.class).method(OkGoBuilder.PSOT).callback(new OkGoUtil<VideoBean>(VideoBean.class) {
            @Override
            public void onSuccess(Response<VideoBean> response) {
                loadingView.dismiss();
                totalList.clear();
                if (response.body() != null && response.body().getList() != null) {
                    if (response.body() instanceof VideoBean) {
                        VideoBean body = response.body();
                        List<VideoBean.ListBean> list = body.getList();
                        totalList.addAll(list);
                    }
                }
                mAdapter.notifyDataSetChanged();
                /* else {
                    ToastUtils.show(mContext, "网络请求异常");
                }*/

//                progressDialog.dismiss();

            }

            @Override
            public void onError(Response<VideoBean> response) {
                loadingView.dismiss();
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }).build();

    }

    /**
     * @param classId        班型Id
     * @param subjectClassId 选中的上一级的课程id
     * @param userId         用户Id
     * @param idSubject      科目Id
     * @param idType         分类Id
     * @param idTeacher      名师Id
     * @param idOutline      大纲Id
     * @param idOutlineClass 大纲下分类Id
     * @return 返回处理好的请求requestBody
     */
    private HashMap<String, String> initVideoListRequestJson(String classId, String subjectClassId, String userId, String idSubject, String idType, String idTeacher, String idOutline, String idOutlineClass) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("subjectId", classId);
        map.put("filterSubjectId", idSubject);
        map.put("filterTypeId", idType);
        map.put("courseId", subjectClassId);
        map.put("filterTeacherId", idTeacher);
        map.put("filterOutlineId", idOutline);
        map.put("filterOutlineClassificationId", idOutlineClass);
        return map;
    }


    @Override
    public void initData(Context mContext) {
        adapterClassSubject = new FilterClassAdapter(listClassSubject, getLayoutInflater(), tflClasssubject);
        tflClasssubject.setAdapter(adapterClassSubject);
        adapterSubject = new FilterAdapter(listSubject, getLayoutInflater(), tflSubject);
        tflSubject.setAdapter(adapterSubject);
        adapterType = new FilterAdapter(listFilter, getLayoutInflater(), tflType);
        tflType.setAdapter(adapterType);
        adapterTeacher = new FilterAdapter(listTeacher, getLayoutInflater(), tflTeacher);
        tflTeacher.setAdapter(adapterTeacher);
        adapterOutline = new FilterAdapter(listOutline, getLayoutInflater(), tflOutline);
        tflOutline.setAdapter(adapterOutline);
        adapterOutlineClass = new FilterAdapter(listOutlineClass, getLayoutInflater(), tflOutlineclass);
        tflOutlineclass.setAdapter(adapterOutlineClass);
        getClassSubject();
    }
}
