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.elvishew.xlog.XLog
import com.miya.fastcashier.beans.ViewPayOrderData
import com.miya.fastcashier.repository.PayRepository
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.service.PrintService
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch


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) {
        XLog.d("开始退款:${JSON.toJSONString(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)
                XLog.d("退款成功:${JSON.toJSONString(refundPayServiceResponse)}")
                //保存到数据库
                ViewPayOrderData.insert(refundPayServiceResponse)
                refundLiveData.postValue(Result.success(refundPayServiceResponse))

            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("退款异常:${e.message}")
                refundLiveData.postValue(Result.failure(e))
            }

            //退款打印
            try {
                XLog.d("开始退款打印")
                AccountService.getAccountInfo()
                    ?.let {
                        refundPayServiceResponse?.let { it1 ->
                            PrintService.refundPrint(
                                it,
                                it1
                            )
                        }
                    }
            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("退款打印异常${e.message}")
                refundLiveData.postValue(Result.failure(e))
            }

        }
    }

    /**
     * 退款固定数额
     */
    fun refund(payServiceResponse: PayServiceResponse, refundPrice: String) {
        XLog.d("开始退款:${JSON.toJSONString(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"] = refundPrice
                refundPayServiceResponse = PayRepository.refundByOrderNo(refundParams)
                XLog.d("退款成功:${JSON.toJSONString(refundPayServiceResponse)}")
                //保存到数据库
                ViewPayOrderData.insert(refundPayServiceResponse)
                refundLiveData.postValue(Result.success(refundPayServiceResponse))

            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("退款异常:${e.message}")
                refundLiveData.postValue(Result.failure(e))
            }

            //退款打印
            try {
                XLog.d("开始退款打印")
                AccountService.getAccountInfo()
                    ?.let {
                        refundPayServiceResponse?.let { it1 ->
                            PrintService.refundPrint(
                                it,
                                it1
                            )
                        }
                    }
            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("退款打印异常${e.message}")
                refundLiveData.postValue(Result.failure(e))
            }

        }
    }


    /**
     * 生成付款码支付
     * payType 只支持微信或者支付宝
     * 2是微信 1是支付宝
     * price 传进来要是分,整数
     */
    fun generatePayCode(price: String, payType: String) {
        XLog.d("开始生成主扫码")
        if (TextUtils.isEmpty(price)) {
            payServiceResponseLiveData.value = Result.failure(RuntimeException("请输入金额!"))
            return
        }

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

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

        XLog.d("主扫码订单号${orderNo}")
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val payServiceResponse = PayRepository.generatePayCode(orderNo, priceFen, payType)
                payServiceResponseLiveData.postValue(Result.success(payServiceResponse))
                XLog.d("生成付款码成功${JSON.toJSONString(payServiceResponse)}")
            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("生成付款码异常${e.message}")
                payServiceResponseLiveData.postValue(Result.failure(e))
            }
        }
    }


    /**
     * 订单查询
     */
    fun payResultQuery(payServiceResponse: PayServiceResponse) {
        payResultJob = viewModelScope.launch(Dispatchers.IO) {
            while (isActive) {
                try {
                    XLog.d("支付查询订单号:${payServiceResponse.shopTradeNo}")
                    val payServiceResponseResult =
                        PayRepository.payResultQuery(payServiceResponse.shopTradeNo)
                    XLog.d("支付查询结果:${JSON.toJSONString(payServiceResponseResult)}")
                    //加入数据库
                    ViewPayOrderData.insert(payServiceResponseResult)
                    payResultLiveData.postValue(Result.success(payServiceResponseResult))
                    break
                } catch (e: Exception) {
                    XLog.d("支付查询异常:${e.message}")
                    e.printStackTrace()
                    payResultLiveData.postValue(Result.failure(e))
                    Thread.sleep(5000)
                }
            }
        }
    }


    /**
     * 订单查询,退款查询
     */
    fun payResultQuery(orderNo: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                XLog.d("开始退款支付查询:${orderNo}")
                val payServiceResponseResult = PayRepository.payResultQuery(orderNo)
                XLog.d("退款支付查询成功:${JSON.toJSONString(payServiceResponseResult)}")
                payResultLiveData.postValue(Result.success(payServiceResponseResult))
            } catch (e: Exception) {
                e.printStackTrace()
                XLog.d("退款支付查询异常:${e.message}")
                payResultLiveData.postValue(Result.failure(e))
            }
        }
    }


    /**
     * 被扫支付,金额是元,首先要转成分
     */
    fun pay(price: String, payCode: String) {
        XLog.d("被扫开始")
        if (TextUtils.isEmpty(price)) {
            payResultLiveData.value = Result.failure(RuntimeException("请输入金额!"))
            return
        }

        if (TextUtils.isEmpty(payCode)) {
            payResultLiveData.value = Result.failure(RuntimeException("付款码为空!"))
            return
        }

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

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

        XLog.d("被扫参数 orderNo = $orderNo price = $priceFen payCode = $payCode")
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //0代表不分类别付款
                val payServiceResponse = PayRepository.pay(orderNo, priceFen, payCode, "0")
                //保存到数据库
                ViewPayOrderData.insert(payServiceResponse)
                payResultLiveData.postValue(Result.success(payServiceResponse))
                XLog.d("被扫支付成功${JSON.toJSONString(payServiceResponse)}")
            } catch (e: Exception) {
                e.printStackTrace()
                payResultLiveData.postValue(Result.failure(e))
                XLog.d("被扫支付异常${JSON.toJSONString(e.message)}")
            }
        }

    }

}