package com.dlc.exam.ui.common

import android.app.Dialog
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.DatePicker
import android.widget.Toast
import com.dlc.exam.databinding.DialogDateChooseBinding
import com.rc.core.util.DateUtils
import java.util.*

/**
 * 日期选择Dialog
 *
 * @author ReiChin_
 */
class DateChooseDialog constructor(
    context: Context,
    private val startDate: String?, // 默认开始日期
    private val endDate: String?, // 默认结束日期
    private val dialogListener: ((startDate: String, endDate: String) -> Boolean)? = null
) :
    Dialog(context, 0) {

    private val viewBinding by lazy {
        DialogDateChooseBinding.inflate(LayoutInflater.from(getContext()))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initWindowConfig()
        initViews()
    }

    private fun initWindowConfig() {
        window?.apply {
            val dm = Resources.getSystem().displayMetrics
            attributes.width = (dm.widthPixels * 0.7f).toInt()
            attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }

    private fun initViews() {
        initDatePicker(viewBinding.startDate, startDate)
        initDatePicker(viewBinding.endDate, endDate)

        // 取消
        viewBinding.btnNeg.setOnClickListener { dismiss() }
        // 确定
        viewBinding.btnPos.setOnClickListener {
            val startCalendar = getSelectedCalendar(viewBinding.startDate)
            val endCalendar = getSelectedCalendar(viewBinding.endDate)
            if (DateUtils.compareToYMD(startCalendar, endCalendar) > 0) {
                // 开始日期 > 结束日期
                Toast.makeText(context, "开始日期不能大于结束日期", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val result = dialogListener?.invoke(
                DateUtils.formatDate(startCalendar),
                DateUtils.formatDate(endCalendar)
            )
                ?: true
            if (result) dismiss()
        }
    }

    private fun getSelectedCalendar(datePicker: DatePicker): Calendar {
        val calendar = Calendar.getInstance()
        calendar.set(datePicker.year, datePicker.month, datePicker.dayOfMonth)
        return calendar
    }

    private fun initDatePicker(datePicker: DatePicker, dataStr: String?) {
        val calendar = DateUtils.parseDate(dataStr)
        datePicker.init(
            calendar[Calendar.YEAR],
            calendar[Calendar.MONTH],
            calendar[Calendar.DAY_OF_MONTH],
            null
        )
    }
}