package com.lukouguoji.module_base.service.viewModel

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.R
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.UserRoleBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.http.net.Api
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.http.user.ServiceCreator
import com.lukouguoji.module_base.http.user.UserNetwork
import com.lukouguoji.module_base.http.user.`interface`.CommonService
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.service.repository.LoginRepository
import com.lukouguoji.module_base.util.DictUtils
import com.lukouguoji.module_base.util.WebSocketUtil
import dev.DevUtils
import dev.utils.LogPrintUtils
import dev.utils.app.NetWorkUtils
import dev.utils.app.ShellUtils
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart

class LoginViewModel : BaseViewModel() {
    inner class User(var userAccount: String, var pass: String)

    private val userLiveData = MutableLiveData<User>()

    val userRoleBean = MutableLiveData<UserRoleBean?>()

    val dictList = MutableLiveData<List<KeyValue>>()

    val loginLiveData = Transformations.switchMap(userLiveData) { user ->
        loge("登录信息 : ${user.userAccount} ; ${user.pass} ; $roleTerm ; $userRole")
        LoginRepository.login(user.userAccount, user.pass, roleTerm, userRole)
    }

    val urlList = listOf(
        KeyValue("内网", DevUtils.getContext().resources.getString(R.string.system_url_inner)),
        KeyValue("外网", DevUtils.getContext().resources.getString(R.string.system_url)),
    )

    val weightUrlList = listOf(
        KeyValue("内网", DevUtils.getContext().resources.getString(R.string.weight_url_inner)),
        KeyValue("外网", DevUtils.getContext().resources.getString(R.string.weight_url)),
    )


    val roleList = listOf<KeyValue>(KeyValue("", ""))

    var roleTerm = ""
    var userRole = ""

    fun login(userAccount: String, pass: String) {
        if (userRole.verifyNullOrEmpty("请选择角色")) {
            return
        }
        userLiveData.value = User(userAccount, pass)
    }

    fun onCreated(context: Context) {
        createLoading(context)
        WebSocketUtil.closeWebSocket()
    }

    fun setBaseUrl(index: Int) {
        val baseUrl = urlList[index].value
        val weightUrl = weightUrlList[index].value
        SharedPreferenceUtil.addString(Constant.Share.ipAddress, baseUrl)
        SharedPreferenceUtil.addString(Constant.Share.ipAddressWeight, weightUrl)
        if (ServiceCreator.ipAddress != baseUrl) {
            ServiceCreator.ipAddress = baseUrl
            ServiceCreator.retrofit = ServiceCreator.createRetrofit()
            UserNetwork.commonService = ServiceCreator.create<CommonService>()
            Api.BASE_URL = baseUrl
            NetApply.init()
        }

        DictUtils.getRoleList { list ->
            dictList.value = list
        }
    }

    /**
     * 获取用户角色
     */
    fun getUserRole(account: String) {
        launchCollect({
            NetApply.api.getUserRole(account)
        }) {
            onSuccess = {
                if (it.data == null) {
                    showToast("")
                }
                userRoleBean.value = it.data
            }
        }
    }

    private fun isAvailableByPing(ip: String): Boolean {
        // cmd ping ip
        val pingStr = String.format("ping -c 1 %s", ip)
        loge("ping : $pingStr")
        val result = ShellUtils.execCmd(
            pingStr, false
        )
        // 打印信息
        loge("最终结果: ${result.toJson()}")
        // 判断结果, 返回数据不为 null
        return result.isSuccess3
    }

}