import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.text.format.DateFormat
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment
import java.util.Calendar

class TimePickerFragment(private val onTimeSelected: (hour: Int, minute: Int) -> Unit) :
    DialogFragment(), TimePickerDialog.OnTimeSetListener {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // 使用当前时间作为默认值
        val c = Calendar.getInstance()
        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        // 创建并返回 TimePickerDialog 实例
        // activity 参数需要可空性处理，this是OnTimeSetListener，最后一个是是否24小时制
        return TimePickerDialog(
            requireActivity(),
            this,
            hour,
            minute,
            DateFormat.is24HourFormat(activity)
        )
    }

    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
        // 当用户设置时间时，通过回调将结果传回
        onTimeSelected(hourOfDay, minute)
    }
}