package com.beanpodtech.allinone.activity;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.StudyPlanAdapter;
import com.beanpodtech.allinone.adapter.StudyPlanListAdapter;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.beanpodtech.allinone.bean.GetDatePlanBean;
import com.beanpodtech.allinone.bean.GetPlanBean;
import com.beanpodtech.allinone.bean.GetselectedvideoList;
import com.beanpodtech.allinone.bean.Getstudyplan;
import com.beanpodtech.allinone.bean.TestClass;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.DateUtils;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.PlayVideoUtils;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.calendar.Utils;
import com.beanpodtech.allinone.widget.calendar.component.CalendarAttr;
import com.beanpodtech.allinone.widget.calendar.component.CalendarViewAdapter;
import com.beanpodtech.allinone.widget.calendar.interf.OnSelectDateListener;
import com.beanpodtech.allinone.widget.calendar.model.CalendarDate;
import com.beanpodtech.allinone.widget.calendar.view.Calendar;
import com.beanpodtech.allinone.widget.calendar.view.CustomDayView;
import com.beanpodtech.allinone.widget.calendar.view.MonthPager;
import com.beanpodtech.allinone.widget.flowlayout.FlowLayout;
import com.beanpodtech.allinone.widget.flowlayout.TagFlowLayout;
import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class StudyplanActivity extends Activity {
    PopupWindow popupWindow;
    HomeAdapter mAdapter;
    private StudyPlanListAdapter studyplanreview;
    private List<GetPlanBean.ListBean> listPlay = new ArrayList<>();
    RecyclerView recyclerView, toRecycleview;
    private List<Getstudyplan.ClassesBean> listclasses = new ArrayList<>();
    private List<Getstudyplan.ClassesBean.CourseBean> listcourse = new ArrayList<>();
    private List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean> listsubjects = new ArrayList<>();
    private List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean> listtype = new ArrayList<>();
    private List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean.TeachersBean> listteachers = new ArrayList<>();
    private List<TestClass> testClass = new ArrayList<>();
    private TagFlowLayout clSelection, clCourse, clSubjiet, clTeather, clType;
    private StudyPlanAdapter studyPlanAdapter, sucourseAdapter, subjiecAdapter, typeAdapter, classAdapter;
    private LinearLayout editplan;
    private LinearLayout saveThePlan;
    private TextView tvSavePlan, planSave;
    private View popipWindowView;
    private ImageView delete, studyWrite;
    private String userId;
    JSONObject jsonObject = null;
    JSONArray jsonArray = new JSONArray();
    JSONObject object = null;
    DatePicker datePicker;
    //    int year, month, day;
    String SelectedTime;
    private long timeStamp;
    List<GetselectedvideoList.ListBean> selectedVideoList;
    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.study_write:
                    getPopupWindow();
                    popupWindow.showAtLocation(view, Gravity.CENTER_HORIZONTAL, 0, 0);
                    init(view);
                    break;
                case R.id.tv_save_plan:
                    editplan.setVisibility(View.VISIBLE);
                    saveThePlan.setVisibility(View.GONE);
                    mAdapter.undeleteData(true);
                    Addstudyplan();
                    break;
                case R.id.study_delete:
                    studyplanreview.setIsDelete(StudyPlanListAdapter.ISDELETE);
                    delete.setVisibility(View.GONE);
                    studyWrite.setVisibility(View.GONE);
                    planSave.setVisibility(View.VISIBLE);

                    break;
                case R.id.buttonq:
                    if (popipWindowView != null && popipWindowView.isShown()) {
                        popupWindow.dismiss();
                        popupWindow = null;
                    }
                    break;
                case R.id.s_filter:
                    if (popipWindowView != null && popipWindowView.isShown()) {
                        editplan.setVisibility(View.GONE);
                        saveThePlan.setVisibility(View.VISIBLE);
                        popupWindow.dismiss();
                        popupWindow = null;
                        getRequestData();
                    }
                    break;
                case R.id.plan_save:
                    delete.setVisibility(View.VISIBLE);
                    studyWrite.setVisibility(View.VISIBLE);
                    planSave.setVisibility(View.GONE);

                    deletePlan();
                    break;

                case R.id.iv_back:
                    finish();
                    break;
            }
        }
    };
    private ImageView ivBack;

    /**
     * 删除学习计划
     */
    private void deletePlan() {
        studyplanreview.setIsDelete(StudyPlanListAdapter.ISNOTDELETE);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < listPlay.size(); i++) {
            if (listPlay.get(i).isSelect()) {
                stringBuilder.append(listPlay.get(i).getPlanId()).append(",");
            }
        }
        if (stringBuilder.length() == 0) {
            ToastUtils.show(this, getString(R.string.please_select_delete_plan));
//            showDeleteMenu();
            return;
        }
        String substring = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("planId", substring);
        OkGoBuilder.getInstance().url(UrlConfig.DELETEPLAN).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(BaseRequestBean.class).callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
            @Override
            public void onSuccess(Response<BaseRequestBean> response) {
                if (response.body() != null) {
                    if (response.body().getStatus() == 1) {
                        ToastUtils.show(StudyplanActivity.this, R.string.delete_success);
                    } else {
                        ToastUtils.show(StudyplanActivity.this, R.string.delete_fail);
                    }
                }
                getPlayForThisDay();
            }
        }).build();

    }

    //日历所用的控件
    private ImageView ivLastmonth;
    private TextView showDateView;
    private ImageView ivNextmonth;
    private MonthPager calendarView;
    private ArrayList<Calendar> currentCalendars = new ArrayList<>();
    private CalendarViewAdapter calendarAdapter;
    private OnSelectDateListener onSelectDateListener;
    private CalendarDate currentDate;
    private boolean initiated = false;
    //用来请求小红点的参数
    private String timeMonth;

    private void Addstudyplan() {
        jsonArray = new JSONArray();
        if (jsonObject != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("userId", userId);
            map.put("date", timeStamp + "");
            map.put("videoIdList", jsonObject.toString());

            OkGoBuilder.getInstance().url(UrlConfig.ADDSTUDYPLAN).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(BaseRequestBean.class).callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                @Override
                public void onSuccess(Response<BaseRequestBean> response) {
                    if (response.body() != null) {
                        if (response.body().getStatus() == 1) {
                            ToastUtils.show(StudyplanActivity.this, getString(R.string.add_success));
                        } else {
                            ToastUtils.show(StudyplanActivity.this, getString(R.string.add_fail));
                        }
                        getPlayForThisDay();
                        getHasPlanDays();
                    }
                }
            }).build();
        }
        mAdapter.notifyDataSetChanged();

    }

    public void getRequestData() {
        Iterator<Integer> iteratorClass = clSelection.getSelectedList().iterator();
        Iterator<Integer> iteratorCourse = clCourse.getSelectedList().iterator();
        Iterator<Integer> iteratorSubject = clSubjiet.getSelectedList().iterator();
        Iterator<Integer> iteratorType = clType.getSelectedList().iterator();
        Iterator<Integer> iteratorTeather = clTeather.getSelectedList().iterator();
        String idClass = "";
        String idCourse = "";
        String idSubject = "";
        String idType = "";
        String idteacher = "";
        while (iteratorClass.hasNext()) {
            Integer next = iteratorClass.next();
            idClass = listclasses.get(next).getFilterClassId();

        }
        while (iteratorCourse.hasNext()) {
            Integer next = iteratorCourse.next();
            if (listcourse != null && listcourse.size() != 0) {
                idCourse = listcourse.get(next).getFilterCourseId();
            }

        }

        while (iteratorSubject.hasNext()) {
            Integer next = iteratorSubject.next();
            if (listsubjects != null && listsubjects.size() != 0) {
                idSubject = listsubjects.get(next).getFilterSubjectId();
            }
        }
        while (iteratorType.hasNext()) {
            Integer next = iteratorType.next();
            if (listtype != null && listtype.size() != 0) {
                idType = listtype.get(next).getFilterTypeId();
            }
        }
        while (iteratorTeather.hasNext()) {
            Integer next = iteratorTeather.next();
            if (listteachers != null && listteachers.size() != 0) {
                idteacher = listteachers.get(next).getFilterTeacherId();
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("filterClassId", idClass);
        map.put("filterCourseId", idCourse);
        map.put("filterSubjectId", idSubject);
        map.put("filterTypeId", idType);
        map.put("filterTeacherId", idteacher);
        OkGoBuilder.getInstance().url(UrlConfig.GETSELECTEDVIDEOLIST).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(GetselectedvideoList.class).callback(new OkGoUtil<GetselectedvideoList>(GetselectedvideoList.class) {
            @Override
            public void onSuccess(Response<GetselectedvideoList> response) {
                GetselectedvideoList body = response.body();
                selectedVideoList = body.getList();
                recyclerView.setAdapter(mAdapter = new HomeAdapter());
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                listclasses.clear();
                listcourse.clear();
                listsubjects.clear();
                listtype.clear();
                listteachers.clear();
            }
        }).build();

    }


    public void init(View view) {
        studyPlanAdapter = new StudyPlanAdapter(listclasses, getLayoutInflater(), clSelection);
        clSelection.setAdapter(studyPlanAdapter);
        sucourseAdapter = new StudyPlanAdapter(listcourse, getLayoutInflater(), clCourse);
        clCourse.setAdapter(sucourseAdapter);
        subjiecAdapter = new StudyPlanAdapter(listsubjects, getLayoutInflater(), clSubjiet);
        clSubjiet.setAdapter(subjiecAdapter);
        typeAdapter = new StudyPlanAdapter(listtype, getLayoutInflater(), clType);
        clType.setAdapter(typeAdapter);
        classAdapter = new StudyPlanAdapter(listteachers, getLayoutInflater(), clTeather);
        clTeather.setAdapter(classAdapter);
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
//        initTempData();

        OkGoBuilder.getInstance().url(UrlConfig.GETFILTERVIDEOCONDITION).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(Getstudyplan.class).callback(new OkGoUtil<Getstudyplan>(Getstudyplan.class) {
            @Override
            public void onSuccess(Response<Getstudyplan> response) {

                if (response.body().getClasses() != null) {
                    if (response.body() instanceof Getstudyplan) {
                        dealDataFromNet(response);
                    }
                } else {
                    listclasses.clear();
                    listcourse.clear();
                    listsubjects.clear();
                    listtype.clear();
                    listteachers.clear();
                    studyPlanAdapter.notifyDataChanged();
                    sucourseAdapter.notifyDataChanged();
                    subjiecAdapter.notifyDataChanged();
                    typeAdapter.notifyDataChanged();
                    classAdapter.notifyDataChanged();
                }
            }
        }).build();
//        initTempData();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_studyplan);
        userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
        editplan = findViewById(R.id.s_editplan);
        saveThePlan = findViewById(R.id.save_the_plan);
        tvSavePlan = findViewById(R.id.tv_save_plan);
        studyWrite = findViewById(R.id.study_write);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(click);

        studyWrite.setOnClickListener(click);
        tvSavePlan.setOnClickListener(click);
        delete = findViewById(R.id.study_delete);
        planSave = findViewById(R.id.plan_save);
        planSave.setOnClickListener(click);
        delete.setOnClickListener(click);
        toRecycleview = findViewById(R.id.to_plan_recycview);
        toRecycleview.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL));
        studyplanreview = new StudyPlanListAdapter(listPlay, this);
        toRecycleview.setAdapter(studyplanreview);
        studyplanreview.setIsDelete(StudyPlanListAdapter.ISNOTDELETE);
        toRecycleview.setItemAnimator(new DefaultItemAnimator());

        recyclerView = findViewById(R.id.idplan_recycview);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL));
        datePicker = findViewById(R.id.datepicker);
        findViewForCalendar();
        currentDate = new CalendarDate();
        showDateView.setText(currentDate.getYear() + "年" + currentDate.getMonth() + "月");
        SelectedTime = currentDate.year + "-" + currentDate.month + "-" + currentDate.day;
        timeMonth = currentDate.year + "-" + ((currentDate.month + "").length() == 1 ? ("0" + currentDate.month) : (currentDate.month));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            timeStamp = sdf.parse(SelectedTime).getTime();
            timeStamp = timeStamp / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        getHasPlanDays();
        getPlayForThisDay();
    }

    /**
     * 日历控件初始化
     */
    private void findViewForCalendar() {
        ivLastmonth = findViewById(R.id.iv_lastmonth);
        showDateView = findViewById(R.id.show_date_view);
        ivNextmonth = findViewById(R.id.iv_nextmonth);
        calendarView = findViewById(R.id.calendar_view);
        calendarView.setViewHeight(Utils.dpi2px(this, 290));
        initCalendarView();
    }

    /**
     * 请求该日期下的计划列表
     */
    private void getPlayForThisDay() {
        HashMap<String, String> p_map = new HashMap<>();
        p_map.put("userId", userId);
        p_map.put("date", timeStamp + "");
        OkGoBuilder.getInstance().url(UrlConfig.STUDYPLAN).Builder(this).requestBody(HttpUtils.getRequestJson(p_map)).method(OkGoBuilder.PSOT).cls(GetPlanBean.class).callback(new OkGoUtil<GetPlanBean>(GetPlanBean.class) {
            @Override
            public void onSuccess(Response<GetPlanBean> response) {
                listPlay.clear();
                if (response.body() != null) {
                    GetPlanBean planBean = response.body();
                    List<GetPlanBean.ListBean> list = planBean.getList();
                    if (list != null && list.size() != 0) {
                        listPlay.addAll(list);
                    }
                }
                studyplanreview.notifyDataSetChanged();
            }
        }).build();
    }

    /**
     * 请求该月哪一天有小红点
     */
    private void getHasPlanDays() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("time", timeMonth);
        OkGoBuilder.getInstance().url(UrlConfig.GETTIMERPLAN).Builder(this).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(GetDatePlanBean.class).callback(new OkGoUtil<GetDatePlanBean>(GetDatePlanBean.class) {
            @Override
            public void onSuccess(Response<GetDatePlanBean> response) {
                if (response.body() != null) {
                    GetDatePlanBean datePlanBean = response.body();
                    List<GetDatePlanBean.ListBean> list = datePlanBean.getList();
                    if (list != null && list.size() != 0) {
                        initMarkData(list);
                    }
                }
            }
        }).build();
    }

    /**
     * 创建PopupWindow
     */
    protected void initPopupWindow() {
        // TODO: 15/10/9
        //获取自定义布局文件activity_pop_left.xml 布局文件
        popipWindowView = getLayoutInflater().inflate(R.layout.study_popupwindow, null, false);
        //创建Popupwindow 实例，200，LayoutParams.MATCH_PARENT 分别是宽高
        popupWindow = new PopupWindow(popipWindowView, (int) getResources().getDimension(R.dimen.x900), (int) getResources().getDimension(R.dimen.y900), false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        setTransparentBg();
        clSelection = popipWindowView.findViewById(R.id.cl_selection);
        clSelection.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(1, position);
                return true;
            }
        });
        clCourse = popipWindowView.findViewById(R.id.cl_course);
        clCourse.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(2, position);
                return false;
            }
        });
        clSubjiet = popipWindowView.findViewById(R.id.cl_subjiet);
        clSubjiet.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(3, position);
                return false;
            }
        });
        clType = popipWindowView.findViewById(R.id.cl_type);
        clType.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(4, position);
                return false;
            }
        });
        clTeather = popipWindowView.findViewById(R.id.cl_teather);
        clTeather.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doFilter(5, position);
                return false;
            }
        });

        TextView cancel = popipWindowView.findViewById(R.id.buttonq);
        TextView filter = popipWindowView.findViewById(R.id.s_filter);
        cancel.setOnClickListener(click);
        filter.setOnClickListener(click);
    }

    private void setTransparentBg() {
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;//调节透明度
        getWindow().setAttributes(lp);
        //监听弹窗
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //弹窗关闭  dismiss()时恢复原样
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //拦截弹窗外部点击事件
        if (popupWindow != null && popupWindow.isShowing()) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * @param clickType 点的哪一个分类 1 年级  2 类型  3 科目 4 名师 5 大纲 6 大纲下分类
     * @param position  点的分类下的index
     */
    private void doFilter(int clickType, int position) {
        List<Getstudyplan.ClassesBean.CourseBean> course = null;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean> subjects = null;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean> type = null;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean.TeachersBean> teachers = null;

        switch (clickType) {
            case 1:
                course = listclasses.get(position).getCourse();
                listcourse.clear();
                if (course != null) {
                    listcourse.addAll(course);
                }
                sucourseAdapter.notifyDataChanged();

                if (listcourse != null && listcourse.size() != 0) {
                    subjects = listcourse.get(0).getSubjects();
                } else {
                    subjects = new ArrayList<>();
                }
                listsubjects.clear();
                if (subjects != null) {
                    listsubjects.addAll(subjects);
                }
                subjiecAdapter.notifyDataChanged();

                if (listsubjects != null && listsubjects.size() != 0) {
                    type = listsubjects.get(0).getTypes();
                } else {
                    type = new ArrayList<>();
                }
                listtype.clear();
                if (type != null) {
                    listtype.addAll(type);
                }
                typeAdapter.notifyDataChanged();

                if (listtype != null && listtype.size() != 0) {
                    teachers = listtype.get(0).getTeachers();
                } else {
                    teachers = new ArrayList<>();
                }
                listteachers.clear();
                if (teachers != null) {
                    listteachers.addAll(teachers);
                }
                classAdapter.notifyDataChanged();
                break;
            case 2:
                subjects = listcourse.get(position).getSubjects();
                listsubjects.clear();
                if (subjects != null) {
                    listsubjects.addAll(subjects);
                }
                subjiecAdapter.notifyDataChanged();
                if (listsubjects != null && listsubjects.size() != 0) {
                    type = listsubjects.get(0).getTypes();
                } else {
                    type = new ArrayList<>();
                }
                listtype.clear();
                if (type != null) {
                    listtype.addAll(type);
                }
                typeAdapter.notifyDataChanged();
                if (listtype != null && listtype.size() != 0) {
                    teachers = listtype.get(0).getTeachers();
                } else {
                    teachers = new ArrayList<>();
                }
                listteachers.clear();
                if (teachers != null) {
                    listteachers.addAll(teachers);
                }
                classAdapter.notifyDataChanged();
                break;
            case 3:
                type = listsubjects.get(position).getTypes();
                listtype.clear();
                if (type != null) {
                    listtype.addAll(type);
                }
                typeAdapter.notifyDataChanged();
                if (listtype != null && listtype.size() != 0) {
                    teachers = listtype.get(0).getTeachers();
                } else {
                    teachers = new ArrayList<>();
                }
                listteachers.clear();
                if (teachers != null) {
                    listteachers.addAll(teachers);
                }
                classAdapter.notifyDataChanged();
                break;
            case 4:
                teachers = listtype.get(position).getTeachers();
                listteachers.clear();
                if (teachers != null) {
                    listteachers.addAll(teachers);
                }
                classAdapter.notifyDataChanged();
                break;
            default:
                break;
        }
    }


    /**
     * 获取PopipWinsow实例
     */
    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopupWindow();
        }
    }

    /**
     * @param response 请求回来response
     */
    private void dealDataFromNet(Response<Getstudyplan> response) {
        List<Getstudyplan.ClassesBean> listclasses;
        List<Getstudyplan.ClassesBean.CourseBean> listcourse;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean> listsubjects;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean> listtype;
        List<Getstudyplan.ClassesBean.CourseBean.SubjectsBean.TypesBean.TeachersBean> listteachers;

        try {
            Getstudyplan body = response.body();
            if (body != null) {
                listclasses = body.getClasses();
            } else {
                listclasses = new ArrayList<>();
            }
            if (body.getClasses() != null && body.getClasses().size() != 0) {
                listcourse = body.getClasses().get(0).getCourse();
            } else {
                listcourse = new ArrayList<>();
            }
            if (listcourse != null && listcourse.size() != 0) {
                listsubjects = body.getClasses().get(0).getCourse().get(0).getSubjects();
            } else {
                listsubjects = new ArrayList<>();
            }
            if (listsubjects != null && listsubjects.size() != 0) {
                listtype = body.getClasses().get(0).getCourse().get(0).getSubjects().get(0).getTypes();
            } else {
                listtype = new ArrayList<>();
            }
            if (listtype != null && listtype.size() != 0) {
                listteachers = body.getClasses().get(0).getCourse().get(0).getSubjects().get(0).getTypes().get(0).getTeachers();

            } else {
                listteachers = new ArrayList<>();
            }
            if (listclasses != null) {
                this.listclasses.clear();
                this.listclasses.addAll(listclasses);
            }
            if (listcourse != null) {
                this.listcourse.clear();
                this.listcourse.addAll(listcourse);
            }
            if (listsubjects != null) {
                this.listsubjects.clear();
                this.listsubjects.addAll(listsubjects);
            }
            if (listtype != null) {
                this.listtype.clear();
                this.listtype.addAll(listtype);
            }
            if (listteachers != null) {
                this.listteachers.clear();
                this.listteachers.addAll(listteachers);
            }
            studyPlanAdapter.notifyDataChanged();
            sucourseAdapter.notifyDataChanged();
            subjiecAdapter.notifyDataChanged();
            typeAdapter.notifyDataChanged();
            classAdapter.notifyDataChanged();
            studyPlanAdapter.setSelectedList(0);
            sucourseAdapter.setSelectedList(0);
            subjiecAdapter.setSelectedList(0);
            typeAdapter.setSelectedList(0);
            classAdapter.setSelectedList(0);
        } catch (NullPointerException e) {

        }

    }

    class HomeAdapter extends RecyclerView.Adapter {
        public Boolean stat = false;

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_addstudyplan_recycleciew, parent, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        public void undeleteData(Boolean stat) {
            this.stat = stat;
            notifyDataSetChanged();
        }

        @Override
        public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
            if (stat == true) {
                ((ViewHolder) holder).add_stustplan.setVisibility(View.VISIBLE);
                ((ViewHolder) holder).joined_stustplan.setVisibility(View.GONE);
            } else {
                if (selectedVideoList.get(position).isAddingStatus()) {
                    ((ViewHolder) holder).add_stustplan.setVisibility(View.GONE);
                    ((ViewHolder) holder).joined_stustplan.setVisibility(View.VISIBLE);
                } else {
                    ((ViewHolder) holder).add_stustplan.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ((ViewHolder) holder).add_stustplan.setVisibility(View.GONE);
                            ((ViewHolder) holder).joined_stustplan.setVisibility(View.VISIBLE);
                            try {
                                jsonObject = new JSONObject();
                                object = new JSONObject();
                                object.put("videoId", selectedVideoList.get(position).getVideoId());
                                jsonArray.put(object);
                                jsonObject.put("list", jsonArray);
                            } catch (JSONException e) {
                                e.printStackTrace();

                            }
                        }
                    });
                }
            }
            ((ViewHolder) holder).time.setText("总时长:  " + selectedVideoList.get(position).getVideoDuration());
            ((ViewHolder) holder).title.setText(selectedVideoList.get(position).getVideoName());
            ((ViewHolder) holder).videoName.setText(selectedVideoList.get(position).getVideoName());
            ((ViewHolder) holder).teacher.setText(selectedVideoList.get(position).getTeacherName());
            Glide.with(StudyplanActivity.this).load(selectedVideoList.get(position).getPicturePath()).into(((ViewHolder) holder).image);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PlayVideoUtils.getInstance().setVideoId(selectedVideoList.get(position).getVideoId()).setContext(StudyplanActivity.this).setCourseId(selectedVideoList.get(position).getCourseId()).setType(PlayVideoUtils.NORMAL_VIDEO).setIsNeedRecord(true).build();
