package com.zj365.mime.vm

import androidx.lifecycle.MutableLiveData
import com.xty.base.vm.BaseVm
import com.xty.common.BuildConfig
import com.xty.network.model.RespBody
import com.xty.network.model.SettingBean
import com.xty.network.model.WxTokenBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext

class AccountSafeVm: BaseVm() {

    val allData by lazy { MutableLiveData<RespBody<SettingBean>>() }
    val destLive by lazy{MutableLiveData<RespBody<Any>>()}
    val bindWx by lazy{MutableLiveData<RespBody<Any>>()}
    /**
     * 获取所有信息
     */
    fun getAllInfo() {
        startHttp {
            var body = apiInterface().getMySetting()
            body.getCodeStatus(allData,nowData)
        }
    }


    /**
     * 获取openId
     */
    fun getWxOpenId(code:String){
        startHttp {
            withContext(Dispatchers.IO) {
                startHttp {
                    withContext(Dispatchers.IO) {
                        var tokenHttp = async { getWxToken(code) }
                        var token = tokenHttp.await()
                        if(!token.openid.isNullOrEmpty()){
                            //开始进行绑定
                            var body = apiInterface().bindWx(token.openid)
                            body.getCodeStatus(bindWx,nowData)
                        }
                    }
                }
            }
        }
    }
    /**
     * 获取微信登陆信息
     */
    private suspend fun getWxToken(code:String): WxTokenBean {
        var url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=${BuildConfig.appid}" +
                "&secret=${BuildConfig.appSecret}" +
                "&code=$code" +
                "&grant_type=authorization_code"
        return   apiInterface().getWxToken(url)

    }

    //账号注销
    fun destAccount(id:String){
        startHttp {
            var response= apiInterface().destAccount(id)
            response.getCodeStatus(destLive,nowData)
        }
    }
}