package com.cooleshow.student.ui.main

import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.CustomListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cooleshow.base.common.WebConstants
import com.cooleshow.base.router.RouterPath
import com.cooleshow.base.ui.fragment.BaseMVPFragment
import com.cooleshow.base.utils.SizeUtils
import com.cooleshow.base.utils.TimeUtils
import com.cooleshow.base.widgets.EmptyViewLayout
import com.cooleshow.student.R
import com.cooleshow.student.adapter.CourseTableListAdapter
import com.cooleshow.student.bean.CourseTableDataBean
import com.cooleshow.student.constants.CourseTableContract
import com.cooleshow.student.databinding.FragmentCourseTableLayoutBinding
import com.cooleshow.student.presenter.main.CourseTablePresenter
import com.cooleshow.student.ui.course.SparringCourseDetailActivity
import com.cooleshow.student.widgets.CalendarExpandDecoration
import com.cooleshow.student.widgets.CalendarShrinkDecoration
import com.cooleshow.student.widgets.helper.CourseHelper
import com.haibin.calendarview.CalendarView
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import io.rong.imkit.utils.helper.OpenChatHelper
import kotlinx.android.synthetic.main.fragment_course_table_layout.*
import java.util.*


/**
 * Author by pq, Date on 2022/4/20.
 */
