package com.miya.fastcashier.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.ViewOrderStatisticsInfo
import com.miya.fastcashier.repository.PayRepository
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.service.LoginService
import com.miya.fastcashier.service.PrintService
import com.miya.fastcashier.utils.DateUtils
import com.sdy.miya.moblie.component.pay.platform.bean.MiyaOrderRefundResponse
import kotlinx.coroutines.*
import java.lang.Exception
import java.lang.RuntimeException
import java.util.*
import kotlin.collections.HashMap


class MainViewModel : ViewModel() {

    val refundLiveData: MutableLiveData<Result<PayRepository>> = MutableLiveData()

    val statisticsLiveData: MutableLiveData<Result<Long>> = MutableLiveData()
    val balanceLiveData: MutableLiveData<Result<Long>> = MutableLiveData()

    /**
     * oriOrderNo 原订单号
     * refundOrderNo 退款订单号
     * refundPrice 退款金额
     */
    fun refund(oriOrderNo: String, refundOrderNo: String, refundPrice: String) = runBlocking {

        val refundParams = HashMap<String, String>()
        refundParams["oriOrderNo"] = oriOrderNo
        refundParams["refundOrderNo"] = refundOrderNo
        refundParams["refundPrice"] = refundPrice

        val refundResult = async(Dispatchers.IO) {
            PayRepository.refundByOrderNo(refundParams)
        }

        val printResult = async(Dispatchers.IO) {
            AccountService.getAccountInfo()
                ?.let { PrintService.refundPrint(it, refundResult.await()) }
        }

        printResult.await()

//        refundLiveData.value = Result.success()

    }

    /**
     * 订单统计
     */
    fun orderStatistics(beginDate: Date, endDate: Date, isBalance: Boolean) {
        val accountInfo = AccountService.getAccountInfo()
        val liveData: MutableLiveData<Result<Long>> =
            if (isBalance) balanceLiveData else statisticsLiveData
        if (accountInfo == null) {
            liveData.value = Result.failure(RuntimeException("账户数据为空"))
            return
        }
        val accountInfoFinal = accountInfo!!

        viewModelScope.launch(Dispatchers.IO) {
            try {
                val response = PayRepository.requestOrderQueryByTime(beginDate, endDate)
                val info = ViewOrderStatisticsInfo.transfer(
                    response,
                    DateUtils.format18(beginDate),
                    DateUtils.format18(endDate)
                )
                PrintService.printStatisticInfo(info, accountInfoFinal,isBalance)
                liveData.postValue(Result.success(endDate.time))
            } catch (e: Exception) {
                e.printStackTrace()
                liveData.postValue(Result.failure(e))
            }
        }
    }

}