package com.hongyegroup.cpt_auth.mvvm.vm

import android.app.Activity
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.guadou.cs_cptservices.YYConstants
import com.guadou.cs_cptservices.popup.FullWidthTextPopup
import com.guadou.cs_router.YYRouterService
import com.guadou.lib_baselib.base.vm.BaseViewModel
import com.guadou.lib_baselib.engine.SP
import com.guadou.lib_baselib.ext.dp2px
import com.guadou.lib_baselib.engine.putString
import com.guadou.lib_baselib.utils.log.YYLogUtils
import com.hongyegroup.cpt_auth.mvvm.repository.DemoRepository
import com.hongyegroup.cpt_auth.mvvm.repository.SchoolRepository
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class UserLoginViewModel @Inject constructor(
    private val mRepository: DemoRepository,
    private val mSchoolRepository: SchoolRepository,
    private val savedStateHandle: SavedStateHandle
) : BaseViewModel() {

    val mPhoneNumLD = MutableLiveData<String>()    //电话号码值
    val mPasswordLD = MutableLiveData<String>()    //密码登录-密码值
    val mPassCodeLD = MutableLiveData<String>()    //验证码登录-验证码值
    var mMobileCodeLiveData = MutableLiveData<String>()    //当前选中的区号

    //全部的电话号码区号集合
    private val countyCodes = listOf("+1", "+44", "+60", "+61", "+63", "+65", "+66", "+84", "+86", "+852")

    val mLoginSuccessLD = MutableLiveData<Boolean>()  //登录成功的回调

    init {
        mMobileCodeLiveData.value = "+86"

        YYLogUtils.w("mRepository:" + mRepository + " mSchoolRepository:" + mSchoolRepository +" savedStateHandle:"+savedStateHandle)
    }

    /**
     * 下拉选选择国家区号
     */
    fun showCountryCodePopup(view: View, activity: Activity) {

        XPopup.Builder(activity)
            .hasShadowBg(false)
            .isCenterHorizontal(true) //是否与目标水平居中对齐
            .offsetY(-5)
            .popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
            .atView(view) // 依附于所点击的View，内部会自动判断在上方或者下方显示
            .asCustom(FullWidthTextPopup(activity, view, dp2px(300f), countyCodes) { _, text ->
                mMobileCodeLiveData.value = text
            })
            .show()

    }

    /**
     * 执行登录请求
     */
    fun requestLogin() {

        launchOnUI {
            loadStartProgress()

            withContext(Dispatchers.IO) {
                SP().putString(YYConstants.SP_KEY_TOKEN, "test")
                YYRouterService.serviceComponentServer?.resetLoginStatus()

                delay(2500)
            }

            loadHideProgress()
            mLoginSuccessLD.value = true
        }

    }

}