package com.zj365.dc.vm

import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.google.gson.internal.LinkedTreeMap
import com.tamsiree.rxkit.RxRegTool
import com.tamsiree.rxkit.RxTool
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.MMkvHelper
import com.xty.common.util.CommonToastUtils
import com.xty.network.model.MainBean
import com.xty.network.model.RespBody
import com.xty.network.model.Update
import com.xty.network.model.WxInfoBean
import com.xty.network.model.WxTokenBean
import com.zj365.dc.BuildConfig
import com.zj365.dc.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.Headers
import org.json.JSONObject

class LoginVm() : BaseVm() {
    val mLogin by lazy { MutableLiveData<RespBody<MainBean.User>>() }
    val codeLive by lazy { MutableLiveData<RespBody<String>>() }
    val getImUserSig by lazy { MutableLiveData<RespBody<String>>() }
    val wxLoginInfo by lazy { MutableLiveData<WxInfoBean>() }
    val loginWxRegister by lazy { MutableLiveData<RespBody<Any>>() }
    val loginWx by lazy { MutableLiveData<RespBody<Any>>() }
    val setLoginWxId by lazy { MutableLiveData<Long>() }
    fun login(account: String, pwd: String) {
        if (account.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_phone)
            return
        }else{
            if(!RxRegTool.isMobileSimple(account)){
                CommonToastUtils.showToast(R.string.please_input_ok_phone)
                return
            }
        }
        if (pwd.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_new_pwd)
            return
        } else {
            if (pwd.length < 6) {
                CommonToastUtils.showToast(R.string.please_input_new_pwd)
                return
            }

        }
        startHttp {
            val json = JSONObject()
            json.put("phone", account)
            json.put("userPwd", RxTool.Md5(pwd))
            val login = apiInterface().login(retrofits.getRequestBody(json.toString()))
            if (login.body()?.code == 500) {
                login.body()?.msg?.let { CommonToastUtils.showToast(it) }
                return@startHttp
            }
            saveToken(login.raw().headers)
            val bodys = login.body() as RespBody
            if (bodys != null){
                MMkvHelper.put(Const.USER_ID, bodys.data.id)
                val deviceType = bodys.data.deviceType
                if (TextUtils.isEmpty(deviceType)) {
                    MMkvHelper.remove(Const.DEVICE_TYPE)
                } else {
                    MMkvHelper.put(Const.DEVICE_TYPE, bodys.data.deviceType)
                }
            }

            bodys.getCodeStatus(mLogin, nowData, loading)
        }
    }

    /**
     * 验证码登陆
     */
    fun loginCode(account: String, code: String) {
        if (account.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_phone)
            return
        }
        if (code.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_code)
            return
        }
        startHttp {
            val login = apiInterface().loginCode(account, code)
            if (login.body()?.code == 500) {
                login.body()?.msg?.let { CommonToastUtils.showToast(it) }
                return@startHttp
            }
            saveToken(login.raw().headers)
            val bodys = login.body() as RespBody
            if(bodys != null){
                MMkvHelper.put(Const.USER_ID, bodys.data.id)
                val deviceType = bodys.data.deviceType
                if (TextUtils.isEmpty(deviceType)) {
                    MMkvHelper.remove(Const.DEVICE_TYPE)
                } else {
                    MMkvHelper.put(Const.DEVICE_TYPE, bodys.data.deviceType)
                }
            }

            bodys.getCodeStatus(mLogin, nowData, loading)
        }
    }


    fun sendCode(phone: String) {
        startHttp {
            var code = apiInterface().sendCode(phone)
            code.getCodeStatus(codeLive, nowData)
        }

    }

    fun getImUserSig(identifier: String) {
        startHttp {
            val imUserSig = apiInterface().getImUserSig(identifier)
            imUserSig.body()?.getCodeStatus(getImUserSig, nowData, paramsData = identifier)
        }
    }

    fun getWxLoginInfo(code: String) {
        startHttp {
            withContext(Dispatchers.IO) {
                var tokenHttp = async { getWxToken(code) }
                var token = tokenHttp.await()
                if (token.access_token.isNotEmpty() && token.openid.isNotEmpty()) {
                    var wxInfoHttp = async { getWxInfo(token.access_token, token.openid) }
                    var wxInfo = wxInfoHttp.await()
                    if (wxInfo.errcode == 0) {
                        wxLoginInfo.postValue(wxInfo)
                    }
                }
            }

        }
    }

    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)

    }

    private suspend fun getWxInfo(token: String, openId: String): WxInfoBean {
        var url = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=$token" +
                "&openid=$openId"
        return apiInterface().getWxInfo(url)
    }

    fun loginWx(bean: WxInfoBean) {
        startHttp {
            val json = JSONObject()
            json.put("openId", bean.openid)
            val body = apiInterface().loginWx(retrofits.getRequestBody(json.toString()))

            val respBody = body.body() as RespBody
            if (respBody.data is String) {
                respBody.getCodeStatus(loginWxRegister, nowData)
            } else {
                saveToken(body.raw().headers)
                val bodys = body.body()!!.data as LinkedTreeMap<*, *>
                if (bodys.containsKey("deviceType")) {
                    val deviceType = bodys["deviceType"]
                    var result = ""
                    if (deviceType is String) {
                        result = deviceType
                    } else if (deviceType is Double) {
                        result = deviceType.toString()
                    }
                    if (TextUtils.isEmpty(result)) {
                        MMkvHelper.remove(Const.DEVICE_TYPE)
                    } else {
                        MMkvHelper.put(Const.DEVICE_TYPE, result)
                    }
                }
                if (bodys.containsKey("id")) {
                    val id = bodys["id"]
                    var result = 0L
                    if (id is Long) {
                        result = id
                    } else if (id is Double) {
                        result = id.toLong()
                    }
                    setLoginWxId.postValue(result)
                    MMkvHelper.put(Const.USER_ID, result)
                    Log.e("simon", "成功-- ${MMkvHelper.getLong(Const.USER_ID)}")
                }
                respBody.getCodeStatus(loginWx, nowData, loading)
            }

        }
    }

    private fun saveToken(headers: Headers) {
        var headerIterator = headers.iterator()
        while (headerIterator.hasNext()) {
            var next = headerIterator.next()
            if (Const.Auth_Token == next.first || "auth-token".equals(next.first)) MMkvHelper.put(Const.Auth_Token, next.second)

            if (Const.Auth_Id == next.first || "auth-id".equals(next.first)) MMkvHelper.put(Const.Auth_Id, next.second)
        }
    }

    val updateLive by lazy { MutableLiveData<RespBody<Update>>() }

    fun getVersionNew() {
        startHttp {
          /*  var response = apiInterface().getVersionNew(BuildConfig.VERSION_CODE)
            response.getCodeStatus(updateLive, nowData)*/
        }
    }
}