package com.narutohuo.xindazhou.common.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch

/**
 * 基础 Fragment
 * 
 * 封装 UI 通用功能：
 * - ViewBinding 支持
 * - 统一的加载状态管理
 * - 统一的错误提示
 * - 生命周期管理
 * 
 * 使用方式：
 * ```kotlin
 * class LoginFragment : BaseFragment<FragmentLoginBinding>() {
 *     private val viewModel: LoginViewModel by viewModels()
 *     
 *     override fun initObserver() {
 *         // 使用扩展函数简化代码
 *         observeStateFlow(viewModel.loginState) { state ->
 *             when (state) {
 *                 is LoginState.Loading -> showLoading()
 *                 is LoginState.Success -> {
 *                     hideLoading()
 *                     showSuccess(state.message)
 *                 }
 *                 is LoginState.Error -> {
 *                     hideLoading()
 *                     showError(state.message)
 *                 }
 *             }
 *         }
 *     }
 * }
 * ```
 */
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
    
    protected lateinit var binding: VB
    protected abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
    
    // 加载状态（子类可重写自定义实现）
    protected open fun showLoading() {
        // 默认实现：显示加载提示
        // 子类可重写自定义加载UI
    }
    
    protected open fun hideLoading() {
        // 默认实现：隐藏加载提示
        // 子类可重写自定义加载UI
    }
    
    // 错误提示（子类可重写自定义实现）
    protected open fun showError(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }
    
    protected open fun showSuccess(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = getViewBinding(inflater, container)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initObserver()
    }
    
    /**
     * 初始化视图（子类实现）
     */
    protected open fun initView() {}
    
    /**
     * 初始化观察者（子类实现）
     */
    protected open fun initObserver() {}
    
    /**
     * 统一执行网络请求
     * 
     * 自动处理加载状态和错误提示
     */
    protected fun <T> executeRequest(
        request: suspend () -> Result<T>,
        onSuccess: (T) -> Unit,
        onError: ((String) -> Unit)? = null,
        showLoading: Boolean = true
    ) {
        lifecycleScope.launch {
            try {
                if (showLoading) showLoading()
                
                request()
                    .onSuccess { data ->
                        hideLoading()
                        onSuccess(data)
                    }
                    .onFailure { throwable ->
                        hideLoading()
                        val errorMsg = throwable.message ?: "操作失败"
                        if (onError != null) {
                            onError(errorMsg)
                        } else {
                            showError(errorMsg)
                        }
                    }
            } catch (e: Exception) {
                hideLoading()
                val errorMsg = e.message ?: "操作失败"
                if (onError != null) {
                    onError(errorMsg)
                } else {
                    showError(errorMsg)
                }
            }
        }
    }
}

