package com.zswc.creativity.vmodel

import android.app.Activity
import android.app.Application
import android.text.Editable
import android.text.TextUtils
import android.util.Log
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zswc.creativity.BR
import com.zswc.creativity.utils.ChosePhotoUtils
import com.zswc.creativity.utils.net.NetEngine
import com.zswc.creativity.view.SimpleTextWatcher
import com.ysnows.base.base.BRepository
import com.ysnows.base.base.BViewModel
import kotlinx.coroutines.launch

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

    //https://cdnheifengwuliu.qs110.com/idcard/xuzgomb3/android/v/mmexport1599207639412.jpg
    var url: MutableLiveData<String> = MutableLiveData("")

    var fk_id="0"
     val num = 255
     var wordNum=0

    var textNums: MutableLiveData<String> = MutableLiveData("0/255")
    var type=1


    @Bindable
    var title: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.title)
        }

    @Bindable
    var phone: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.phone)
        }

    @Bindable
    var content: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.content)
        }


    fun choseImg(){

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

    }

    fun  toSubmit(){

        if(TextUtils.isEmpty(title)){
            toast("请输入标题")
            return
        }

        if(TextUtils.isEmpty(content)){
            toast("选择问题类型帮助我们更快处理您的反馈")
            return
        }

        if(TextUtils.isEmpty(phone)){
            toast("请输入手机号")
            return
        }
        var up_url=""
        if(!TextUtils.isEmpty(url.value)){
            up_url= url.value!!
        }

        viewModelScope.launch {
            val resp = repository().lreq { NetEngine.service.guestEdit(fk_id,title,content,phone,up_url,type.toString()) }
            if (resp.ok(true)) {
                var con = repository().context as Activity
                con.finish()
            }
        }


    }

    var text= object :SimpleTextWatcher(){

        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            Log.e("-shy-", "s=: "+s.toString() )

            val number = s!!.length
            textNums.value= "$number/$num"
            if(wordNum>num){
                s.delete(254,wordNum)
                content= s.toString()
                toast("字数超出范围了")
            }

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            super.onTextChanged(s, start, before, count)
            wordNum = s!!.length //实时记录输入的字数

        }
    }












}