//                PlayVideoUtils utils = new PlayVideoUtils(mContext, list.get(position).getVideoId(), list.get(position).getCourseId(), PlayVideoUtils.NORMAL_VIDEO);
//                utils.getPlayAuthToPlay();
//                loadingView.show();
//                getPlayAuth(list.get(position));
                }
            });
        }

        @Override
        public int getItemCount() {
            if (selectedVideoList == null) {
                return 0;
            } else {

                return selectedVideoList.size();
            }

        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            TextView joined_stustplan;
            TextView add_stustplan;
            TextView time;
            TextView title;
            TextView videoName;
            TextView teacher;
            ImageView image;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                joined_stustplan = itemView.findViewById(R.id.joined_stustplan);
                add_stustplan = itemView.findViewById(R.id.add_stustplan);
                time = itemView.findViewById(R.id.time);
                title = itemView.findViewById(R.id.title);
                videoName = itemView.findViewById(R.id.videoName);
                teacher = itemView.findViewById(R.id.teacher);
                image = itemView.findViewById(R.id.image);
            }
        }
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !initiated) {
            refreshMonthPager();
            initiated = true;
        }
    }

    /**
     * 初始化CustomDayView，并作为CalendarViewAdapter的参数传入
     */
    private void initCalendarView() {
        initCalendarListener();
        CustomDayView customDayView = new CustomDayView(this, R.layout.custom_day);
        calendarAdapter = new CalendarViewAdapter(
                this,
                onSelectDateListener,
                CalendarAttr.WeekArrayType.Monday,
                customDayView);
        initMonthPager();
    }


    private void initMarkData(List<GetDatePlanBean.ListBean> listBeans) {
        HashMap<String, String> markData = new HashMap<>();
        for (int i = 0; i < listBeans.size(); i++) {
            markData.put(listBeans.get(i).getYear() + "-" + subStringZero(listBeans.get(i).getMonth()) + "-" + subStringZero(listBeans.get(i).getDay()), "1");
        }
        calendarAdapter.setMarkData(markData);
    }

    private String subStringZero(String date) {
        if (date.length() == 2) {
            if ("0".equals(date.substring(0, 1))) {
                return date.substring(1, 2);
            } else {
                return date;
            }
        } else {
            return date;
        }
    }

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

    private void initMonthPager() {
        calendarView.setAdapter(calendarAdapter);
        calendarAdapter.switchToWeek(calendarView.getRowIndex());
        calendarAdapter.switchToMonth();
        calendarView.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        calendarView.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        calendarView.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
//                mCurrentPage = position;
                currentCalendars = calendarAdapter.getPagers();
                if (currentCalendars.get(position % currentCalendars.size()) != null) {
                    CalendarDate date = currentCalendars.get(position % currentCalendars.size()).getSeedDate();
                    currentDate = date;
                    showDateView.setText(currentDate.getYear() + "年" + currentDate.getMonth() + "月");
                    timeStamp = DateUtils.parseDate(currentDate.getYear() + "-" + currentDate.getMonth() + "-" + currentDate.getDay(), DateUtils.DEFAULT_FORMATS).getTime() / 1000;
                    StudyplanActivity.this.timeMonth = currentDate.getYear() + "-" + ((currentDate.getMonth() + "").length() == 1 ? ("0" + currentDate.getMonth()) : (currentDate.getMonth()));
                    // TODO: 2020/7/6 换月展示小红点
                    getHasPlanDays();
                    getPlayForThisDay();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initCalendarListener() {
        onSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                calendarView.selectOtherMonth(offset);
            }
        };
        ivNextmonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                calendarView.setCurrentItem(calendarView.getCurrentPosition() + 1);
            }
        });
        ivLastmonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                calendarView.setCurrentItem(calendarView.getCurrentPosition() - 1);
            }
        });
    }

    private void refreshClickDate(CalendarDate date) {
        currentDate = date;
        showDateView.setText(currentDate.getYear() + "年" + currentDate.getMonth() + "月");
        timeStamp = DateUtils.parseDate(currentDate.getYear() + "-" + currentDate.getMonth() + "-" + currentDate.getDay(), DateUtils.DEFAULT_FORMATS).getTime() / 1000;
        getPlayForThisDay();
    }

    private void refreshMonthPager() {
        CalendarDate today = new CalendarDate();
        calendarAdapter.notifyDataChanged(today);
        showDateView.setText(today.getYear() + "年" + today.getMonth() + "月");
    }
}
