package com.feasycom.feasybeacon.ui.about

import androidx.activity.viewModels
import com.feasycom.feasybeacon.R
import com.feasycom.feasybeacon.databinding.ActivityFeedbackBinding
import com.feasycom.feasybeacon.logic.BeaconRepository.FEEDBACK_ADVICE
import com.feasycom.feasybeacon.logic.BeaconRepository.FEEDBACK_BUG
import com.feasycom.feasybeacon.logic.BeaconRepository.FEEDBACK_COOPERATION
import com.feasycom.feasybeacon.logic.BeaconRepository.FEEDBACK_UI
import com.feasycom.feasybeacon.ui.base.BaseActivity
import com.feasycom.feasybeacon.ui.dialog.LoadDialogFragment
import com.feasycom.feasybeacon.ui.dialog.TipsDialog

/**
 * 创建反馈活动
 */

class FeedbackActivity : BaseActivity<ActivityFeedbackBinding>() {

    private lateinit var waitDialog: LoadDialogFragment

    // 声明延迟初始化的 viewModel 属性，并通过 viewModels() 扩展函数初始化
    private val viewModel: FeedbackViewModel by viewModels()

    // 获取视图绑定对象的方法
    override fun getViewBinding() = ActivityFeedbackBinding.inflate(layoutInflater)

    // 初始化视图的方法
    override fun initView() {
        // 设置标题和返回按钮的文本
        binding.header.apply {
            headerTitle.text = getString(R.string.feedback)
            headerLeft.text = getString(R.string.feedback_left)
            headerLeft.setOnClickListener { finish() }
        }
    }

    // 初始化事件的方法
    override fun initEvent() {
        // 设置提交按钮的点击事件
        binding.submit.setOnClickListener {
            // 获取反馈文本并检查是否为空
            val feedbackText = binding.dataEv.text.toString().trim()
            if (feedbackText.isNotEmpty()) {
                // 显示等待对话框
                waitDialog = LoadDialogFragment(getString(R.string.feedback_status))
                waitDialog.show(supportFragmentManager, "feedback")

                // 根据选中的单选按钮确定反馈类型
                val feedbackType = when (binding.radioGroup.checkedRadioButtonId) {
                    R.id.proposal -> FEEDBACK_ADVICE
                    R.id.abnormal_function -> FEEDBACK_BUG
                    R.id.interface_abnormality -> FEEDBACK_UI
                    R.id.cooperation -> FEEDBACK_COOPERATION
                    else -> FEEDBACK_ADVICE
                }
                // 调用 ViewModel 的 feedback 方法提交反馈
                viewModel.feedback(feedbackText, feedbackType)
            }
        }

        // 观察 ViewModel 中的 LiveData，处理反馈提交结果
        viewModel.mFeedbackResponseBodyLiveData.observe(this) { response ->
            // 关闭等待对话框
            waitDialog.dismiss()
            // 根据提交结果显示提示对话框
            val messageResId = if (response.isSuccess) R.string.feedback_success else R.string.feedback_failure
            val tipsDialog = TipsDialog(this)
            tipsDialog.setInfo(getString(messageResId), binding.dataEv)
            tipsDialog.show()
        }
    }
}
