package com.za.ui.servicing.order_confirm.receive_money

import androidx.lifecycle.viewModelScope
import com.za.base.BaseVm
import com.za.base.view.LoadingManager
import com.za.bean.PaymentInfoBean
import com.za.bean.request.CustomerPaymentCreateBean
import com.za.bean.request.CustomerPaymentCreateRequest
import com.za.bean.request.PaymentInfoRequest
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class ReceiveMoneyVm : BaseVm<ReceiveMoneyVm.Action, ReceiveMoneyVm.UiState>() {
    private val _uiState = MutableStateFlow(UiState())
    val uiState get() = _uiState.asStateFlow()
    private var timerJob: Job? = null

    override fun updateState(uiState: UiState) {
        _uiState.value = uiState
    }

    override fun dispatch(action: Action) {
        when (action) {
            is Action.Init -> init(action.userOrderId, action.taskId)
            is Action.ChangeOnSite -> changeOnSite(action.onSite)
            is Action.CreatePaymentInfo -> createPaymentInfo()
        }
    }

    private fun init(userOrderId: Int, taskId: Int) {
        updateState(uiState.value.copy(userOrderId = userOrderId, taskId = taskId))
        queryPaymentInfo {
            createPaymentInfo()
            startTimer()
        }
    }

    private fun createPaymentInfo() {
        LoadingManager.showLoading()
        val customerPaymentCreateRequest = if (uiState.value.isOnSite == 1) {
            CustomerPaymentCreateRequest(userOrderId = uiState.value.userOrderId,
                taskOrderId = uiState.value.taskId,
                onSite = uiState.value.isOnSite,
                orderPayDetailId = uiState.value.paymentInfoBean?.orderPayDetailId)
        } else {
            CustomerPaymentCreateRequest(userOrderId = uiState.value.userOrderId,
                taskOrderId = uiState.value.taskId,
                onSite = uiState.value.isOnSite,
                userPhone = uiState.value.userPhone,
                orderPayDetailId = uiState.value.paymentInfoBean?.orderPayDetailId)
        }
        RetrofitHelper.getDefaultService().customerPaymentCreate(customerPaymentCreateRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<CustomerPaymentCreateBean>() {
                override fun doSuccess(it: CustomerPaymentCreateBean?) {
                    LoadingManager.hideLoading()
                    updateState(uiState.value.copy(qrCode = it?.payData, payState = 1))
                }

                override fun doFailure(code: Int, msg: String?) {
                    LoadingManager.hideLoading()
                }
            })
    }

    private fun changeOnSite(onSite: Int) {
        updateState(uiState.value.copy(isOnSite = onSite, payState = null, userPhone = null, qrCode = null))
        createPaymentInfo()
    }

    private fun queryPaymentInfo(success: (PaymentInfoBean?) -> Unit = {}) {
        LoadingManager.showLoading()
        val paymentInfoRequest = PaymentInfoRequest(uiState.value.userOrderId, uiState.value.taskId)
        RetrofitHelper.getDefaultService()
            .paymentInfoQuery(paymentInfoRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<PaymentInfoBean>() {
                override fun doSuccess(it: PaymentInfoBean?) {
                    LoadingManager.hideLoading()
                    updateState(uiState.value.copy(paymentInfoBean = it, userPhone = it?.userPhone))
                    success(it)
                }

                override fun doFailure(code: Int, msg: String?) {
                    LoadingManager.hideLoading()
                }
            })
    }

    private fun queryPaymentResult() {
        val paymentInfoRequest = PaymentInfoRequest(uiState.value.userOrderId, uiState.value.taskId)
        RetrofitHelper.getDefaultService()
            .paymentInfoQuery(paymentInfoRequest)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<PaymentInfoBean>() {
                override fun doSuccess(it: PaymentInfoBean?) {
                    if (it?.tradeState == 2) {
                        stopTimer()
                        updateState(uiState.value.copy(payState = 3))
                        return
                    } else {
                        updateState(uiState.value.copy(paymentInfoBean = it))
                    }
                }

                override fun doFailure(code: Int, msg: String?) {

                }

            })
    }

    private fun startTimer() {
        stopTimer()
        timerJob = viewModelScope.launch {
            while (isActive) {
                delay(5000)
                queryPaymentResult()
            }
        }
        timerJob?.start()
    }

    private fun stopTimer() {
        timerJob?.cancel()
        timerJob = null
    }

    sealed class Action {
        data class Init(val userOrderId: Int, val taskId: Int) : Action()
        data class ChangeOnSite(val onSite: Int) : Action()
        data object CreatePaymentInfo : Action()
    }

    data class UiState(
        val paymentInfoBean: PaymentInfoBean? = null,
        val userOrderId: Int = 0,
        val taskId: Int = 0,
        val userPhone: String? = null,//用户手机号
        val isOnSite: Int = 1,//是否在现场 1是 2否
        val qrCode: String? = null,//收款二维码
        val payState: Int? = null,//支付状态 1待支付 2支付成功 3 支付成功  4 二维码超时
    )
}