package com.miya.fastcashier.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miya.fastcashier.dao.DatabaseKeeper
import com.miya.fastcashier.utils.DateUtils
import com.miya.fastcashier.utils.MiYaPayPlantformPayWayEnum
import com.miya.fastcashier.utils.isEmpty
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception
import com.miya.fastcashier.beans.ViewPayOrderData as ViewPayOrderData1

class SearchOrderViewModel : ViewModel() {

    val payDataLiveData: MutableLiveData<Result<List<ViewPayOrderData1>>> = MutableLiveData()

    /**
     * 获取所有订单,分页处理
     */
    fun getPayData(payType: MiYaPayPlantformPayWayEnum.MiyaPayType, currentSize: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val list =
                    DatabaseKeeper.payDatabase.payDataDao()
                        .queryWithType(payType = payType.code, currentSize)
                payDataLiveData.postValue(Result.success(list))
            } catch (e: Exception) {
                e.printStackTrace()
                payDataLiveData.postValue(Result.failure(e))
            }

        }
    }

    /**
     * 根据时间、用户获取订单，不分页
     */
    fun getPayDataByTimeAndUser(
        payType: MiYaPayPlantformPayWayEnum.MiyaPayType,
        userName: String,
        limitTime: Long
    ) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val list = DatabaseKeeper.payDatabase.payDataDao()
                    .queryAllWithTypeAndName(payType = payType.code, userName)

                if (limitTime == 0L) {
                    payDataLiveData.postValue(Result.success(list))
                    return@launch
                }

                val destList: MutableList<ViewPayOrderData1> = arrayListOf()
                if (!isEmpty(list)) {
                    for (order in list) {
                        val tradeDate: String = order.chanelOrderTradeTime
                        if (!TextUtils.isEmpty(tradeDate) &&
                            DateUtils.stringToLong(
                                tradeDate,
                                DateUtils.DF_YYYY_MM_DDHHMMSS
                            ) > limitTime
                        ) {
                            destList.add(order)
                        }
                    }
                }

                payDataLiveData.postValue(Result.success(destList))
            } catch (e: Exception) {
                e.printStackTrace()
                payDataLiveData.postValue(Result.failure(e))
            }
        }
    }
}