package com.adealink.weparty.playmatesetting.page

import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import com.adealink.frame.base.fastLazy
import com.adealink.frame.log.Log
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.showToast
import com.adealink.weparty.joinus.R
import com.adealink.weparty.joinus.databinding.FragmentPlaymateSettingFormBinding
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory
import com.adealink.weparty.playmatesetting.viewmodel.PlaymateSettingViewModel
import com.adealink.weparty.module.widget.form.BaseWidgetView
import com.adealink.weparty.module.widget.form.adapter.StepWidgetAdapter
import com.adealink.weparty.module.widget.form.data.FieldException
import com.adealink.weparty.module.widget.form.data.StepField

class PlaymateSettingFormFragment : BaseFragment(R.layout.fragment_playmate_setting_form) {

    companion object {
        const val TAG = "PlaymateSettingFormFragment"
    }


    private val binding by viewBinding(FragmentPlaymateSettingFormBinding::bind)
    private val settingViewModel by activityViewModels<PlaymateSettingViewModel> { JoinUsViewModelFactory() }

    private val fieldAdapter by fastLazy { StepWidgetAdapter() }
    private val formWidgetList = mutableListOf<BaseWidgetView<*>>()

    override fun initViews() {
        super.initViews()
        //binding.btnSubmit.isEnabled = false
        binding.btnSubmit.onClick {
            clickConfirm()
        }
        fitWindow()
    }

    private fun fitWindow() {
        // 关键：只在需要的时候设置
        activity?.window?.fitSystemWindows(false)
        // 内容布局处理键盘
        val contentView = activity?.contentView() ?: return
        val submitButton = binding.btnSubmit
        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)
            view.updatePadding(bottom = bottomInset)
            insets
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        settingViewModel.selectCategoryLD.observe(viewLifecycleOwner) {
            binding.tvTitle.text = it?.categoryName
        }
    }

    override fun loadData() {
        super.loadData()
        val formData = settingViewModel.categoryFormLD.value
        if (formData == null) {
            return
        }
        inflateForm(formData.fields)
    }

    private fun inflateForm(fields: List<StepField<*>>) {
        try {
            val widgetList = fieldAdapter.inflateWidget(this, binding.llForm, fields)
            formWidgetList.clear()
            formWidgetList.addAll(widgetList)
        } catch (e: Exception) {
            Log.e(TAG, "inflateForm fail, for ${e.message}", e)
            if (e is FieldException) {
                showToast(e.message)
            }
        }
    }

    private fun clickConfirm() {
        showLoading()
        settingViewModel.submitForm(formWidgetList).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
        }
    }

}