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

import androidx.lifecycle.MutableLiveData
import com.cheng.bole.common.Constants
import com.cheng.bole.net.ApiFactory
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.utils.Utils
import com.example.base.viewmodel.BaseViewModel
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class MineViewModel : BaseViewModel() {
    val userInfoLiveData = MutableLiveData<com.cheng.bole.bean.UserEntity>()

    fun userInfo(showLoading: Boolean = false) {
        if (showLoading) 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 wxService() {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.wxService()
            if (response.status) {
                contactClientService(response.data)
            } else {
                toast(response.message, true)
            }
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    private fun contactClientService(data: com.cheng.bole.bean.WxServiceEntity) {
        val api = WXAPIFactory.createWXAPI(Utils.getApp(), Constants.WechatAppId)
        if (!api!!.isWXAppInstalled) {
            toast("未安装微信客户端")
            return
        }
        if (api.wxAppSupportAPI >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
            val req = WXOpenCustomerServiceChat.Req()
            req.corpId = data.corpid
            req.url = data.address
            api.sendReq(req)
        }
    }
}