package com.gh.gamecenter.discovery.interestedgame

import android.app.Activity
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.viewModels
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.FragmentInterestedGameBinding
import com.gh.gamecenter.entity.InterestedGameEntity
import com.gh.gamecenter.entity.InterestedGameEntity.TypeTag.Tag
import com.gh.gamecenter.entity.InterestedGamePostEntity
import com.gh.gamecenter.eventbus.EBDiscoverChanged
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray

class InterestedGameFragment : ToolbarFragment() {

    private val mViewModel: InterestedGameViewModel by viewModels()
    private val mBinding by lazy { FragmentInterestedGameBinding.inflate(layoutInflater) }
    private val mFrequencyViewList by lazy {
        listOf(
            mBinding.frequencyOne,
            mBinding.frequencyTwo,
            mBinding.frequencyThree
        )
    }
    private val mConditionViewList by lazy {
        listOf(
            mBinding.conditionOne,
            mBinding.conditionTwo
        )
    }
    private val mTendencyViewList by lazy {
        listOf(
            mBinding.tendencyOne,
            mBinding.tendencyTwo,
            mBinding.tendencyThree
        )
    }
    private val mFrequencyList by lazy {
        listOf(
            "daily",
            "holiday",
            "sometime"
        )
    }
    private val mConditionList by lazy {
        listOf(
            "new",
            "old"
        )
    }
    private val mTendencyList by lazy {
        listOf(
            "single",
            "friend",
            "others"
        )
    }
    private var mCurrentFrequencyIndex = -1
    private var mCurrentConditionIndex = -1
    private var mCurrentTendencyIndex = -1
    private val mSelectedTagViewList = arrayListOf<View>()
    private var mDialogStayTime = 0L

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

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

    override fun onParentActivityFinish() {
        super.onParentActivityFinish()
        val frequency =
            if (mCurrentFrequencyIndex == -1) "" else mFrequencyViewList[mCurrentFrequencyIndex].text.toString()
        val prefer =
            if (mCurrentConditionIndex == -1) "" else mConditionViewList[mCurrentConditionIndex].text.toString()
        val tendency = if (mCurrentTendencyIndex == -1) "" else mTendencyViewList[mCurrentTendencyIndex].text.toString()
        val tagIdArray = JSONArray(mViewModel.getSelectedTagIdList())
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        NewFlatLogUtils.logInterestedGamePageExit(
            frequency,
            prefer,
            tendency,
            tagIdArray,
        )
        NewFlatLogUtils.logInterestedGamePageBrowse(
            frequency,
            prefer,
            tendency,
            tagIdArray,
            stayTime
        )
    }

    private fun initObserver() {
        mViewModel.interestedGameData.observeNonNull(this) {
            initStatus(it)
        }
        mViewModel.postResult.observeNonNull(this) {
            if (it) {
                toast("已根据你的偏好优化推荐机制~")
                SPUtils.setBoolean(Constants.SP_DISCOVER_FORCE_REFRESH, true)
                EventBus.getDefault().post(EBDiscoverChanged())
                requireActivity().setResult(Activity.RESULT_OK)
                requireActivity().finish()
            } else {
                toast("保存失败")
            }
        }
        mViewModel.selectedTagLisLiveData.observeNonNull(this) {
            removeAllTagView()
            it.forEach { tag ->
                addTagView(tag)
            }
        }
    }

    private fun removeAllTagView() {
        mSelectedTagViewList.clear()
        if (mBinding.typeFlexBox.childCount > 1) {
            mBinding.typeFlexBox.removeViews(1, mBinding.typeFlexBox.childCount - 1)
        }
    }

    private fun initView() {
        mBinding.run {
            typeFlexBox.addView(getAddTypeView())
            mFrequencyViewList.forEachIndexed { index, view ->
                view.setOnClickListener {
                    if (mCurrentFrequencyIndex != index) {
                        mViewModel.isModify = true
                        mCurrentFrequencyIndex = index
                        updateViewList(mFrequencyViewList, index)
                    }
                }
            }
            mConditionViewList.forEachIndexed { index, view ->
                view.setOnClickListener {
                    if (mCurrentConditionIndex != index) {
                        mViewModel.isModify = true
                        mCurrentConditionIndex = index
                        updateViewList(mConditionViewList, index)
                    }
                }
            }
            mTendencyViewList.forEachIndexed { index, view ->
                view.setOnClickListener {
                    if (mCurrentTendencyIndex != index) {
                        mViewModel.isModify = true
                        mCurrentTendencyIndex = index
                        updateViewList(mTendencyViewList, index)
                    }
                }
            }
            saveBtn.setOnClickListener {
                postInterestedGameData()
            }
        }
    }

