package com.gh.gamecenter.qa.questions.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.BaseDialogWrapperFragment
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.util.*
import com.gh.common.util.DialogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.CancelListener
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.databinding.QuestionsEditTagBinding
import com.gh.gamecenter.entity.ErrorEntity
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.entity.Permissions
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.qa.entity.QuestionsDetailEntity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity
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 TagsSelectFragment : BaseFragment<String>() {

    companion object {
        @JvmStatic
        fun getInstance(): TagsSelectFragment {
            return TagsSelectFragment()
        }

        @JvmStatic
        fun getInstance(detail: QuestionsDetailEntity): TagsSelectFragment {
            val bundle = Bundle()
            bundle.putParcelable(QuestionsDetailEntity::class.java.simpleName, detail)
            bundle.putBoolean(EntranceConsts.KEY_QUESTION_MODERATOR_PATCH, true)
            val fragment = TagsSelectFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    private lateinit var mBinding: QuestionsEditTagBinding
    private var mModeratorPatchTagsCallback: OnModeratorPatchTagsCallback? = null

    private var mViewModel: QuestionEditViewModel? = 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)
        val isModeratorPatch = arguments?.getBoolean(EntranceConsts.KEY_QUESTION_MODERATOR_PATCH)
        if (isModeratorPatch != null && isModeratorPatch) {
            mViewModel = ViewModelProviders.of(this).get(QuestionEditViewModel::class.java)
            mViewModel?.isModeratorPatch = isModeratorPatch
            mViewModel?.questionEntity = arguments?.getParcelable(QuestionsDetailEntity::class.java.simpleName)
            mViewModel?.moderatorPostLiveData?.observe(this, Observer {
                if (it?.status == Status.SUCCESS) {
                    if (mViewModel?.questionEntity!!.me.moderatorPermissions.updateQuestionTag == Permissions.REPORTER) {
                        toast("提交成功")
                    } else {
                        toast("操作成功")
                        mViewModel?.questionEntity?.tags = mViewModel?.selectedTags!!
                    }
                    mModeratorPatchTagsCallback?.onPatchTagsSuccess()
                    val fragment = parentFragment
                    (fragment as? BaseDialogWrapperFragment)?.dismissAllowingStateLoss()
                    AppExecutor.uiExecutor.executeWithDelay(Runnable {
                        NotificationHelper.showNotificationHintDialog(NotificationUgc.QUESTION)
                    }, 1000)
                } else if (it?.status == Status.ERROR) {
                    val e = it.exception
                    if (e != null && e.code() == 403) {
                        val string = e.response().errorBody()?.string()
                        val errorJson = JSONObject(string)
                        val errorCode = errorJson.getInt("code")
                        if (errorCode == 403059) {
                            DialogHelper.showDialog(
                                requireContext(), "提交失败", "权限错误，请刷新后重试",
                                "确定", "", {
                                    mModeratorPatchTagsCallback?.onPermissionError()
                                    val fragment = parentFragment
                                    (fragment as? BaseDialogWrapperFragment)?.dismissAllowingStateLoss()
                                }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                            )
                            return@Observer
                        }
                    }
                    toast(R.string.post_failure_hint)
                }
            })
        } else {
            mViewModel = activity?.let { ViewModelProviders.of(it).get(QuestionEditViewModel::class.java) }
            mViewModel?.postLiveData?.observe(this, Observer {
                if (it?.status == Status.SUCCESS) {
                    if (mViewModel?.questionEntity != null) { // 修改问题
                        val data = Intent()
                        data.putExtra(QuestionsDetailEntity::class.java.simpleName, mViewModel?.questionEntity)
                        activity?.setResult(Activity.RESULT_OK, data)
                    } else {
                        val data = JSONObject(it.data ?: "")
                        startActivity(
                            NewQuestionDetailActivity.getIntent(
                                requireContext(), data.getString("_id")
                                    ?: "", mEntrance, "发布问题"
                            )
                        )
                        val intent = Intent()
                        intent.putExtra("question_id", data.optString("_id"))
                        activity?.setResult(Activity.RESULT_OK, intent)
                    }
                    toast("发布成功")
                    activity?.finish()
                    AppExecutor.uiExecutor.executeWithDelay(Runnable {
                        NotificationHelper.showNotificationHintDialog(NotificationUgc.QUESTION)
                    }, 1000)
                } else if (it?.status == Status.ERROR) {
                    val errorString = it.exception?.response()?.errorBody()?.string()
                    val errorEntity = errorString?.toObject<ErrorEntity>()
                    val data = errorEntity?.data
                    when {
                        errorEntity?.code == 403066 -> {
//                            MtaHelper.onEvent("提交相似问题弹窗", CommunityManager.getInstance().community.name, "问题相似-出现弹窗提示")
                            DialogUtils.showCommunityDialog(context,
                                "已有相似问题，去看看？",
                                data?.questionTitle,
                                data?.getFollowCount().toString() + " 关注 · " + data?.answerCount + " 回答",
                                "继续提交", "去看看",
                                object : CancelListener {
                                    override fun onCancel() {
                                        mViewModel?.uploadPicAndPostQuestion(true)
//                                        MtaHelper.onEvent("提交相似问题弹窗", CommunityManager.getInstance().community.name, "问题相似-继续提交")
                                    }
                                }, object : ConfirmListener {
                                    override fun onConfirm() {
//                                        MtaHelper.onEvent("提交相似问题弹窗", CommunityManager.getInstance().community.name, "问题相似-去看看")
                                        val intent = NewQuestionDetailActivity.getIntent(
                                            requireContext(),
                                            data?.questionId ?: "",
                                            mEntrance,
                                            "相似问题"
                                        )
                                        context?.startActivity(intent)
                                    }
                                })
                        }
                        errorEntity?.code == 403067 -> {
//                            MtaHelper.onEvent("提交重复问题弹窗", CommunityManager.getInstance().community.name, "问题重复-出现弹窗提示")
                            DialogUtils.showCommunityDialog(context,
                                "已有重复问题，无法提问",
                                data?.questionTitle,
                                data?.getFollowCount().toString() + " 关注 · " + data?.answerCount + " 回答",
                                null, "去看看", null,
                                object : ConfirmListener {
                                    override fun onConfirm() {
//                                        MtaHelper.onEvent("提交重复问题弹窗", CommunityManager.getInstance().community.name, "问题重复-去看看")
                                        val intent = NewQuestionDetailActivity.getIntent(
                                            requireContext(),
                                            data?.questionId ?: "",
                                            mEntrance,
                                            "重复问题"
                                        )
                                        context?.startActivity(intent)
                                    }
                                })
                        }
                        else -> {
                            ErrorHelper.handleError(requireContext(), errorString, showHighPriorityHint = true)
                        }
                    }
                }
            })
        }
    }

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

        if (mViewModel != null && mViewModel?.isModeratorPatch!!) {
            mBinding.questionsEditTagCancel.text = "取消"
            mBinding.questionsEditTagTitle.text = "修改标签"
        } else {
//            mViewModel?.getDefaultTag(isLoadOver = {
//                initTags()
//            })
        }

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

    fun postQuestion() {
        if (mViewModel?.isModeratorPatch!!) {
            val isSame = mViewModel?.questionEntity?.tags.checkSameFromStringArray(mViewModel?.selectedTags)
            if (isSame) {
                toast("标签没有变化")
            } else {
                DialogHelper.showDialog(
                    requireContext(), "修改标签",
                    if (mViewModel?.questionEntity!!.me.moderatorPermissions.updateQuestionTag == Permissions.REPORTER)
                        "你的操作将提交给小编审核，确定提交吗？" else "你的操作将立即生效，确定提交吗？（你的管理权限为：高级）",
                    "确定", "取消", {
                        mViewModel?.uploadPicAndPatchQuestion(true)
                    }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
            }
        } else {
            mViewModel?.uploadPicAndPostQuestion(false)
        }
    }

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

        val tags = when {
            mViewModel?.questionEntity != null -> {
                mViewModel?.questionEntity?.tags ?: arrayListOf()
            }
            mViewModel?.questionDraftEntity != null -> {
                mViewModel?.questionDraftEntity?.tags ?: arrayListOf()
            }
            else -> {
                arrayListOf()
            }
        }

        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 QuestionEditActivity).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 QuestionEditActivity).controlInsertDetailContainer()
        }
        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)
    }


    fun setPatchTagsCallBack(callback: OnModeratorPatchTagsCallback) {
        mModeratorPatchTagsCallback = callback
    }

    interface OnModeratorPatchTagsCallback {
        fun onPatchTagsSuccess()
        fun onPermissionError()
    }
}