package com.dlc.chemical.ui.dialog

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 com.dlc.chemical.R
import com.dlc.chemical.databinding.DialogDatePickerBinding
import com.rc.core.util.DateUtils
import java.util.*

/**
 * info
 *
 * @author ReiChin_
 */
class DatePickerDialog(
    context: Context,
    private val titleText: String = "选择截止时间",
    private val defDate: String?, // 默认日期
    private val dialogListener: ((pickerDate: Calendar) -> Boolean)? = null
) :
    Dialog(context, R.style.AlertDialogStyle) {

    private val viewBinding: DialogDatePickerBinding by lazy {
        DialogDatePickerBinding.inflate(LayoutInflater.from(context))
    }

    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.32f).toInt()
            attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }

    private fun initViews() {
        viewBinding.title.text = titleText
        initDatePicker(viewBinding.datePicker, defDate)

        // 取消
        viewBinding.cancel.setOnClickListener { dismiss() }
        // 确认
        viewBinding.confirm.setOnClickListener {
            val datePickerCalendar = getSelectedCalendar(viewBinding.datePicker)
            if (null == dialogListener
                || dialogListener.invoke(datePickerCalendar)
            ) {
                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
        )
    }

}