package com.zswc.creativity.vmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.tencent.mmkv.MMKV
import com.ysnows.base.base.BApp
import com.ysnows.base.base.BRepository
import com.ysnows.base.base.BViewModel
import com.ysnows.base.utils.UiSwitch
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import com.zswc.creativity.R
import com.zswc.creativity.activity.LoginActivity
import com.zswc.creativity.utils.ChosePhotoUtils
import okhttp3.Call
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File
import java.util.regex.Pattern


class MyInfoVModel(application: Application) : BViewModel<BRepository>(application)  {

    var imagUrl = MutableLiveData<String>()

    //退出登录
    fun  toExitLogin(){
        //只清空token
        MMKV.defaultMMKV().putString("token", "")
        UiSwitch.single_new_task_with_clear_task(repository().context, LoginActivity::class.java)
    }

    fun choseImg(){

        //选择照片
        ChosePhotoUtils.getChosePhoto(view()!!.context(), 1)

    }

    fun toUpImg(url:String){


        var name: String //文件名字不能含有中文
        val index =url.lastIndexOf("/")

        name = if (isContainChinese(url.substring(index + 1))) {
            System.currentTimeMillis().toString() + ".jpg"
        } else {
            url.substring(index + 1)
        }

        val requestCall = OkHttpUtils.post()
                .url(BApp.config.baseUrl()+"Publics/uploadLocality")
                .addFile("file", name,  File(url))
                .build()

        requestCall.execute(object : StringCallback() {
            override fun onError(call: Call, e: Exception, id: Int) {
                bView.toast(bView.getStr(R.string.upload_pic_fail)+e)
                Log.e("-shy-", "onError: $e")

            }

            override fun onResponse(response: String, id: Int) {
                //地址
                val root = JSONObject(response)
                val root1 = JSONObject(root.getString("data"))
                var url=root1.get("url")
                imagUrl.value = url.toString()




            }
        })



    }
    /**
     * url中是否含有中文
     *
     * @param str
     * @return
     */
    fun isContainChinese(str: String?): Boolean {
        val p = Pattern.compile("[\u4e00-\u9fa5]")
        val m = p.matcher(str)
        return m.find()
    }




}
