package com.cheng.bole.ui.fragment.mine.vip

import androidx.lifecycle.MutableLiveData
import com.cheng.bole.net.ApiFactory
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.viewmodel.BaseViewModel
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody

class VipViewModel : BaseViewModel() {
    val userInfoLiveData = MutableLiveData<com.cheng.bole.bean.UserEntity>()
    val mealListLiveData = MutableLiveData<List<com.cheng.bole.bean.VipGoodsEntity>>()
    val couponListLiveData = MutableLiveData<List<com.cheng.bole.bean.CouponEntity>>()
    val createOrderLiveData = MutableLiveData<com.cheng.bole.bean.OrderPayEntity>()

    fun userInfo() {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.userInfo()
            if (response.status) {
                userInfoLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun getGoodsList() {
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.getGoodsList()
            if (response.status) {
                mealListLiveData.postValue(response.data)
            }
        }, {
            setError(it)
            L.d(it)
        })
    }

    fun couponList() {
        val params = HashMap<String, String>()
        params["page"] = "1"
        params["size"] = "50"
        params["status"] = "1"
        params["expire"] = "1"
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.couponList(params)
            if (response.status) {
                couponListLiveData.postValue(response.data.items)
            } else toast(response.message, true)
        },{
            setError(it)
            L.d(it)
        })
    }

    fun payCreateOrder(goos_id: String, pay_type: String, source: String) {
        showDialog()
        launchOnUiTryCatch({
            val json = JsonObject()
            json.addProperty("goods_id", goos_id)
            json.addProperty("pay_type", pay_type)
            json.addProperty("source", source)
            json.addProperty("pay_source", "app")

            val extra = JsonObject()
//            extra.addProperty("choose_red_packet", true)//红包选中
            json.add("extra", extra)
            L.d("TAG-->>$json")
            val response = ApiFactory.apiService.payCreateOrder(json.toString().toRequestBody())
            if (response.status) {
                createOrderLiveData.postValue(response.data)
            } else {
                toast(response.message, true)
            }
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }
}