package com.zj365.dc.vm

import androidx.lifecycle.MutableLiveData
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.ImageUploadBean
import com.xty.network.model.MainBean
import com.xty.network.model.NotAccepted
import com.xty.network.model.RespBody
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.Headers
import okhttp3.MultipartBody
import org.json.JSONObject
import java.io.File

class InfoSimpleVm : BaseVm() {

    val setBasic by lazy { MutableLiveData<RespBody<NotAccepted>>() }
    val mLogin by lazy { MutableLiveData<RespBody<MainBean.User>>() }
    val getImUserSig by lazy { MutableLiveData<RespBody<String>>() }

    fun login(account: String, pwd: String) {
        startHttp {
            val json = JSONObject()
            json.put("phone", account)
            json.put("userPwd", RxTool.Md5(pwd))
            //json.put("userPwd", 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

            MMkvHelper.put(Const.USER_ID, bodys.data.id)
            bodys.getCodeStatus(mLogin, nowData, loading)
        }
    }

    private fun saveToken(headers: Headers) {
        val headerIterator = headers.iterator()
        while (headerIterator.hasNext()) {
            val next = headerIterator.next()
            if (Const.Auth_Token == next.first) MMkvHelper.put(Const.Auth_Token, next.second)

            if (Const.Auth_Id == next.first) MMkvHelper.put(Const.Auth_Id, next.second)
        }
    }

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

    fun submit(path: String, name: String?, sex: String, birthDaytype: String, birthDay: String) {
        startHttp {
            withContext(Dispatchers.IO) {
                var fileId = ""
                if (path.isNullOrEmpty()) {

                } else {
                    val image = async { uploadImage(path) }
                    val await = image.await()
                    fileId = await.fileId
                }
                val upload = async { uploadInfo(name, sex, fileId, birthDaytype, birthDay) }
                val await = upload.await() //个人信息上传
                if (await.code != 0) {
                    CommonToastUtils.showToast(await.msg)
                }
            }
        }
    }

    private suspend fun uploadInfo(
        name: String?,
        sex: String,
        fileId: String = "",
        birthdayType: String,
        birthDay: String
    ): RespBody<NotAccepted> {
        val json = JSONObject()
        json.put("name", name)
        json.put("sex", sex)
        if (sex == "1") {
            json.put("height", "170")
            json.put("weight", "65")
        } else {
            json.put("height", "160")
            json.put("weight", "49")
        }

        json.put("birthday", birthDay)
        json.put("birthdayType", birthdayType)

        if (!fileId.isNullOrEmpty()) {
            json.put("avatarUrl", fileId)
        }
        val rb = retrofits.getRequestBody(json.toString())
        val body = apiInterface().setUpdateUser(rb)
        body.getCodeStatus(setBasic, nowData)
        return body
    }

    private suspend fun uploadImage(path: String): ImageUploadBean {
        val f = File(path)
        val fileRb = MultipartBody.Part.createFormData(
            "file",
            f.name,
            retrofits.getMultiPartFileRb(f)
        )
        val body = apiInterface().uploadImage(fileRb)
        return body.data
    }
}