package com.cooleshow.teacher.ui.main

import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.OnItemClickListener
import com.cooleshow.base.ui.fragment.BaseMVPFragment
import com.cooleshow.base.utils.SizeUtils
import com.cooleshow.base.utils.TimeUtils
import com.cooleshow.base.utils.ToastUtils
import com.cooleshow.teacher.CourseHelper
import com.cooleshow.teacher.R
import com.cooleshow.teacher.adapter.CourseTableListAdapter
import com.cooleshow.teacher.bean.CourseTableDataBean
import com.cooleshow.teacher.contract.CourseTableContract
import com.cooleshow.teacher.contract.HomeContract
import com.cooleshow.teacher.databinding.FragmentCourseTableLayoutBinding
import com.cooleshow.teacher.presenter.main.CourseTablePresenter
import com.cooleshow.teacher.widgets.CalendarExpandDecoration
import com.cooleshow.teacher.widgets.CalendarShrinkDecoration
import com.haibin.calendarview.CalendarView
import kotlinx.android.synthetic.main.fragment_course_table_layout.*
import org.w3c.dom.Text
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: View
    private lateinit var emptyText: TextView
    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);

        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) {
                                mViewBinding.calendarLayout.shrink()
                            } else {
                                mViewBinding.calendarLayout.expand()
                            }
                            return true
                        }
                    }
                }
                return super.onInterceptTouchEvent(rv, e)
            }
        })
        adapter.setOnItemClickListener(OnItemClickListener() { adapter, view, position ->
        })
    }

    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()
    }

    /**
     * 查询当前选择日期的课程
     */
    private 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)
    }

    override fun onViewChange(isMonthView: Boolean) {
        if (!isMonthView) {
            recyclerView.removeItemDecoration(calendarExpandDecoration)
            if (recyclerView.itemDecorationCount == 0 || recyclerView.getItemDecorationAt(0) !is CalendarShrinkDecoration) {
                recyclerView.addItemDecoration(calendarShrinkDecoration, 0)
            }
        } else {
            recyclerView.removeItemDecoration(calendarShrinkDecoration)
            if (recyclerView.itemDecorationCount == 0 || recyclerView.getItemDecorationAt(0) !is CalendarExpandDecoration) {
                recyclerView.addItemDecoration(calendarExpandDecoration, 0)
            }
        }
    }

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

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

    /**
     * 查询当天的课程
     */
    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 = LayoutInflater.from(requireContext())
                .inflate(com.cooleshow.base.R.layout.empty_layout, adapter?.emptyLayout, false)
            emptyText = emptyView.findViewById<TextView>(com.cooleshow.base.R.id.tv_empty_tip)
        }
        emptyText.text = "暂无数据"
        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, true, 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()
        }

    }
}