package com.gh.gamecenter.qa.article.edit

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.common.utils.NotificationHelper
import com.gh.gamecenter.common.utils.TextHelper
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.QuestionsEditTagBinding
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.qa.entity.ArticleDetailEntity
import com.gh.gamecenter.qa.questions.edit.QuestionEditViewModel
import com.google.android.flexbox.FlexboxLayout
import com.lightgame.utils.Util_System_Keyboard
import org.json.JSONObject
import java.util.*

/**
 * Created by khy on 28/04/18.
 */
class ArticleTagsSelectFragment : BaseFragment<String>() {

    private lateinit var mBinding: QuestionsEditTagBinding

    private var mViewModel: ArticleEditViewModel? = null
    private val mAllTags: MutableList<String> = ArrayList() // 所有标签集合

    override fun getLayoutId(): Int {
        return R.layout.questions_edit_tag
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = QuestionsEditTagBinding.bind(mCachedView)
        if (activity != null) mViewModel =
            ViewModelProviders.of(requireActivity()).get(ArticleEditViewModel::class.java)
    }

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

        mViewModel?.defaultTags?.observe(viewLifecycleOwner, Observer {
            initTags()
        })

        mViewModel?.postArticle?.observe(viewLifecycleOwner, Observer {
            if (mViewModel?.openArticleInNewPage == false) {
                val intent = Intent()
                mViewModel?.detailEntity?.me?.articleDraft = null
                intent.putExtra(ArticleDetailEntity::class.java.simpleName, mViewModel?.detailEntity)
                if (mViewModel?.detailEntity == null) {
                    tryWithDefaultCatch {
                        intent.putExtra("article_id", JSONObject(it).optString("_id"))
                        intent.putExtra("community_id", mViewModel?.mSelectCommunityData?.id)
                    }
                }
                activity?.setResult(Activity.RESULT_OK, intent)
            } else {
                activity?.setResult(Activity.RESULT_OK)
                val articleId = mViewModel?.detailEntity?.id ?: JSONObject(it).getString("_id")
                val intent = ArticleDetailActivity.getIntent(
                    requireContext(),
                    mViewModel?.mSelectCommunityData!!,
                    articleId, mEntrance, "撰写文章"
                )
                startActivity(intent)
            }
            toast("发布成功")
            activity?.finish()
            AppExecutor.uiExecutor.executeWithDelay(Runnable {
                NotificationHelper.showNotificationHintDialog(NotificationUgc.ARTICLE)
            }, 1000)
        })

        mBinding.questionsEditTagAdd.setOnClickListener {
            if (mViewModel?.selectedTags?.size!! < QuestionEditViewModel.QUESTION_TAG_MAX_COUNT) {
                showAddTagDialog()
            } else {
                toast(R.string.questionsdetail_max_tag_hint)
            }
        }
//        mViewModel?.getDefaultTag()
    }

    fun publishArticle(isOriginal: Boolean = false) {
        mViewModel?.postArticle(isOriginal)
    }


    private fun initTags() {
        // 添加标签
        val mDefaultTag = mViewModel?.defaultTags?.value ?: ArrayList()

        if (mViewModel?.detailEntity == null) {
            val mTitleTag = (mViewModel?.titleTags?.value ?: ArrayList()) as MutableList
            // 添加默认标签(如果标题标签与默认标签重复则选中)
            for (s in mDefaultTag.reversed()) {
                val contains = mTitleTag.contains(s)
                addTag(s, contains)
                if (contains) mTitleTag.remove(s)
            }
            // 未匹配到默认标签的默认选中在前排
            for (s in mTitleTag) {
                addTag(s, true)
            }
        } else {
            val tags = mViewModel?.detailEntity?.tags ?: ArrayList()
            for (s in mDefaultTag) {
                if (!tags.contains(s))
                    addTag(s, false)
            }
            for (s in tags.reversed()) {
                addTag(s, true)
            }
        }
    }

    private fun showAddTagDialog() {
        view?.visibility = View.GONE
        (requireActivity() as ArticleEditActivity).closeExtendedKeyboard()
        val dialog = Dialog(requireContext())
        val view = View.inflate(context, R.layout.dialog_add_new_label, null)
        val input = view.findViewById<EditText>(R.id.content)
        input.setSelection(input.text.length)
        input.filters = arrayOf(TextHelper.getFilter(10, "标签最多10个字"))
        // 取消按钮
        view.findViewById<TextView>(R.id.cancel).setOnClickListener { dialog.dismiss() }
        // 确定按钮
        view.findViewById<TextView>(R.id.confirm).setOnClickListener {
            if (!TextUtils.isEmpty(input.text.toString().trim())) {
                addTag(input.text.toString().trim(), true)
                dialog.dismiss()
            } else {
                toast(R.string.vote_empty_hint)
            }
        }
        dialog.setOnDismissListener {
            this.view?.visibility = View.VISIBLE
            requireActivity().currentFocus?.clearFocus()
//            (requireActivity() as ArticleEditActivity).controlAddLabelContainer()
        }
        dialog.setCancelable(false)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(view)
        dialog.show()
        mBaseHandler.postDelayed({ Util_System_Keyboard.showSoftKeyboard(context, input) }, 300)
    }

    private fun addTag(tag: String, isSelect: Boolean) {
        if (isSelect && mAllTags.contains(tag)) { // 标签已存在
            if (!mViewModel?.selectedTags?.contains(tag)!!) { // 标签已存在且未选择
                for (i in 0 until mBinding.questionsEditTag.childCount) {
                    val tagView = mBinding.questionsEditTag.getChildAt(i) as TextView
                    val text = tagView.text
                    if (text != null && text.toString() == tag) {
                        mViewModel?.selectedTags?.add(tag)
                        mViewModel?.selectedTagsChange?.postValue(true)
                        tagView.setBackgroundResource(R.drawable.bg_article_edit_label_select)
                        tagView.setTextColor(ContextCompat.getColor(requireContext(), R.color.theme_font))
                    }
                }
            }
            toast("标签已存在")
            return
        }

        val view = LayoutInflater.from(context).inflate(R.layout.questionsdedit_tag_item, null)
        val tagTv = view as TextView
        tagTv.text = tag
        val params = FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 28f.dip2px())
        tagTv.layoutParams = params
        mBinding.questionsEditTag.addView(view, 0)

        tagTv.setOnClickListener {
            if (mViewModel?.selectTag(tagTv.text.toString())!!) {
                tagTv.setBackgroundResource(R.drawable.bg_article_edit_label_select)
                tagTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.theme_font))
            } else {
                tagTv.setBackgroundResource(R.drawable.bg_article_edit_label_unselect)
                tagTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.text_subtitle))
            }
        }

        if (isSelect) {
            mViewModel?.selectedTags?.add(tag)
            mViewModel?.selectedTagsChange?.postValue(true)
            tagTv.setBackgroundResource(R.drawable.bg_article_edit_label_select)
            tagTv.setTextColor(ContextCompat.getColor(requireContext(), R.color.theme_font))
        }
        mAllTags.add(tag)
    }


    companion object {
        fun getInstance(): ArticleTagsSelectFragment {
            return ArticleTagsSelectFragment()
        }
    }
}