package com.abbidot.tracker.dialog

import android.content.Context
import android.view.View
import android.widget.NumberPicker
import android.widget.NumberPicker.OnValueChangeListener
import android.widget.TextView
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.databinding.DialogCalenderAndTimeLayoutBinding
import com.abbidot.tracker.util.NumberPickerValueFill0Format
import com.abbidot.tracker.util.ViewUtil
import com.haibin.calendarview.CalendarView
import com.hjq.toast.Toaster
import java.util.Calendar


/**
 *Created  by .yzq on 2022/1/7/007.
 * @link
 * @description:显示日历弹窗
 *  @param canSelectFutureDate 平时正常日期，true不能选择未来时间
 *  @param minLastDayRange 最小天数能选最近多少天，0表示没有限制
 */
class ShowCalenderAndTimeDialog(
    context: Context,
    showCalenderTextView: TextView,
    okListener: OnDialogSelectListener? = null,
    format: String = Utils.DATE_FORMAT_PATTERN_EN1,
    canSelectFutureDate: Boolean = false,
    calenderShowTimestamp: Long = 0,
    minYear: Int = 2023,
    minLastDayRange: Int = 0
) : BaseDialog<DialogCalenderAndTimeLayoutBinding>(
    DialogCalenderAndTimeLayoutBinding::inflate, context
), OnValueChangeListener {

    private val mShowCalenderTextView = showCalenderTextView
    private var mShowYearMonthDialog: ShowYearMonthDialog? = null
    private lateinit var mMonths: Array<String>
    private var mShowYear = 0
    private var mShowMonth = 0
    private val mCanSelectFutureDate = canSelectFutureDate
    private val mDateFormat = format
    private val mOkListener = okListener

    private val mMinYear = minYear
    private var mCalenderShowTimestamp = calenderShowTimestamp
    private val mMinLastDayRange = minLastDayRange

    override fun initView() {
        mMonths = context.resources.getStringArray(R.array.array_month)

        mViewBinding.apply {
            llDialogCalenderLayout.cvShowSelectCalender.let {
                mShowYear = it.curYear
                mShowMonth = it.curMonth
                if (!mCanSelectFutureDate) {
                    val calendar = Calendar.getInstance()
                    val cYear = calendar.get(Calendar.YEAR)
                    val month = calendar.get(Calendar.MONTH) + 1
                    val day = calendar.get(Calendar.DAY_OF_MONTH)
                    if (mMinLastDayRange > 0) {
                        val minTimestamp = Utils.getBeforeHowTimestamp(
                            calendar.timeInMillis, mMinLastDayRange.toLong()
                        )
                        val minDate =
                            Utils.formatTime(minTimestamp, Utils.DATE_FORMAT_PATTERN_CN).split("-")
                        it.setRange(
                            minDate[0].toInt(),
                            minDate[1].toInt(),
                            minDate[2].toInt(),
                            cYear,
                            month,
                            day
                        )
                    } else {
                        it.setRange(mMinYear, 1, 1, cYear, month, day)
                    }
                }
                updateMonthYear()

                it.setOnMonthChangeListener { year, month ->
                    mShowMonth = month
                    mShowYear = year
                    updateMonthYear()
                }
                it.setOnCalendarSelectListener(object : CalendarView.OnCalendarSelectListener {
                    override fun onCalendarOutOfRange(calendar: com.haibin.calendarview.Calendar?) {
                        Toaster.show(R.string.txt_time_out_of_range)
                    }

                    override fun onCalendarSelect(
                        calendar: com.haibin.calendarview.Calendar, isClick: Boolean
                    ) {
                    }
                })
            }

            npDialogCalenderHour.let {
                ViewUtil.instance.setNumberPickerAttributes(
                    context,
                    it,
                    0,
                    23,
                    5,
                    16,
                    NumberPickerValueFill0Format(),
                    this@ShowCalenderAndTimeDialog
                )
            }
            npDialogCalenderMin.let {
                ViewUtil.instance.setNumberPickerAttributes(
                    context,
                    it,
                    0,
                    59,
                    5,
                    16,
                    NumberPickerValueFill0Format(),
                    this@ShowCalenderAndTimeDialog
                )
            }


            setOnClickListenerViews(
                llDialogCalenderLayout.ivSelectCalendarMonthLeft,
                llDialogCalenderLayout.ivSelectCalendarMonthRight,
                btnSelectCalenderHourMinCancel,
                btnSelectCalenderHourMinOk,
                llDialogCalenderLayout.tvSelectCalendarYearMonth
            )
        }
    }

    override fun onStart() {
        super.onStart()
        //根据传入的时间戳进行还原显示
        setSelectDate(mCalenderShowTimestamp)
    }

    /**
     * 根据传入的时间戳进行还原显示
     * @param showTimestamp 13位时间戳
     */
    fun setSelectDate(showTimestamp: Long) {
        if (showTimestamp > 0) {
            mViewBinding.apply {
                val calendar = Calendar.getInstance().apply {
                    timeInMillis = showTimestamp
                }
                llDialogCalenderLayout.cvShowSelectCalender.scrollToCalendar(
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH) + 1,
                    calendar.get(Calendar.DAY_OF_MONTH)
                )
                npDialogCalenderHour.value = calendar.get(Calendar.HOUR_OF_DAY)
                npDialogCalenderMin.value = calendar.get(Calendar.MINUTE)
            }
        }
    }


    private fun updateMonthYear() {
        val curMonthYear = "${mMonths[mShowMonth - 1]} $mShowYear"
        mViewBinding.llDialogCalenderLayout.tvSelectCalendarYearMonth.text = curMonthYear
    }

    override fun onClick(v: View) {
        mViewBinding.apply {
            when (v) {
                llDialogCalenderLayout.tvSelectCalendarYearMonth -> {
                    if (null == mShowYearMonthDialog) {
                        mShowYearMonthDialog = ShowYearMonthDialog(
                            context, llDialogCalenderLayout.cvShowSelectCalender
                        )
                    }
                    mShowYearMonthDialog?.show()
                }

                llDialogCalenderLayout.ivSelectCalendarMonthRight -> {
                    llDialogCalenderLayout.cvShowSelectCalender.scrollToNext(true)
                }

                llDialogCalenderLayout.ivSelectCalendarMonthLeft -> {
                    llDialogCalenderLayout.cvShowSelectCalender.scrollToPre(true)
                }

                btnSelectCalenderHourMinCancel -> dismiss()
                btnSelectCalenderHourMinOk -> {
                    val calendar = llDialogCalenderLayout.cvShowSelectCalender.selectedCalendar
                    val selectMonthYear = "${calendar.year}-${calendar.month}-${calendar.day} ${
                        Utils.fill2Digits(npDialogCalenderHour.value)
                    }:${Utils.fill2Digits(npDialogCalenderMin.value)}:00"
                    val timesTamp = Utils.stringToTimestamp(selectMonthYear)
                    val nowTimestamp = System.currentTimeMillis()

                    if (timesTamp > nowTimestamp) {
                        mCalenderShowTimestamp = nowTimestamp
                        mShowCalenderTextView.text = Utils.formatTime(nowTimestamp, mDateFormat)
                        mOkListener?.onSelectClick(this@ShowCalenderAndTimeDialog, nowTimestamp)
                    } else {
                        mCalenderShowTimestamp = timesTamp
                        mShowCalenderTextView.text = Utils.stringToDate(
                            selectMonthYear, Utils.DATE_FORMAT_PATTERN_CN2, mDateFormat
                        )
                        mOkListener?.onSelectClick(this@ShowCalenderAndTimeDialog, timesTamp)
                    }
                    dismiss()
                }
            }
        }
    }

    override fun onValueChange(picker: NumberPicker, oldVal: Int, newVal: Int) {
    }


    //利用反射修改线的颜色，目前没用
//    private fun setNumberPickerDividerColor(context: Context, numberPicker: NumberPicker) {
//        val pickerFields: Array<Field> = NumberPicker::class.java.declaredFields
//        for (pf in pickerFields) {
//            if (pf.name.equals("mSelectionDivider")) {
//                pf.isAccessible = true
//                try {
//                    //设置分割线的颜色值
//                    pf.set(
//                        numberPicker, ColorDrawable(
//                            ContextCompat.getColor(context, R.color.red)
//                        )
//                    )
//                } catch (e: IllegalArgumentException) {
//                    e.printStackTrace()
//                } catch (e: Resources.NotFoundException) {
//                    e.printStackTrace()
//                } catch (e: IllegalAccessException) {
//                    e.printStackTrace()
//                }
//                break
//            }
//        }
//    }
}