package com.adealink.weparty.module.widget.form

import android.content.Context
import android.util.AttributeSet
import androidx.annotation.CallSuper
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.base.Rlt
import com.adealink.weparty.commonui.ext.getActivity
import com.adealink.weparty.module.widget.form.data.FieldException
import com.adealink.weparty.module.widget.form.data.StepFieldValue
import com.adealink.weparty.module.widget.form.dialog.ExampleDialog

abstract class BaseWidgetView<DATA : IWidgetData> @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : ConstraintLayout(context, attrs, defStyle) {
    var widgetData: DATA? = null

    /**
     * 创建表格组件
     */
    @Throws(FieldException::class)
    @CallSuper
    open fun onViewCreated(lifecycleOwner: LifecycleOwner, widget: DATA) {
        this.widgetData = widget
        checkWidgetValid(widget)
    }

    @Throws(FieldException::class)
    open fun checkWidgetValid(widget: DATA) {
    }

    /**
     * 校验
     */
    abstract fun validate(): Rlt<Any>

    /**
     * 提交前的操作
     */
    open suspend fun beforeSubmit(): Rlt<Any> {
        return Rlt.Success(Unit)
    }

    /**
     * 获取表格值
     */
    abstract fun getFieldValue(): StepFieldValue?

    /**
     * 是否已经编辑
     */
    abstract fun hasEditFieldValue(): Boolean

    fun showExampleDialog() {
        val act = context.getActivity() ?: return
        val data = widgetData ?: return
        ExampleDialog().apply {
            setExample(data.fieldData.example)
        }.show(act.supportFragmentManager, "ExampleDialog")
    }
}