package com.sixin.module_p.ui.gnc.cunfang.dialog

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseDialogModel
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.sixin.module_p.R
import com.sixin.module_p.databinding.DialogPdaCunfangFilterBinding
import dev.DevUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import java.util.Calendar

class PdaCunFangFilterDialogModel(
    private val callBack: () -> Unit
) : BaseDialogModel<DialogPdaCunfangFilterBinding>(DIALOG_TYPE_DRAWER) {

    val date = MutableLiveData(DateUtils.getCurrentTime().formatDate())

    val flightNo = MutableLiveData("")

    // 存放区域
    val area = MutableLiveData("")

    // 复磅状态
    val status = MutableLiveData("")

    val areaList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getAreaList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }
    val statusList = MutableLiveData<List<KeyValue>>(
        DictUtils.reWeightStatusList
    )

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    override fun layoutId(): Int {
        return R.layout.dialog_pda_cunfang_filter
    }

    override fun onDialogCreated(context: Context) {
        binding.model = this
    }

    fun onAreaSelected(position: Int) {
        area.value = areaList.value?.get(position)?.value
    }

    fun onStatusSelected(position: Int) {
        status.value = statusList.value?.get(position)?.value
    }

    override fun onBuild(builder: XPopup.Builder) {
        builder.popupPosition(PopupPosition.Right)
    }

    fun onDateClick() {
        Common.onYearMonthDay(DevUtils.getTopActivity(), date.value) { year, month, day ->
            val calendar = Calendar.getInstance()
            calendar.set(year, month - 1, day)
            date.value = DateUtils.formatDate(calendar.time, "yyyy-MM-dd")
        }
    }

    fun onResetClick() {
        date.value = DateUtils.getCurrentTime().formatDate()
        flightNo.value = ""
        if (binding.spinnerArea.adapter.count > 0) {
            binding.spinnerArea.setSelection(0)
        }
        if (binding.spinnerStatus.adapter.count > 0) {
            binding.spinnerStatus.setSelection(0)
        }

        callBack.invoke()
        dismiss()
    }

    fun onConfirmClick() {
        callBack.invoke()
        dismiss()
    }
}