package com.xty.common

import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.core.content.ContextCompat
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.tamsiree.rxkit.RxTimeTool
import com.xty.common.weight.InputView
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*

class TimeSelect(var context: Context, var select: (String) -> Unit) {
    constructor(context: Context, isDialog: Boolean, select: (String) -> Unit) : this(
        context,
        select
    ) {
        showDialog = isDialog
    }

    var showDialog = false
    var format = "yyyy-MM-dd"  //需要在外部输出的时间格式
    var selectedDate = Calendar.getInstance()
    var startDate = Calendar.getInstance()
    var endDate = Calendar.getInstance()
    private var timeTv: TextView? = null
    private var otherView: View? = null
    var chooseMany = false
    var selectTime = ""
    var firstSelectedDate: Calendar? = null  // 添加一个伴生对象的属性用于保存第一个选择的时间

    //是分秒是否显示
    var showYear = true
    var showMonth = true
    var showDay = true
    var showHour = false
    var showMin = false
    var showSec = false
    var setStartTime: Boolean = false

    var isLanu:Boolean = false

    init {
        val instance = Calendar.getInstance()
        startDate.set(
            instance.get(Calendar.YEAR),
            instance.get(Calendar.MONTH),
            instance.get(Calendar.DATE)
        )
        endDate.set(
            instance.get(Calendar.YEAR),
            instance.get(Calendar.MONTH),
            instance.get(Calendar.DATE)
        )
    }

    private fun createTimePickerView(): TimePickerView {
        return TimePickerBuilder(context, object : OnTimeSelectListener {
            // ... 时间选择器监听器的实现 ...
            override fun onTimeSelect(date: Date?, v: View?) {
                // 在这里处理时间选择的逻辑
                val date2String = RxTimeTool.date2String(date, SimpleDateFormat(format))
                if (chooseMany) {
                    var str = StringBuilder(timeTv?.text)
                    if (!timeTv?.text.isNullOrEmpty()) {
                        str.append(",$date2String")
                    } else {
                        str.append(date2String)
                    }
                    selectTime = str.toString()
                    timeTv?.text = str
                } else {
                    selectTime = date2String
                    timeTv?.text = date2String
                }
                select.invoke(date2String)
            }

        })
            // ... 设置其他属性 ...
            .build()
    }


