package com.zswc.creativity.vmodel

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.zswc.creativity.BR
import com.zswc.creativity.config.ConfigMMKV
import com.zswc.creativity.config.ConfigRx
import com.zswc.creativity.model.User
import com.zswc.creativity.utils.ChosePhotoUtils
import com.zswc.creativity.utils.net.NetEngine
import com.ysnows.base.base.BRepository
import com.ysnows.base.base.BViewModel
import com.ysnows.base.utils.MMKVManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch
import java.util.HashMap
import java.util.concurrent.TimeUnit

open class PasswordVModel(application: Application) : BViewModel<BRepository>(application) {


    var isShow: MutableLiveData<Boolean> = MutableLiveData()

    var type: MutableLiveData<Int> = MutableLiveData(1)

    var isPayShow: MutableLiveData<Boolean> = MutableLiveData()

    var avatar: MutableLiveData<String> = MutableLiveData()

    var codeTip: MutableLiveData<String> = MutableLiveData(getCodeStr)
    private var disposable: Disposable? = null

    var phone: MutableLiveData<String> = MutableLiveData()

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


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


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


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

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

    fun choseImg() {

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

    }

    fun setInitData() {
        var user = User.get()
        avatar.value = user!!.headimg
        name = user!!.name
    }




    fun toPaySubmit( newPassword: String) {


        if (TextUtils.isEmpty(code)) {
            toast("请输入短信验证码")
            return
        }

//        var oldpwd = ""
//        if (isPayShow.value!!) {
//            if (TextUtils.isEmpty(oldpword)) {
//                toast("请输入旧支付密码")
//                return
//            }
//
//            oldpwd = oldpword
//        }

        if (TextUtils.isEmpty(newPassword)) {
            toast("请输入新支付密码")
            return
        }


        var map = HashMap<String, String>()
        map["code"] = code.toString()
        map["newpwd"] = newPassword
        map["type"] = "1"

        repository().rxLreq(NetEngine.service.setPwd(map))
                .doOnNext {
                    if (it.ok(true)) {
                        toast(it.msg())

                        if (!isPayShow.value!!) {
                            //没有设置密码

                        }

                        (repository().context as Activity).finish()
                    }
                }
                .subscribe()

    }


    fun toSaveInfo() {//保存个人信息
        if (TextUtils.isEmpty(name) && TextUtils.isEmpty(avatar.value)) {
            toast("姓名或者头像必须要修改一项才能保存")
            return
        }
        var avatarUrl = ""
        if (!TextUtils.isEmpty(avatar.value)) {
            avatarUrl = avatar.value!!
        }
        var name = ""
        if (!TextUtils.isEmpty(this.name)) {
            name = this.name!!
        }

        viewModelScope.launch {

            val resp = repository().lreq { NetEngine.service.setProfile(avatarUrl, name) }
            if (resp.ok(true)) {
                var user = User.get()
                user!!.name = name
                user.save()

                RxBus.get().post(ConfigRx.REFRESH_USER, "")

                var con = repository().context as Activity
                con.finish()
            }

        }


    }

    companion object {
        const val time = 60
        var timeStart: Long = 1
        const val getCodeStr = "获取验证码"

    }


    fun getSmsCode(start: Long = 1) {


        viewModelScope.launch {

            var it = repository().lreq { NetEngine.service.getSmsCode() }

            if (it.ok(true)) {

                startTimer(start)

            }

        }

    }

    private fun startTimer(start: Long = 1) {
        disposeTimer()
        disposable = Observable.intervalRange(start, time - start + 1, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    timeStart = it
                    codeTip.value = if (time - it > 0) "${time - it}秒后重发" else {
                        getCodeStr
                    }
                }
                .doOnComplete() {
                    MMKVManager.instance().encode(ConfigMMKV.REGISTER_TIME_START, 60)
                }
                .doOnDispose() {
                    MMKVManager.instance().encode(ConfigMMKV.REGISTER_TIME_START, 60)
                }
                .subscribe()
    }


    override fun onCleared() {
        super.onCleared()
        disposeTimer()
    }

    private fun disposeTimer() {
        disposable?.isDisposed ?: disposable?.dispose()
    }


}
