package com.adealink.weparty.joinus.step2

import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.contentView
import com.adealink.weparty.commonui.ext.fitSystemWindows
import com.adealink.weparty.commonui.ext.onWindowInsets
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.joinus.R
import com.adealink.weparty.joinus.databinding.FragmentJoinUsStep2Binding
import com.adealink.weparty.joinus.step2.comp.EditAvatarComp
import com.adealink.weparty.joinus.step2.comp.EditBirthdayComp
import com.adealink.weparty.joinus.step2.comp.EditGenderComp
import com.adealink.weparty.joinus.step2.comp.EditIntroductionComp
import com.adealink.weparty.joinus.step2.comp.EditLanguageComp
import com.adealink.weparty.joinus.step2.comp.EditNicknameComp
import com.adealink.weparty.joinus.step2.data.Step2EditUserInfo
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory

class JoinUsStep2Fragment : BaseFragment(R.layout.fragment_join_us_step_2) {

    private val binding by viewBinding(FragmentJoinUsStep2Binding::bind)
    private val step2ViewModel by viewModels<Step2ViewModel>()
    private val joinUsViewModel by activityViewModels<JoinUsViewModel> { JoinUsViewModelFactory() }
    override fun initViews() {
        super.initViews()
        binding.btnSubmit.isEnabled = false
        binding.btnSubmit.onClick {
            submit()
        }
        fitWindow()
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        val contentView = activity?.contentView() ?: return
        val submitButton = binding.btnSubmit
        val submitButtonMask = binding.vSubmitMask
        contentView.onWindowInsets { view, insets ->
            val ime = insets.getInsets(WindowInsetsCompat.Type.ime())

            // 键盘显示时使用键盘高度，否则使用导航栏高度
            val bottomInset = if (ime.bottom > 0) ime.bottom else 0
            submitButton.show(bottomInset <= 0)
            submitButtonMask.show(bottomInset <= 0)
            view.updatePadding(bottom = bottomInset)
            insets
        }
    }

    override fun initComponents() {
        super.initComponents()
        EditAvatarComp(this, binding.vEditAvatar).attach()
        EditNicknameComp(this, binding.vEditNickname).attach()
        EditGenderComp(this, binding.vEditGender).attach()
        EditBirthdayComp(this, binding.vEditBirthday).attach()
        EditLanguageComp(this, binding.vEditLanguage).attach()
        EditIntroductionComp(this, binding.vEditIntroduction).attach()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        step2ViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            val enable = checkSubmitEnable(it)
            binding.btnSubmit.isEnabled = enable
        }
    }

    override fun loadData() {
        super.loadData()
        step2ViewModel.initEditUserInfo(joinUsViewModel.joinProgressLD.value?.step2)
        step2ViewModel.loadLanguageConfig()
    }

    private fun checkSubmitEnable(
        userInfo: Step2EditUserInfo?,
        showToast: Boolean = false
    ): Boolean {
        if (userInfo == null) {
            return false
        }
        if (userInfo.avatar == null || userInfo.avatar?.isNull() == true) {
            if (showToast) {
                showToast(R.string.join_us_step2_avatar_is_empty)
            }
            return false
        }
        val nickName = userInfo.nickname
        if (nickName.isNullOrEmpty()) {
            if (showToast) {
                showToast(R.string.join_us_step2_nickname_is_empty)
            }
            return false
        }
        if (userInfo.birthday == null || (userInfo.birthday ?: 0) <= 0) {
            if (showToast) {
                showToast(R.string.join_us_step2_birthday_is_empty)
            }
            return false
        }
        if (userInfo.languages.isNullOrEmpty()) {
            if (showToast) {
                showToast(R.string.join_us_step2_language_is_empty)
            }
            return false
        }
        val intro = userInfo.intro
        if (intro.isNullOrEmpty()) {
            if (showToast) {
                showToast(R.string.join_us_step2_intro_is_empty)
            }
            return false
        }
        return true
    }

    private fun submit() {
        val userInfo = step2ViewModel.editUserInfoLD.value
        if (!checkSubmitEnable(userInfo, true)) {
            return
        }
        showLoading()
        step2ViewModel.improveUserInfo().observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    dismissLoading()
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    val progressData = rlt.data
                    if (progressData == null) {
                        joinUsViewModel.loadApplyProgress()
                    } else {
                        joinUsViewModel.updateApplyProgress(rlt.data)
                    }
                }
            }
        }
    }

}