package com.narutohuo.xindazhou.community.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.narutohuo.xindazhou.qrcode.factory.QRCodeManagerFactory

/**
 * 社区Fragment
 * 
 * 显示社区相关功能
 */
class CommunityFragment : Fragment() {

    private val qrCodeManager = QRCodeManagerFactory.getInstance()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 创建布局
        val layout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            gravity = android.view.Gravity.CENTER
            setPadding(32, 32, 32, 32)
        }

        // 标题
        val textView = TextView(requireContext()).apply {
            text = "社区页面"
            textSize = 18f
            gravity = android.view.Gravity.CENTER
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 0, 0, 32)
            }
        }
        layout.addView(textView)

        // 扫码按钮
        val scanButton = Button(requireContext()).apply {
            text = "扫码"
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            setOnClickListener {
                startScanQRCode()
            }
        }
        layout.addView(scanButton)

        return layout
    }

    /**
     * 开始扫码
     */
    private fun startScanQRCode() {
        val activity = requireActivity()
        qrCodeManager.scanQRCode(activity) { response ->
            if (response.success) {
                val qrCodeContent = response.data
                Toast.makeText(
                    requireContext(),
                    "扫码成功：$qrCodeContent",
                    Toast.LENGTH_SHORT
                ).show()
                // TODO: 处理扫码结果
            } else {
                val error = response.errorMessage
                if (error != null) {
                    Toast.makeText(
                        requireContext(),
                        "扫码失败：$error",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
}