    private fun initStatus(entity: InterestedGameEntity) {
        mCurrentFrequencyIndex = mFrequencyList.indexOf(entity.playFrequency)
        mCurrentConditionIndex = mConditionList.indexOf(entity.gameCondition)
        mCurrentTendencyIndex = mTendencyList.indexOf(entity.playType)
        updateViewList(mFrequencyViewList, mCurrentFrequencyIndex)
        updateViewList(mConditionViewList, mCurrentConditionIndex)
        updateViewList(mTendencyViewList, mCurrentTendencyIndex)

        val frequency =
            if (mCurrentFrequencyIndex == -1) "" else mFrequencyViewList[mCurrentFrequencyIndex].text.toString()
        val prefer =
            if (mCurrentConditionIndex == -1) "" else mConditionViewList[mCurrentConditionIndex].text.toString()
        val tendency = if (mCurrentTendencyIndex == -1) "" else mTendencyViewList[mCurrentTendencyIndex].text.toString()
        NewFlatLogUtils.logInterestedGamePageEnter(
            frequency,
            prefer,
            tendency,
            JSONArray(entity.tags)
        )
    }

    private fun updateViewList(list: List<CheckedTextView>, selectedIndex: Int) {
        if (selectedIndex == -1) return

        list.forEachIndexed { index, view ->
            view.isChecked = index == selectedIndex
        }

        setSaveBtnStatus()
    }

    private fun getAddTypeView(): View {
        return TextView(requireContext()).apply {
            layoutParams = ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                32F.dip2px()
            ).apply { topMargin = 8F.dip2px() }
            setPadding(12F.dip2px(), 0, 12F.dip2px(), 0)
            background = R.drawable.bg_shape_2496ff_alpha_10_radius_8.toDrawable(requireContext())
            gravity = Gravity.CENTER
            setDrawableStart(R.drawable.ic_interested_game_add)
            compoundDrawablePadding = 4F.dip2px()
            setTextColor(R.color.theme_font.toColor(requireContext()))
            textSize = 12F
            text = "添加类型"
            setOnClickListener {
                if (mViewModel.getTypeTags().isNotEmpty()) {
                    InterestedGameTypeDialogFragment.show(requireActivity() as AppCompatActivity, mViewModel) {
                        val tagIdArray = JSONArray(mViewModel.getSelectedTagIdList())
                        val stayTime = (System.currentTimeMillis() - mDialogStayTime) / 1000
                        NewFlatLogUtils.logInterestedGameTypeDialogClose(tagIdArray)
                        NewFlatLogUtils.logInterestedGameTypeDialogBrowse(tagIdArray, stayTime)
                    }
                    mDialogStayTime = System.currentTimeMillis()
                    NewFlatLogUtils.logInterestedGameTypeDialogShow(JSONArray(mViewModel.getSelectedTagIdList()))
                }
            }
        }
    }

    private fun addTagView(tag: Tag) {
        val tagView = TextView(requireContext()).apply {
            layoutParams = ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                32F.dip2px()
            ).apply {
                topMargin = 8F.dip2px()
                leftMargin = 8F.dip2px()
            }
            setPadding(12F.dip2px(), 0, 12F.dip2px(), 0)
            background = R.drawable.border_round_transparent_stroke_divider_radius_8.toDrawable(requireContext())
            gravity = Gravity.CENTER
            setDrawableEnd(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_interested_game_tag_delete))
            compoundDrawablePadding = 4F.dip2px()
            setTextColor(R.color.text_subtitle.toColor(requireContext()))
            textSize = 12F
            text = tag.name
            setOnClickListener {
                removeTagView(tag)
                mViewModel.decreaseSelectedCount()
                mViewModel.removeTag(tag)
                mViewModel.isModify = true
                setSaveBtnStatus()
            }
        }
        mSelectedTagViewList.add(tagView)
        mBinding.typeFlexBox.addView(tagView)
        setSaveBtnStatus()
    }

    private fun removeTagView(tag: Tag) {
        val index = mViewModel.getTagIndex(tag)
        if (index < mSelectedTagViewList.size) {
            mBinding.typeFlexBox.removeView(mSelectedTagViewList[index])
            mSelectedTagViewList.removeAt(index)
        }
    }

    private fun isAllOptionSelected(): Boolean {
        return listOf(mCurrentFrequencyIndex, mCurrentConditionIndex, mCurrentTendencyIndex).all { it != -1 }
                && mViewModel.getSelectedTagList().isNotEmpty()
    }

    private fun setSaveBtnStatus() {
        mBinding.saveBtn.alpha = if (isAllOptionSelected()) 1.0F else 0.4F
    }

    override fun onBackPressed(): Boolean {
        if (mViewModel.isModify) {
            showSaveDialog()
            return true
        }
        return super.onBackPressed()
    }

    private fun showSaveDialog() {
        DialogHelper.showDialog(
            requireContext(),
            "提示",
            "是否保存本次的修改？",
            "保存",
            "取消",
            { postInterestedGameData() },
            { requireActivity().finish() },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun postInterestedGameData() {
        if (!isAllOptionSelected()) {
            toast("请完善你的游戏偏好")
            return
        }
        val postEntity = InterestedGamePostEntity(
            mFrequencyList[mCurrentFrequencyIndex],
            mConditionList[mCurrentConditionIndex],
            mTendencyList[mCurrentTendencyIndex],
            mViewModel.getSelectedTagIdList()
        )
        mViewModel.postInterestedGameData(postEntity)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.run {
            typeFlexBox.removeAllViews()
            typeFlexBox.addView(getAddTypeView())
            mViewModel.getSelectedTagList().forEach { tag ->
                addTagView(tag)
            }
        }
    }
}