    private lateinit var pvTime1: TimePickerView
    fun createPvTime(context: Context, endDate: Calendar, select: () -> Unit) {
        pvTime1 = TimePickerBuilder(context, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                // 在这里处理时间选择的逻辑
                val date2String = RxTimeTool.date2String(date, SimpleDateFormat(format))
                if (chooseMany) {
                    var str = StringBuilder(timeTv?.text)
                    if (!timeTv?.text.isNullOrEmpty()) {
                        str.append(",$date2String")
                    } else {
                        str.append(date2String)
                    }
                    selectTime = str.toString()
                    timeTv?.text = str
                } else {
                    selectTime = date2String
                    timeTv?.text = date2String
                }
                select.invoke()
            }
        })
            // 设置其他属性
            .setType(
                booleanArrayOf(
                    showYear,
                    showMonth,
                    showDay,
                    showHour,
                    showMin,
                    showSec
                )
            )// 显示需要的时间
            .setCancelText(context.getString(R.string.cancel))//取消按钮文字
            .setSubmitText(context.getString(R.string.confirm))//确认按钮文字
            //.setContentSize(18)//滚轮文字大小
            .setTitleSize(18)//标题文字大小
            .setTitleText("")//标题文字
            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false)//是否循环滚动
            .setTitleColor(ContextCompat.getColor(context, R.color.col_455)!!)//标题文字颜色
            .setSubmitColor(ContextCompat.getColor(context, R.color.black))!!//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(context, R.color.black)!!)//取消按钮文字颜色
            .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
            .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
            .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
            .setRangDate(null, endDate)//起始终止年月日设定
            .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .isDialog(false)//是否显示为对话框样式
            .build()
    }

    fun setHide1(): TimePickerView {
        return pvTime1
    }

    fun setHide(): TimePickerView {
        return pvTime
    }

    private val pvTime by lazy {
        TimePickerBuilder(context, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                val date2String = RxTimeTool.date2String(date, SimpleDateFormat(format))
                if (chooseMany) {
                    var str = StringBuilder(timeTv?.text)
                    if (!timeTv?.text.isNullOrEmpty()) {
                        str.append(",$date2String")
                    } else {
                        str.append(date2String)
                    }
                    selectTime = str.toString()
                    timeTv?.text = str
                } else {
                    selectTime = date2String
                    timeTv?.text = date2String
                }
                if (otherView != null && otherView is InputView) {
                    (otherView as InputView).setValues(date2String)
                }
                select.invoke(date2String)
            }
        })
            .setType(
                booleanArrayOf(
                    showYear,
                    showMonth,
                    showDay,
                    showHour,
                    showMin,
                    showSec
                )
            )// 显示需要的时间
            .setCancelText(context.getString(R.string.cancel))//取消按钮文字
            .setSubmitText(context.getString(R.string.confirm))//确认按钮文字
            //.setContentSize(18)//滚轮文字大小
            .setTitleSize(18)//标题文字大小
            .setTitleText("")//标题文字
            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false)//是否循环滚动
            .setTitleColor(ContextCompat.getColor(context, R.color.col_455)!!)//标题文字颜色
            .setSubmitColor(ContextCompat.getColor(context, R.color.black))!!//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(context, R.color.black)!!)//取消按钮文字颜色
            .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
            .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
            .setRangDate(if (setStartTime) startDate else null, endDate)//起始终止年月日设定
            .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
            .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .isDialog(showDialog)//是否显示为对话框样式
            .build()
    }


    private var pvLunarTime : TimePickerView?= null

    // 设置结束日期

    fun selectManyTime2(timeTv: View, format: String = "yyyy-MM-dd") {
        this.chooseMany = true
        selectTime(timeTv, format)
    }

    fun selectManyTime(timeTv: View, format: String = "yyyy-MM-dd") {
        this.chooseMany = true
        selectTime(timeTv, format)
    }

    fun selectTime2(timeTv: View, format: String = "yyyy-MM-dd", selectedDate: Calendar? = null) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = selectedDate  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate.add(Calendar.DAY_OF_MONTH, -1)
            val s: String = SimpleDateFormat("yyyy-MM-dd").format(endDate.time)
            LogUtils.d("------endDate:$s")
        }
        this.format = format
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = true
        pvTime1.show()
    }

    fun selectTimeWithYearMonth2(
        timeTv: View,
        format: String = "yyyy-MM-dd",
        selectedDate: Calendar? = null
    ) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = firstSelectedDate?.clone() as Calendar?  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate?.add(Calendar.DAY_OF_MONTH, -1)
        }

        this.format = format
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = false
        pvTime1.show()
    }

    fun selectTimeWithYear2(
        timeTv: View,
        format: String = "yyyy-MM-dd",
        selectedDate: Calendar? = null
    ) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = firstSelectedDate?.clone() as Calendar?  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate?.add(Calendar.DAY_OF_YEAR, -1)
        }

        this.format = format
        this.timeTv = timeTv as TextView
        showMonth = false
        showYear = true
        showDay = false
        pvTime1.show()
    }

    fun selectTime(timeTv: View) {
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = true
        pvTime.show()
    }

    fun selectTimeTwo(timeTv: View,timeType:View) {
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = true

      pvLunarTime =  TimePickerBuilder(context, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                val date2String = RxTimeTool.date2String(date, SimpleDateFormat(format))
                if (chooseMany) {
                    var str = StringBuilder(timeTv?.text)
                    if (!timeTv?.text.isNullOrEmpty()) {
                        str.append(",$date2String")
                    } else {
                        str.append(date2String)
                    }
                    selectTime = str.toString()
                    timeTv?.text = str
                } else {
                    selectTime = date2String
                    timeTv?.text = date2String
                }
                if (otherView != null && otherView is InputView) {
                    (otherView as InputView).setValues(date2String)
                }

                if(isLanu){
                    (timeType as TextView).text = "公历"

                }else{
                    (timeType as TextView).text = "农历"
                }
                select.invoke(date2String)
            }
        })
            .setLayoutRes(R.layout.layout_customer_date_picker,object : CustomListener{
                override fun customLayout(v: View?) {

                    var tvSubmit =v!!.findViewById<TextView>(R.id.tv_confirm)

                    var tvCancel = v!!.findViewById<TextView>(R.id.tv_cancel)

                    var checkLuna = v!!.findViewById<CheckBox>(R.id.check_brithday)

                    tvSubmit.setOnClickListener {
                       pvLunarTime?.returnData()
                        pvLunarTime?.dismiss()
                    }

                    tvCancel.setOnClickListener {
                       pvLunarTime?.dismiss()
                    }

                    checkLuna.setOnCheckedChangeListener { compoundButton, b ->
                        isLanu = b
                        /*if(b){
                            (timeType as TextView).text = "农历"
                        }else{
                            (timeType as TextView).text = "公历"
                        }*/
                    }
                }
            })

            .setType(
                booleanArrayOf(
                    showYear,
                    showMonth,
                    showDay,
                    showHour,
                    showMin,
                    showSec
                )
            )// 显示需要的时间
            .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false)//是否循环滚动
            .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
            .setLineSpacingMultiplier(2.5f)
            .setTextColorCenter(ContextCompat.getColor(context, R.color.col_313))
            .setTextColorOut(ContextCompat.getColor(context, R.color.col_6B6))
            .setDividerColor(ContextCompat.getColor(context, R.color.transparent))
            .setItemVisibleCount(3)
            .setRangDate(if (setStartTime) startDate else null, endDate)//起始终止年月日设定
            .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
            .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .isDialog(showDialog)//是否显示为对话框样式
            .build()

        pvLunarTime?.show()
    }
    fun selectTime(timeTv: View, format: String = "yyyy-MM-dd", selectedDate: Calendar? = null) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = selectedDate  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate.add(Calendar.DAY_OF_MONTH, -1)
            val s: String = SimpleDateFormat("yyyy-MM-dd").format(endDate.time)
            LogUtils.d("------endDate:$s")
        }
        this.format = format
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = true
        pvTime.show()
    }

    fun selectTimeWithYearMonth(
        timeTv: View,
        format: String = "yyyy-MM-dd",
        selectedDate: Calendar? = null
    ) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = firstSelectedDate?.clone() as Calendar?  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate?.add(Calendar.DAY_OF_MONTH, -1)
        }

        this.format = format
        this.timeTv = timeTv as TextView
        showYear = true
        showMonth = true
        showDay = false
        pvTime.show()
    }

    fun selectTimeWithYear(
        timeTv: View,
        format: String = "yyyy-MM-dd",
        selectedDate: Calendar? = null
    ) {
        this.selectedDate =
            selectedDate ?: Calendar.getInstance()  // 如果 selectedDate 为空，则使用当前日期作为默认时间
        if (selectedDate != null) {
            firstSelectedDate = selectedDate  // 将传入的 selectedDate 赋值给 firstSelectedDate
            endDate = firstSelectedDate?.clone() as Calendar?  // 设置最大可选日期为第一个选择器选择的日期减去一天
            endDate?.add(Calendar.DAY_OF_YEAR, -1)
        }

        this.format = format
        this.timeTv = timeTv as TextView
        showMonth = false
        showYear = true
        showDay = false
        pvTime.show()
    }

    fun selectTimeNoneView(otherView: View, format: String = "yyyy-MM-dd HH:mm:ss") {
        this.format = format
        this.otherView = otherView
        if (format == "yyyy-MM-dd HH:mm:ss") {
            this.showHour = true
            this.showMin = true
            this.showSec = true
        }
        pvTime.show()
    }

    fun selectDefault(
        otherView: View?,
        tv: TextView? = null,
        format: String = "yyyy-MM-dd HH:mm:ss"
    ) {
        this.format = format
        this.otherView = otherView
        this.timeTv = tv
        pvTime.show()
    }
}