package com.gh.vspace

import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.text.InputFilter
import android.text.Spanned
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.ViewModel
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogVgameFeedbackBinding
import com.gh.gamecenter.databinding.ItemVfeedbackOptionBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import com.lightgame.utils.toast.ToastHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.parcelize.Parcelize
import okhttp3.ResponseBody
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.HttpException

class VFeedbackDialogFragment : BaseDialogFragment() {

    private var mGame: GameEntity? = null
    private var mTagList: List<FeedbackTag>? = null
    private val mBinding by lazy { DialogVgameFeedbackBinding.inflate(layoutInflater) }
    private val mViewModel: VFeedbackViewModel by lazy { viewModelProvider() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mTagList = arguments?.getParcelableArrayList(KEY_TAG_LIST)

        mGame = arguments?.getParcelable(KEY_GAME)

        if (mGame == null) {
            Utils.log("遇到内部异常")
            dismissAllowingStateLoss()
        }

        mGame!!.let {
            mBinding.gameIconIv.displayGameIcon(it)
            mBinding.gameNameTv.text = it.name
        }
        mBinding.closeIv.enlargeTouchArea()
        mBinding.closeIv.setOnClickListener {
            dismissAllowingStateLoss()
        }


        mBinding.feedbackEt.filters = arrayOf(object : InputFilter {
            override fun filter(
                source: CharSequence?,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence {
                val count = dest?.count { !it.isWhitespace() } ?: 0
                if(count >= 500){
                    ToastHelper.showToast(requireContext(), "最多输入500个字")
                    return ""
                }else{
                    return source?:""
                }
            }
        })
        mBinding.feedbackEt.doOnTextChanged { _, _, _, _ ->
            updateSubmitButton()
        }
        mBinding.dontShowAgainTv.enlargeTouchArea()
        mBinding.dontShowAgainTv.setOnClickListener {
            VFeedbackSuppressedSimpleDao().add(mGame?.getUniquePackageName() ?: "")
            dismissAllowingStateLoss()
        }
        mBinding.submitTv.setOnClickListener {
            mGame?.run {
                mViewModel.postFeedback(
                    this,
                    mBinding.feedbackEt.text.toString(),
                    VHelper.getVersionName(it.context),
                    getSelectedTagString()
                )
            }
            NewFlatLogUtils.logHaloFunGameExitDialogSubmitClick(
                mGame?.id ?: "",
                mBinding.feedbackEt.text.toString(),
                JSONArray(getSelectedTagString())
            )
            dismissAllowingStateLoss()
        }
        checkLabel()

        updateSubmitButton()
    }

    private fun getSelectedTagString(): ArrayList<String> {
        val selectedTagList = arrayListOf<String>()
        mTagList?.forEachIndexed { index, tag ->
            if (tag.checked) {
                selectedTagList.add(mTagList!![index].tagName)
            }
        }
        return selectedTagList
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.attributes?.gravity = Gravity.BOTTOM
        val width = DisplayUtils.getScreenWidth()
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
        dialog?.setCanceledOnTouchOutside(true)
    }

    private fun addChildToFlexboxLayout(feedbackTag: FeedbackTag) {
        val binding = ItemVfeedbackOptionBinding.inflate(layoutInflater)
        binding.feedbackTagTv.width = (DisplayUtils.getScreenWidth() - 58F.dip2px()) / 2
        binding.feedbackTagTv.text = feedbackTag.tagName
        if (feedbackTag.checked) {
            binding.feedbackTagTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
            binding.feedbackTagTv.setBackgroundResource(R.drawable.bg_vfeedback_label_selected)
        } else {
            binding.feedbackTagTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext()))
            binding.feedbackTagTv.setBackgroundResource(R.drawable.bg_vfeedback_label)
        }
        binding.root.setOnClickListener {
            feedbackTag.checked = !feedbackTag.checked
            checkLabel()
        }
        mBinding.feedbackFlexbox.addView(binding.root)
    }

    private fun updateSubmitButton() {
        val isTagSelected = mTagList?.any { it.checked } ?: false
        if (mBinding.feedbackEt.text.trim().isNotBlank() || isTagSelected) {
            mBinding.submitTv.isEnabled = true
            mBinding.submitTv.alpha = 1F
        } else {
            mBinding.submitTv.isEnabled = false
            mBinding.submitTv.alpha = 0.6F
        }
    }

    private fun checkLabel() {
        mBinding.feedbackFlexbox.removeAllViews()
        for (tag in mTagList!!) {
            addChildToFlexboxLayout(tag)
        }
        updateSubmitButton()
    }

    companion object {
        private const val KEY_GAME = "game"
        private const val KEY_TAG_LIST = "tag_list"

        @JvmStatic
        fun show(
            activity: AppCompatActivity,
            game: GameEntity?
        ) {
            NewFlatLogUtils.logHaloFunEvent("halo_fun_game_exit_dialog_show")
            VFeedbackDialogFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(KEY_GAME, game)
                    putParcelableArrayList(
                        KEY_TAG_LIST,
                        arrayListOf(
                            FeedbackTag(tagName = "游戏卡顿", tagType = "game_lag"),
                            FeedbackTag(tagName = "游戏闪退", tagType = "game_crash"),
                            FeedbackTag(tagName = "游戏不好玩", tagType = "game_not_fun"),
                            FeedbackTag(tagName = "广告太多了", tagType = "to_many_ad"),
                            FeedbackTag(tagName = "游戏需要更新", tagType = "game_need_update"),
                            FeedbackTag(tagName = "需要实名认证", tagType = "need_name_verification"),
                            FeedbackTag(tagName = "需要登录", tagType = "need_login"),
                            FeedbackTag(tagName = "登录不了", tagType = "can_not_login")
                        )
                    )
                }
            }.show(activity.supportFragmentManager, VFeedbackDialogFragment::class.java.simpleName)
        }
    }

    @Parcelize
    class FeedbackTag(
        val tagName: String = "",
        val tagType: String = "", // 对应后台的 key
        var checked: Boolean = false
    ) : Parcelable

    class VFeedbackViewModel : ViewModel() {

        fun postFeedback(game: GameEntity, message: String, vSpaceVersion: String?, tags: ArrayList<String>) {
            val processedMessage = StringBuilder().apply {
                append("【畅玩问题】")
                append(game.name)
                game.getApk().safelyGetInRelease(0)?.version?.run {
                    append("-$this")
                }

                vSpaceVersion?.apply {
                    append("-$this")
                }

                if (message.isNotBlank()) {
                    append("-$message")
                }
            }
            val json = json {
                "from" to ""
                "ghversion" to PackageUtils.getGhVersionName()
                "channel" to HaloApp.getInstance().channel
                "type" to Build.MODEL
                "sdk" to Build.VERSION.SDK_INT.toString()
                "version" to Build.VERSION.RELEASE
                "source" to HaloApp.getInstance().application.getString(R.string.app_name)
                "jnfj" to MetaUtil.getBase64EncodedIMEI()
                "manufacturer" to Build.MANUFACTURER
                "rom" to MetaUtil.getRom().name + " " + MetaUtil.getRom().versionName

                "suggestion_type" to "游戏问题"
                "game_id" to game.id
                "message" to processedMessage
                "tags" to JSONArray(tags)
            }

            val requestBody = json.toRequestBody()
            RetrofitManager.getInstance().api.postSuggestion(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Response<ResponseBody?>() {
                    override fun onResponse(response: ResponseBody?) {
                        super.onResponse(response)
                        ToastUtils.showToast("感谢您的反馈信息，我们将尽快处理~")
                    }

                    override fun onFailure(e: HttpException?) {
                        e?.response()?.errorBody()?.let {
                            val content = JSONObject(it.string())
                            if (content.getInt("code") == 403052) {
                                ToastUtils.showToast("您已经提交过反馈信息，我们将尽快处理~")
                            }
                        }
                    }
                })
        }

    }

}