package com.cheng.blzb.ui.fragment.main

import androidx.lifecycle.MutableLiveData
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.UserEntity
import com.cheng.blzb.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 MainViewModel : BaseViewModel() {
    val userInfoLiveData = MutableLiveData<UserEntity>()

    val areaLiveData = MutableLiveData<List<AreaEntity>>()
    val getCouponLiveData = MutableLiveData<Int>()

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

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


    fun getActivityCoupon(ids: String, type: Int) {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.getActivityCoupons(ids)
            if (response.status) {
                getCouponLiveData.postValue(type)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun updateGTCid(cid: String) {
        launchOnUiTryCatch({
            val jsonObject = JsonObject()
            jsonObject.addProperty("client_cid", cid)
            ApiFactory.apiService.changUser(jsonObject.toString().toRequestBody())
        }, {
            setError(it)
            L.d(it)
        })
    }

    fun reportPushReceipt(msgId: String, status: String) {
        launchOnUiTryCatch({
            val jsonObject = JsonObject()
            jsonObject.addProperty("id", msgId)
            jsonObject.addProperty("status", status)
            ApiFactory.apiService.reportPushReceipt(jsonObject.toString().toRequestBody())
        }, {
            setError(it)
            L.d(it)
        })
    }
}