class CourseTableFragment :
    BaseMVPFragment<FragmentCourseTableLayoutBinding, CourseTablePresenter>(),
    CalendarView.OnCalendarSelectListener,
    CalendarView.OnCalendarInterceptListener, CalendarView.OnMonthChangeListener,
    CalendarView.OnViewChangeListener, CourseTableContract.CourseTableView, View.OnClickListener {
    private lateinit var currentSelectDate: Date
    private lateinit var calendarDate: String
    private lateinit var calendarExpandDecoration: CalendarExpandDecoration
    private lateinit var calendarShrinkDecoration: CalendarShrinkDecoration
    private lateinit var adapter: CourseTableListAdapter
    private lateinit var pvTime: TimePickerView
    private lateinit var emptyView: EmptyViewLayout
    private lateinit var emptyText: TextView
    private lateinit var emptyIcon: ImageView
    private var day: Int = -1;

    override fun getLayoutView(): FragmentCourseTableLayoutBinding {
        return FragmentCourseTableLayoutBinding.inflate(layoutInflater)
    }

    override fun initView(rootView: View?) {
        mViewBinding.calendarView.setOnCalendarSelectListener(this)
        mViewBinding.calendarView.setOnCalendarInterceptListener(this)
        mViewBinding.calendarView.setOnMonthChangeListener(this)
        mViewBinding.calendarView.setOnViewChangeListener(this)
        calendarExpandDecoration = CalendarExpandDecoration(context)
        calendarShrinkDecoration = CalendarShrinkDecoration(context)
        mViewBinding.tvCurrentDate.setOnClickListener(this)
        val layoutManager = LinearLayoutManager(
            activity
        )
        mViewBinding.recyclerView.layoutManager = layoutManager
        mViewBinding.recyclerView.addItemDecoration(calendarShrinkDecoration, 0)
        adapter = CourseTableListAdapter(R.layout.item_course_table_layout);
        val inflater = LayoutInflater.from(context)
        val emptyLayout: View = inflater.inflate(R.layout.layout_empty_course_table, null)
        val tv_find_course = emptyLayout.findViewById<TextView>(R.id.tv_find_course)
        tv_find_course.setOnClickListener(View.OnClickListener {
            (activity as MainActivity?)!!.setPositionItem(0)
        })
        adapter.setEmptyView(emptyLayout)
        mViewBinding.recyclerView.adapter = adapter
        mViewBinding.recyclerView.addOnItemTouchListener(object :
            RecyclerView.SimpleOnItemTouchListener() {
            var y = 0f
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> y = e.y
                    MotionEvent.ACTION_UP -> {
                        val right: Int = rv.width / 2 - SizeUtils.dp2px(16f)
                        val left: Int = rv.width / 2 + SizeUtils.dp2px(16f)
                        if (right < e.x && e.x < left && e.y < SizeUtils.dp2px(30f) && y < SizeUtils.dp2px(
                                30f
                            )
                        ) {
                            if (mViewBinding.calendarLayout.isExpand) {
                                Log.e("sdfsdgsdsdasdaf", "shrink")

                                mViewBinding.calendarLayout.shrink()
                            } else {
                                Log.e("sdfsdgsdsdasdaf", "expand")
                                mViewBinding.calendarLayout.expand()
                            }
                            return true
                        }
                    }
                }
                return super.onInterceptTouchEvent(rv, e)
            }
        })
        adapter.setOnItemClickListener(OnItemClickListener() { adapter, view, position ->
            var data: CourseTableDataBean.StudentListBean =
                adapter.data[position] as CourseTableDataBean.StudentListBean;
            if (TextUtils.equals(CourseTableListAdapter.OTHER_COURSE, data?.courseType)) {
                //陪练课
                ARouter.getInstance()
                    .build(RouterPath.CourseCenter.SPARRING_COURSE_DETAIL)
                    .withString(SparringCourseDetailActivity.COURSE_ID, data.courseId)
                    .withString(
                        SparringCourseDetailActivity.COURSE_GROUP_ID,
                        data.courseGoupId
                    )
                    .navigation()
            } else if (TextUtils.equals(
                    CourseTableListAdapter.PIANO_ROOM_COURSE,
                    data?.courseType
                )
            ) {
                //琴房课 跳转详情页
                ARouter.getInstance().build(RouterPath.CourseCenter.PIANO_ROOM_COURSE_DETAIL)
                    .withString("course_id", data.courseId)
                    .navigation()
            } else {
                //直播课
                ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(
                        WebConstants.WEB_URL,
                        String.format(
                            WebConstants.TEACHER_LIVE_DETAIL_NORMAL_COURSE,
                            data.courseGoupId,
                            data.courseId
                        )
                    )
                    .navigation()
            }
        })

        adapter.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position ->
            var data: CourseTableDataBean.StudentListBean =
                adapter.data[position] as CourseTableDataBean.StudentListBean;
            if (view.id == R.id.iv_go_chat) {
                if (TextUtils.equals(data.courseType, CourseTableListAdapter.OTHER_COURSE)) {
                    //陪练课
                    OpenChatHelper.goChat(context, data.userId, data.name)
                } else {
                    //琴房课或者直播课
                    OpenChatHelper.goGroupChat(context, data.imGroupId, data.name)
                }
            }
        })

        mViewBinding.refreshLayout.setOnRefreshListener(OnRefreshListener {
            queryCurrentDataCourse()
        })
        mViewBinding.refreshLayout.isEnabled = false
    }

    override fun initData() {
        lazyLoad()
    }

    private fun lazyLoad() {
        val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR]
        val month = calendar[Calendar.MONTH] + 1
        day = calendar[Calendar.DAY_OF_MONTH]
        if ((mViewBinding.calendarView.curDay !== day || mViewBinding.calendarView.curMonth !== month || mViewBinding.calendarView.curYear !== year)) {
            mViewBinding.calendarView.updateCurrentDate()
            mViewBinding.calendarView.clearSingleSelect()
        }
        mViewBinding.calendarView.scrollToCalendar(year, month, day);
        setMontAndDay(year, month, day)
        currentSelectDate = TimeUtils.getNowDate()
        calendarDate = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM"))
    }

    private fun setMontAndDay(year: Int, month: Int, day: Int) {
        var span: String = if (month < 10) {
            year.toString() + "年0" + month + "月"
        } else {
            year.toString() + "年" + month + "月"
        }
        mViewBinding.tvCurrentDate.text = span
    }

    override fun onCalendarOutOfRange(calendar: com.haibin.calendarview.Calendar?) {
    }

    override fun onCalendarSelect(calendar: com.haibin.calendarview.Calendar?, isClick: Boolean) {
        val year = calendar!!.year
        val month = calendar!!.month
        val day = calendar!!.day
        currentSelectDate = TimeUtils.millis2Date(calendar.timeInMillis)
        calendarDate =
            TimeUtils.date2String(currentSelectDate, TimeUtils.getSafeDateFormat("yyyy-MM"))
        setMontAndDay(year, month, day)
        queryCurrentDataCourse()
    }

    override fun onResume() {
        super.onResume()
        queryCurrentDataCourse()
    }

    /**
     * 查询当前选择日期的课程
     */
    public fun queryCurrentDataCourse() {
        presenter.getCourseScheduleDateByMonth(calendarDate)
        presenter.getCourseSchedulesWithDate(currentSelectDate)
    }

    override fun onCalendarIntercept(calendar: com.haibin.calendarview.Calendar?): Boolean {
        return false;
    }

    override fun onCalendarInterceptClick(
        calendar: com.haibin.calendarview.Calendar?,
        isClick: Boolean
    ) {

    }

    override fun onMonthChange(year: Int, month: Int) {
        setMontAndDay(year, month, day)
        presenter?.let {
            presenter.getCourseScheduleDateByMonth(getMonth(year, month))
        }
    }

    private fun getMonth(year: Int, month: Int): String {
        var span: String = if (month < 10) {
            "$year-0$month"
        } else {
            "$year-$month";
        }
        return span;
    }

    override fun onViewChange(isMonthView: Boolean) {
        if (!isMonthView) {
            recyclerView.removeItemDecoration(calendarExpandDecoration)
            if (recyclerView.itemDecorationCount == 0 || recyclerView.getItemDecorationAt(0) !is CalendarShrinkDecoration) {
                Log.e("sdfsdgsdsdasdaf", "calendarShrinkDecoration: ")
                recyclerView.addItemDecoration(calendarShrinkDecoration, 0)
                mViewBinding.refreshLayout.isEnabled = false
            }
        } else {
            recyclerView.removeItemDecoration(calendarShrinkDecoration)
            if (recyclerView.itemDecorationCount == 0 || recyclerView.getItemDecorationAt(0) !is CalendarExpandDecoration) {
                Log.e("sdfsdgsdsdasdaf", "calendarExpandDecoration: ")
                recyclerView.addItemDecoration(calendarExpandDecoration, 0)
                mViewBinding.refreshLayout.isEnabled = true
            }
        }
    }

    override fun createPresenter(): CourseTablePresenter {
        return CourseTablePresenter()
    }

    /**
     * 根据月份查询当月有课的日期
     */
    override fun onGetCourseDateByMonthSuccess(datas: MutableList<String>?) {
        if (isDetached) {
            return;
        }
        mViewBinding.refreshLayout.finishRefresh()
        if (datas?.size != 0) {
            //更新日历表,显示有课字样
            mViewBinding.calendarView.clearSchemeDate()
            var maps = CourseHelper.filterDate(datas);
            if (maps != null && maps.isNotEmpty()) {
                mViewBinding.calendarView.addSchemeDate(maps)
            }
        } else {
            mViewBinding.calendarView.clearSchemeDate()
        }
    }

    override fun onGetCourseDateByMonthError() {
        mViewBinding.refreshLayout.finishRefresh()
    }

    /**
     * 查询当天的课程
     */
    override fun onGetCourseSchedulesWithDateSuccess(data: CourseTableDataBean) {
        if (isDetached) {
            return;
        }
        adapter?.data.clear()
        if (data?.studentList?.size != 0) {
            //更新日历表,显示有课字样
            adapter.data.addAll(data?.studentList);
            adapter?.notifyDataSetChanged()
        } else {
            //show空视图
            adapter?.notifyDataSetChanged()
//            showEmptyView()
        }
    }


    private fun showEmptyView() {
        if (!::emptyView.isInitialized) {
            emptyView = EmptyViewLayout(context)
        }
        emptyView.setContent(com.cooleshow.base.R.drawable.icon_empty_course, "暂无课程~")
        adapter.setEmptyView(emptyView)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_current_date -> {
                showTimeSelectView()
            }
        }
    }

    /**
     * 显示日期选择view
     */
    private fun showTimeSelectView() {
        //正确设置方式 原因：注意事项有说明
        if (!::pvTime.isInitialized) {
            pvTime = TimePickerBuilder(
                requireContext(),
                OnTimeSelectListener { date: Date?, v: View? ->  //选中事件回调
                    var year: Int = TimeUtils.getValueByCalendarField(date, Calendar.YEAR)
                    var month: Int = TimeUtils.getValueByCalendarField(date, Calendar.MONTH) + 1
                    var day: Int = TimeUtils.getValueByCalendarField(date, Calendar.DAY_OF_MONTH)
                    mViewBinding.calendarView.scrollToCalendar(year, month, day);
                }).setLayoutRes(com.cooleshow.base.R.layout.pickerview_default_layout,
                CustomListener { v -> //自定义布局中的控件初始化及事件处理
                    val tvSubmit =
                        v.findViewById<View>(com.cooleshow.base.R.id.tv_finish) as TextView
                    val ivCancel =
                        v.findViewById<View>(com.cooleshow.base.R.id.tv_cancel) as TextView
                    tvSubmit.setOnClickListener {
                        pvTime.returnData()
                        pvTime.dismiss()
                    }
                    ivCancel.setOnClickListener { pvTime.dismiss() }
                })
                .setLineSpacingMultiplier(2.5f)
                .setType(booleanArrayOf(true, true, false, false, false, false)) // 默认全部显示
                .isCyclic(true) //是否循环滚动
                .setOutSideCancelable(true) //点击屏幕，点在控件外部范围时，是否取消显示
                .setTextColorCenter(resources.getColor(com.cooleshow.base.R.color.color_1a1a1a)) //设置选中项的颜色
//            .setRangDate(null, endDate) //起始终止年月日设定
//            .setDate(endDate)
                .isDialog(false) //是否显示为对话框样式
                .setLabel("年", "月", "日", "", "", "")
                .build()
        }
        var calendar = Calendar.getInstance();
        calendar.time = currentSelectDate
        pvTime.setDate(calendar)
        if (!pvTime.isShowing) {
            pvTime.show()
        }

    }
}