package cn.muchinfo.rma.view.base.future.trade

import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.business.future.adapter.ChannelOrderReqData
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.AccountData
import cn.muchinfo.rma.global.data.AccountShowData
import cn.muchinfo.rma.global.data.QuoteDayData
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo
import cn.muchinfo.rma.global.data.futureOrders.FutureHoldData
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.base.BaseViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mtp.polymer.com.autowidget.utils.TaskUiModel

/**
 * 期货交易页面额viewmodel
 */
class GoodsTradeViewModel : BaseViewModel() {

    /**
     * 数据初始化状态控制
     */
    val loadingDialogStatus: MutableLiveData<TaskUiModel> = MutableLiveData()

    /**
     * 价格取价类型
     */
    val priceOrderType: MutableLiveData<Int> = MutableLiveData()

    /**
     * 通道下单类型
     */
    val tradeMode: MutableLiveData<Int> = MutableLiveData()

    /**
     * 交易页面的当前商品的盘面信息
     */
    val quoteDayData: MutableLiveData<QuoteDayData> = MutableLiveData()

    /**
     * 使用的当前的资金账户信息
     */
    val usedAccountData : MutableLiveData<AccountData> = MutableLiveData()

    /**
     * 权益
     */
    val allWorth : MutableLiveData<String> = MutableLiveData()

    /**
     * 可用
     */
    val canUseWorth : MutableLiveData<String> = MutableLiveData()

    /**
     * 请求盘面信息
     * @param first Int
     * @param last Int
     * @param callback Function2<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryQuoteDay(
        tag : String,
        goodsCodes: String,
        isShowLoading : Boolean
    ) {
        if (isShowLoading){
            loadingDialogStatus.postValue(TaskUiModel.inFlight())
        }

        val params = mutableMapOf<String, String>().apply {
            put("goodsCodes", goodsCodes)
        }
        MyApplication.getInstance()?.futureManager?.queryQuoteDay(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                if (respData?.isEmpty()?.not() == true) {
                    quoteDayData.postValue(respData[0])
                }
                if (isShowLoading){
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "数据请求成功"))
                }

            } else {
                if (isShowLoading){
                    loadingDialogStatus.postValue(TaskUiModel.failed(InteractiveException(errorMessage = "数据请求失败")))
                }
            }
        }
        addSubscriptQuote(tag = tag,goodsCodes = setOf(goodsCodes))
    }

    /**
     * 订阅行情
     * @param tag String
     * @param goodsInfoList List<GoodsInfo>
     */
    fun addSubscriptQuote(tag : String,goodsCodes: Set<String>){
        GlobalScope.launch {
            MyApplication.getInstance()?.quoteManager?.addSubscriptQuote(
                tag = tag,goodsCodeSet = goodsCodes
            ){isCompleted, err ->

            }
        }
    }

    /**
     * 取消订阅
     * @param tag String
     */
    fun removeSubscriptQuote(tag : String){
        GlobalScope.launch {
            MyApplication.getInstance()?.quoteManager?.removeSubscriptQuote(
                tag = tag
            )
        }
    }

    /**
     * 获取资金信息
     */
    fun calculateMoney(){
        val accountData = GlobalDataCollection.instance?.accountData
        accountData?.setNormalData()
        canUseWorth.postValue(accountData?.canUserAmount.toString())
        allWorth.postValue(accountData?.rightsAndInterests.toString())
    }

    /**
     * 交易下单请求
     * @param data ChannelOrderReqData
     * @param isSuccess Function1<[@kotlin.ParameterName] Boolean, Unit>
     */
    fun tradeRequest(
        data: ChannelOrderReqData,
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.futureManager?.tradeRequest(data = data){isCompleted, err ->
                if (isCompleted){
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                }else{
                    loadingDialogStatus.postValue(TaskUiModel.failed(InteractiveException(errorMessage = err?.message!!)))
                }
            }
        }
    }

    /**
     * 更新交易下单的account
     */
    fun initAccountData(){
        val accountDataList = GlobalDataCollection.instance?.accountDataList
        if (accountDataList.isNullOrEmpty().not()){
            usedAccountData.postValue(GlobalDataCollection.instance?.accountData)
        }
    }

    fun getNowSelectHoldData(goodsId : String,buyorsell : Int) : FutureHoldData{
        val holdList = GlobalDataCollection.instance?.futureHoldData
        var futureholddata : FutureHoldData? = null
        holdList?.forEach {
            if (goodsId == it.goodsid.toString() && buyorsell == it.buyorsell){
                futureholddata = it
            }
        }
         return futureholddata ?: FutureHoldData()
    }

}