package com.zj365.dc.vm

import android.text.TextUtils
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.*
import com.zj365.dc.R
import com.zj365.dc.model.SimpleInfoBean
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 RegisterVm : BaseVm() {
    val codeLive by lazy { MutableLiveData<RespBody<String>>() }
    val registerVm by lazy { MutableLiveData<RespBody<String>>() }
    val mLogin by lazy { MutableLiveData<RespBody<MainBean.User>>() }

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

    /**
     * 密码校验（数字与密码）
     */
//    private fun isPasswordValid(password: String): Boolean {
//        val pattern = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,12}$".toRegex()
//        return pattern.matches(password)
//    }

    fun register(
        phone: String,
        code: String,
        password: String
    ) {
        if (phone.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_phone)
            return
        }
        if (code.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_code)
            return
        }
        if (password.isEmpty()) {
            CommonToastUtils.showToast(R.string.please_input_new_pwd)
            return
        } else {
            if (password.length < 6) {
                CommonToastUtils.showToast(R.string.please_input_new_pwd)
                return
            }

        }
        startHttp {
            withContext(Dispatchers.IO) {
                val json = JSONObject()
                json.put("phone", phone)
                json.put("code", code)
                json.put("password", RxTool.Md5(password))
                val register = apiInterface().register(retrofits.getRequestBody(json.toString()))
                saveToken(register.raw().headers)
                register.body()?.getCodeStatus(registerVm, nowData)
            }
        }
    }

    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)
        }
    }

    suspend fun upLoadImage(image: String): ImageUploadBean {
        var file = File(image)
        var filbody = retrofits.getMultiPartFileRb(file)
        var fileRb = MultipartBody.Part.createFormData("file", file.name, filbody)
        var body = apiInterface().uploadImage(fileRb)
        return body.data
    }

    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)
        }
    }
}