package com.gh.common.util

import android.annotation.SuppressLint
import android.app.Dialog
import android.preference.PreferenceManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.ReportReasonAdapter
import com.gh.gamecenter.common.constant.CommonConsts
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.common.view.VerticalItemDecoration
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogReportReasonBinding
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

object BbsReportHelper {

    fun showReportDialog(contentId: String) {
        val sp = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance())
        val suggestion: SettingsEntity.Suggestion? =
            sp.getString(CommonConsts.SUGGESTION_HINT_TYPE, null)?.toObject()
        val reportList = suggestion?.report ?: return

        CurrentActivityHolder.getCurrentActivity()?.apply {
            if (this.isFinishing) return@apply

            val dialog = Dialog(this, com.gh.gamecenter.common.R.style.DialogWindowTransparent)
            val binding: DialogReportReasonBinding =
                DialogReportReasonBinding.inflate(LayoutInflater.from(this))
            val reportReasonAdapter = ReportReasonAdapter(
                this, reportList as ArrayList<String>
            ) { reason ->
                if (reason == "其他原因") {
                    binding.reasonTitle.setText(R.string.report_reason_other_title)
                    binding.normalReasonContainer.visibility = View.GONE
                    binding.otherReasonContainer.visibility = View.VISIBLE
                } else {
                    postReport(contentId, json {
                        "reason" to reason
                    })
                    dialog.cancel()
                }
            }
            binding.reasonRv.layoutManager = LinearLayoutManager(this)
            binding.reasonRv.addItemDecoration(
                VerticalItemDecoration(
                    this,
                    1f,
                    false,
                    com.gh.gamecenter.common.R.color.ui_background
                )
            )
            binding.reasonRv.adapter = reportReasonAdapter

            binding.negativeBtn.setOnClickListener { v ->
                binding.reasonTitle.setText(R.string.report_reason_title)
                binding.normalReasonContainer.visibility = View.VISIBLE
                binding.otherReasonContainer.visibility = View.GONE
            }

            binding.positiveBtn.setOnClickListener { v ->
                if (TextUtils.isEmpty(
                        binding.otherReasonEt.text.toString().trim()
                    )
                ) {
                    ToastUtils.showToast("请填写举报原因")
                } else {
                    postReport(contentId, json {
                        "reason" to "其它"
                        "description" to binding.otherReasonEt.text.toString()
                    })

                    dialog.cancel()
                }
            }

            binding.otherReasonEt.doOnTextChanged { text, start, before, count ->
                val tvCount: Int = text.toString().length
                if (tvCount >= 500) {
                    binding.tvCount.setTextColor(com.gh.gamecenter.common.R.color.secondary_red.toColor(binding.tvCount.context))
                }
                binding.tvCount.text = "$tvCount/500"
            }

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
            dialog.setContentView(binding.root)
            dialog.show()
        }
    }

    @SuppressLint("CheckResult")
    private fun postReport(contentId: String, reportContent: JSONObject) {
        RetrofitManager.getInstance()
            .api
            .postBbsReport(contentId, reportContent.toRequestBody())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    ToastUtils.toast("举报成功")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    if (exception is HttpException) {
                        ErrorHelper.handleError(
                            HaloApp.getInstance().application,
                            exception.response().errorBody()?.string()
                        )
                    }
                }
            })
    }

}