package com.gh.gamecenter.feedback.view.suggest

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.choosepic.ChoosePicAdapter
import com.gh.gamecenter.feature.view.dialog.SelectGameDialogFragment
import com.gh.gamecenter.feature.view.dialog.SelectGameViewModel
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.databinding.FragmentSuggestFunctionBinding
import com.gh.gamecenter.feedback.entity.ContactType
import com.gh.gamecenter.feedback.utils.NewFlatLogUtils

/***
 * 意见反馈-求游戏功能
 */
class SuggestFunctionFragment : SuggestAppFragment() {
    private lateinit var mBinding: FragmentSuggestFunctionBinding
    private lateinit var mSelectGameViewModel: SelectGameViewModel
    private var mIsFunctionTypeExpand = false

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View =
        FragmentSuggestFunctionBinding.inflate(layoutInflater, null, false).apply { mBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSelectGameViewModel = viewModelProviderFromParent()
    }

    override fun getSuggestType(): String = SuggestType.FUNCTION.type

    override fun initView() {
        mBinding.run {
            function.titleTv.text = Html.fromHtml(getString(R.string.suggestion_function))
            selectGame.titleTv.text = Html.fromHtml(getString(R.string.suggestion_select_game))
            problemDes.titleTv.text = Html.fromHtml(getString(R.string.suggestion_problem_des))

            function.divider.visibility = View.GONE
            function.expandIv.setOnClickListener {
                function.root.layoutParams = function.root.layoutParams.apply {
                    height = if (mIsFunctionTypeExpand) 48F.dip2px() else LinearLayout.LayoutParams.WRAP_CONTENT
                }
                function.expandIv.rotation = if (mIsFunctionTypeExpand) 0F else 180F
                mIsFunctionTypeExpand = !mIsFunctionTypeExpand
            }

            selectGame.root.setOnClickListener {
                SelectGameDialogFragment.show(
                    (requireActivity() as AppCompatActivity),
                    this@SuggestFunctionFragment::class.java.name
                )
            }

            problemDes.run {
                editText.doOnTextChanged { text, _, _, _ ->
                    val count = text?.count { !it.isWhitespace() } ?: 0
                    problemDes.countTv.text = "${count}/300"
                }
                if (mSuggestContent.isNotEmpty()) {
                    editText.setText(mSuggestContent)
                    editText.setSelection(editText.text.length)
                }
            }

            uploadPic.run {
                picRv.layoutManager = mUploadPicLayoutManager
                mPicAdapter = ChoosePicAdapter(requireContext(), mUploadPicListClickListener)
                picRv.adapter = mPicAdapter
            }

            contact.contactTv.setOnClickListener {
                showContactOptionPopup(it) { name ->
                    mViewModel.contactType = ContactType.getContactTypeByName(name)
                    contact.contactTv.text = name
                }
            }

            suggestPostBtn.setOnClickListener {
                val isSelectedFunctionType = mViewModel.selectedProblemType != null
                val isSelectedGame = mViewModel.selectedGameInfo.isNotEmpty()
                val isProblemDesNotEmpty = problemDes.editText.text.trim().isNotEmpty()

                if (function.root.visibility == View.VISIBLE && !isSelectedFunctionType) {
                    toast("请选择功能需求")
                    return@setOnClickListener
                }

                if (!isSelectedGame) {
                    toast("请选择游戏")
                    return@setOnClickListener
                }

                if (!isProblemDesNotEmpty) {
                    toast("请填写问题描述")
                    return@setOnClickListener
                }

                ifLogin("意见反馈-${getSuggestType()}") {
                    NewFlatLogUtils.logFeedbackCommit(getSuggestType(), mViewModel.selectedProblemType?.name ?: "", "")

                    mPostDialog = WaitingDialogFragment.newInstance(getString(R.string.dialog_feedback_doing))
                    mPostDialog?.show(childFragmentManager, null)

                    val fileList = mPicAdapter?.fileList
                    if (fileList.isNullOrEmpty()) {
                        mViewModel.postNormalSuggestion(
                            contact.contactEt.text.toString().trim(),
                            problemDes.editText.text.toString().trim()
                        )
                    } else {
                        mViewModel.uploadPicAndPostNormalSuggestion(
                            fileList,
                            mPostDialog,
                            contact.contactEt.text.toString().trim(),
                            problemDes.editText.text.toString().trim()
                        )
                    }
                }
            }
        }
    }

    override fun observerData() {
        mViewModel.problemTypeLiveData.observeNonNull(this) {
            mBinding.function.flexbox.removeAllViews()
            mProblemTypeItemViewList.clear()
            mBinding.function.root.goneIf(it.size < 2)
            it.forEachIndexed { index, problemType ->
                val item = getProblemTypeItemView(problemType)
                mProblemTypeItemViewList.add(item)
                mBinding.function.flexbox.addView(item)
                item.tag = problemType.name
                toggleHighlightedView(item, mViewModel.selectedProblemType?.id == problemType.id)
                item.setOnClickListener {
                    mProblemTypeCheckedIndex = if (mViewModel.selectedProblemType?.id == problemType.id) -1 else index
                    mViewModel.selectedProblemType =
                        if (mViewModel.selectedProblemType?.id == problemType.id) null else problemType
                    mViewModel.selectedProblemSet.clear()
                    toggleHighlightedView(item, mViewModel.selectedProblemType?.id == problemType.id)
                    for (view in mProblemTypeItemViewList) {
                        if (view != item) toggleHighlightedView(view, false)
                    }
                }
            }
            mBinding.function.flexbox.post {
                mBinding.function.expandIv.goneIf(mBinding.function.flexbox.flexLines.size < 2)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && requestCode == SelectGameDialogFragment.REQUEST_CODE_SELECT_GAME && resultCode == Activity.RESULT_OK) {
            mBinding.selectGame.selectTv.text = data.getStringExtra(EntranceConsts.KEY_GAME_NAME)
            mViewModel.selectedGameName = data.getStringExtra(EntranceConsts.KEY_GAME_NAME) ?: ""
            mViewModel.selectedGameInfo = data.getStringExtra(EntranceConsts.KEY_GAME_INFO) ?: ""
        }
    }

    override fun handleBackPressed(): Boolean {
        mBinding.run {
            if (mViewModel.selectedProblemType != null ||
                mViewModel.selectedGameName.isNotEmpty() ||
                problemDes.editText.text.isNotEmpty() ||
                !mPicAdapter?.fileList.isNullOrEmpty() ||
                contact.contactEt.text.isNotEmpty()
            ) {
                DialogHelper.showDialog(
                    requireContext(), "提示",
                    "确定放弃反馈吗？", "继续反馈", "放弃", cancelClickCallback = {
                        mIsBackConfirm = true
                        requireActivity().onBackPressed()
                    }, extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                )
                return true
            } else {
                return false
            }
        }
    }

    override fun onDarkModeChanged() {
        for ((index, view) in mProblemTypeItemViewList.withIndex()) {
            toggleHighlightedView(view, index == mProblemTypeCheckedIndex)
        }
    }
}