package com.adealink.weparty.joinus.step2.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.frame.oss.data.UploadFile
import com.adealink.frame.util.formatTime
import com.adealink.weparty.App
import com.adealink.weparty.image.AVATAR_IMAGE_MAX_HEIGHT
import com.adealink.weparty.image.AVATAR_IMAGE_MAX_SIZE_KB
import com.adealink.weparty.image.AVATAR_IMAGE_MAX_WIDTH
import com.adealink.weparty.image.AVATAR_IMAGE_MIN_QUALITY
import com.adealink.weparty.joinus.data.ImproveUserInfoReq
import com.adealink.weparty.joinus.data.JoinStep2
import com.adealink.weparty.joinus.data.JoinUsData
import com.adealink.weparty.joinus.datasource.remote.JoinUsHttpService
import com.adealink.weparty.joinus.step2.data.LanguageConfigData
import com.adealink.weparty.joinus.step2.data.Step2EditUserInfo
import com.adealink.weparty.module.image.data.PhotoData
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.Gender
import com.adealink.weparty.util.uploadPhotos
import kotlinx.coroutines.launch

class Step2ViewModel : BaseViewModel() {

    private val joinUsHttpService by lazy {
        App.instance.networkService.getHttpService(
            JoinUsHttpService::class.java
        )
    }
    private val editUserInfo = Step2EditUserInfo()
    val editUserInfoLD = MutableLiveData<Step2EditUserInfo>()

    init {
        editUserInfoLD.send(editUserInfo)
    }

    fun getEditUserInfo(): Step2EditUserInfo {
        return editUserInfo
    }

    fun initEditUserInfo(step2: JoinStep2?) {
        editUserInfo.avatar = PhotoData(url = step2?.avatar, null, null)
        editUserInfo.nickname = step2?.nickname
        editUserInfo.gender = Gender.map(step2?.gender)
        editUserInfo.birthday = step2?.getBirthdayTs()
        editUserInfo.intro = step2?.intro
        editUserInfoLD.send(editUserInfo)
    }

    fun setAvatar(
        url: String?,
        path: String?,
        uri: String?
    ) {
        editUserInfo.avatar = PhotoData(url, path, uri)
        editUserInfoLD.send(editUserInfo)
    }

    fun setNickName(name: String?) {
        if (editUserInfo.nickname == name) {
            return
        }
        editUserInfo.nickname = name
        editUserInfoLD.send(editUserInfo)
    }

    fun setBirthday(birthday: Long) {
        editUserInfo.birthday = birthday
        editUserInfoLD.send(editUserInfo)
    }

    fun setGender(gender: Gender) {
        editUserInfo.gender = gender
        editUserInfoLD.send(editUserInfo)
    }

    fun setIntro(intro: String?) {
        if (editUserInfo.intro == intro) {
            return
        }
        editUserInfo.intro = intro
        editUserInfoLD.send(editUserInfo)
    }

    fun setLanguage(languageCodeList: List<LanguageConfigData>?) {
        editUserInfo.languages = languageCodeList
        editUserInfoLD.send(editUserInfo)
    }


    fun improveUserInfo(): LiveData<Rlt<JoinUsData?>> {
        val liveData = OnceMutableLiveData<Rlt<JoinUsData?>>()
        viewModelScope.launch {
            //检查头像
            editUserInfo.avatar?.let { avatar ->
                if (avatar.isLocal() && !avatar.isNull()) {
                    val rlt = uploadPhotos(
                        listOf(avatar),
                        AVATAR_IMAGE_MAX_WIDTH,
                        AVATAR_IMAGE_MAX_HEIGHT,
                        AVATAR_IMAGE_MAX_SIZE_KB,
                        AVATAR_IMAGE_MIN_QUALITY,
                        UploadFile.FileType.AVATAR
                    )
                    when (rlt) {
                        is Rlt.Failed -> {
                            liveData.send(rlt)
                            return@launch
                        }

                        is Rlt.Success -> {
                            editUserInfo.avatar?.let {
                                it.url = rlt.data.firstOrNull()?.url
                            }
                        }
                    }
                }
            }
            val rlt = joinUsHttpService.improveUserInfo(
                ImproveUserInfoReq(
                    avatar = editUserInfo.avatar?.url,
                    nickname = editUserInfo.nickname,
                    gender = editUserInfo.gender?.gender,
                    birthday = editUserInfo.birthday?.let { ts ->
                        formatTime(ts, "yyyy-MM-dd")
                    },
                    languageCodes = editUserInfo.languages?.map { it.code },
                    intro = editUserInfo.intro,
                )
            )
            when (rlt) {
                is Rlt.Failed -> {
                    liveData.send(rlt)
                }

                is Rlt.Success -> {
                    onUserInfoImprove()
                    liveData.send(Rlt.Success(rlt.data.data))
                }
            }
        }
        return liveData
    }

    private fun onUserInfoImprove() {
        viewModelScope.launch {
            ProfileModule.getUserInfoByUid(ProfileModule.getMyUid(), false)
        }
    }

    private var languageCache: List<LanguageConfigData>? = null

    fun loadLanguageConfig(): LiveData<Rlt<List<LanguageConfigData>>> {
        val liveData = OnceMutableLiveData<Rlt<List<LanguageConfigData>>>()
        viewModelScope.launch {
            val languageCache = this@Step2ViewModel.languageCache
            if (!languageCache.isNullOrEmpty()) {
                liveData.send(Rlt.Success(languageCache))
                return@launch
            }

            val rlt = joinUsHttpService.getLanguageConfig()
            when (rlt) {
                is Rlt.Failed -> {
                    liveData.send(rlt)
                }

                is Rlt.Success -> {
                    val list = rlt.data.data?.languages ?: emptyList()
                    this@Step2ViewModel.languageCache = list
                    liveData.send(Rlt.Success(list))
                }
            }
        }
        return liveData
    }
}
