package com.miya.fastcashier.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NumberUtils
import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo
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.sdy.miya.moblie.component.pay.core.error.ParamInvalidException
import com.sdy.miya.moblie.component.pay.platform.bean.MiyaOrderRefundResponse
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import kotlinx.coroutines.*
import java.util.*
import kotlin.collections.HashMap


class PayViewModel : ViewModel() {

    lateinit var payResultJob: Job

    val refundLiveData: MutableLiveData<Result<PayServiceResponse>> = MutableLiveData()
    val payServiceResponseLiveData: MutableLiveData<Result<PayServiceResponse>> = MutableLiveData()
    val payResultLiveData: MutableLiveData<Result<PayServiceResponse>> = MutableLiveData()



    fun refund(payServiceResponse: PayServiceResponse) {
        viewModelScope.launch(Dispatchers.IO) {
            //退款
            var refundPayServiceResponse: PayServiceResponse? = null
            try {
                val refundParams = HashMap<String, String>()
                refundParams["oriOrderNo"] = payServiceResponse.shopTradeNo;
                val refundOrderNo = AccountService.getAccountInfo()?.shopInfo?.saasid  + System.currentTimeMillis()
                refundParams["refundOrderNo"] = refundOrderNo;
                refundParams["refundPrice"] = payServiceResponse.tradPrice;
                refundPayServiceResponse = PayRepository.refundByOrderNo(refundParams)
                refundLiveData.postValue(Result.success(refundPayServiceResponse))
            } catch (e: Exception) {
                refundLiveData.postValue(Result.failure(e))
            }

            //退款打印
            try {
                AccountService.getAccountInfo()
                    ?.let { refundPayServiceResponse?.let { it1 ->
                        PrintService.refundPrint(it,
                            it1
                        )
                    } }
            }catch (e: Exception){
                refundLiveData.postValue(Result.failure(e))
            }

        }
    }


    /**
     * payType 只支持微信或者支付宝
     * 2是微信 1是支付宝
     * price 传进来要是分，整数
     */
    fun generatePayCode(price: String, payType: String) {
        if (TextUtils.isEmpty(price)) {
            payServiceResponseLiveData.value = Result.failure(ParamInvalidException("请输入金额！"))
            return
        }

        val priceFen: String
        try {
            priceFen = price.toDouble().times(100).toInt().toString()
        } catch (e: java.lang.Exception) {
            payServiceResponseLiveData.value = Result.failure(ParamInvalidException("金额有误！"))
            return
        }

        val sassid = AccountService.getAccountInfo()?.shopInfo?.saasid
//        val storeId = AccountService.getAccountInfo()?.shopInfo?.storeId
        val orderNo = sassid  + System.currentTimeMillis()

        viewModelScope.launch(Dispatchers.IO) {
            try {
                val payServiceResponse = PayRepository.generatePayCode(orderNo, priceFen, payType)
                LogUtils.e("生成付款码：${JSON.toJSONString(payServiceResponse)}")
                payServiceResponseLiveData.postValue(Result.success(payServiceResponse))
            } catch (e: Exception) {
                payServiceResponseLiveData.postValue(Result.failure(e))
            }
        }
    }


    /**
     * 订单查询
     */
    fun payResultQuery(payServiceResponse: PayServiceResponse) {
        payResultJob = viewModelScope.launch(Dispatchers.IO) {
            while (isActive) {
                try {
                    LogUtils.e("支付查询订单号：${payServiceResponse.shopTradeNo}")
                    val payServiceResponseResult = PayRepository.payResultQuery(payServiceResponse.shopTradeNo)
                    LogUtils.e("支付查询结果：${JSON.toJSONString(payServiceResponseResult)}")
                    payResultLiveData.postValue(Result.success(payServiceResponseResult))
                    break
                } catch (e: Exception) {
                    e.printStackTrace()
                    payResultLiveData.postValue(Result.failure(e))
                    Thread.sleep(5000)
                }
            }
        }
    }


    /**
     * 订单查询，退款查询
     */
    fun payResultQuery(orderNo: String) {
        viewModelScope.launch(Dispatchers.IO){
            try {
                LogUtils.e("退款支付查询订单号：${orderNo}")
                val payServiceResponseResult = PayRepository.payResultQuery(orderNo)
                LogUtils.e("退款支付查询结果：${JSON.toJSONString(payServiceResponseResult)}")
                payResultLiveData.postValue(Result.success(payServiceResponseResult))
            } catch (e: Exception) {
                payResultLiveData.postValue(Result.failure(e))
            }
        }
    }

}