package com.bc_chat.circle.activity.fragment

import android.graphics.Rect
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.bc_chat.bc_base.entity.contact.CommentMine
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.circle.activity.TopicDetailsActivity
import com.bc_chat.circle.activity.UserCircleDetailsActivity
import com.bc_chat.circle.adapetr.CommentMineAdapter
import com.bc_chat.circle.contract.TopicDetailsContract
import com.bc_chat.circle.dataSource.CommentMineDataSource
import com.bc_chat.circle.entity.Emoji
import com.bc_chat.circle.fragment.DynamicFragment
import com.bc_chat.circle.presenter.TopicDetailsPresenter
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.EmojiViewPagerAdapter
import com.bc_chat.contacts.view.EmojiPickerView
import com.zhaohaoting.framework.abs.BaseRecyclerFragment
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.abs.contract.BaseContract
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.mvchelper.mvc.IDataAdapter
import com.zhaohaoting.framework.mvchelper.mvc.OnRefreshEndListener
import com.zhaohaoting.framework.utils.ActivityUtils
import com.zhaohaoting.framework.utils.Check
import com.zhaohaoting.framework.utils.Logger
import com.zhaohaoting.framework.utils.Utils

class CommentMineFragment : BaseRecyclerFragment<CommentMine, List<CommentMine>>(), TopicDetailsContract.View {

    private var type: String = "1"
    private var editText: EditText? = null
    private var ivEmoji: ImageView? = null
    private var emojiView: EmojiPickerView? = null
    private var tvSend: TextView? = null
    private var isShowKeyBoard: Boolean = false //当前键盘是否显示
    private var commentUid: String? = "0"
    private var commentid: String? = "0"
    private var circleId: String? = "0"

    private var expressioLayout: View? = null
    private val mAdapter by lazy {
        CommentMineAdapter(activity, type)
    }

    companion object {
        const val TOPIC_DETAILS = 42
    }

    override fun getPresenter(): BaseContract.BasePresenter {
        return TopicDetailsPresenter(this)
    }

    private var mOnRefreshEndListener: OnRefreshEndListener<List<CommentMine>>? = null

    fun setOnRefreshEndListener(onRefreshEndListener: OnRefreshEndListener<List<CommentMine>>) {
        mOnRefreshEndListener = onRefreshEndListener
    }


    override fun onInit() {
        type = arguments?.getString("type", "1")!!
        mAdapter.addOnItemViewClickListener { vh, view, position ->
            val commentMine = mAdapter.data.get(position)
            when (view?.id) {
                R.id.tv_reply -> {
                    circleId = commentMine.cid
                    commentid = if (type.equals("1")) commentMine.id else commentMine.pid
                    commentUid = commentMine.uid
                    expressioLayout.visible()
                    emojiView.gone()
                    ivEmoji?.isSelected = false
                    handler.postDelayed({
                        if (!isShowKeyBoard) {
                            editText?.requestFocus()
                            editText?.hint = "回复${commentMine.nickname}:"
                            Utils.showSoftInput(activity, editText)
                        }
                    }, 200)
                }
                R.id.iv_photo, R.id.tv_nick -> {
                    ActivityUtils.newInstance(this)
                            .putExtra("cuid", commentMine.uid)
                            .navigation(UserCircleDetailsActivity::class.java)
                }
                else -> {
                    ActivityUtils.newInstance(this)
                            .putExtra("cid", commentMine.cid)
                            .navigation(TopicDetailsActivity::class.java, TOPIC_DETAILS)
                }
            }
        }
        expressioLayout = LayoutInflater.from(activity).inflate(R.layout.comment_bottom_layout, flbottom, true)
        expressioLayout.gone()
        editText = expressioLayout?.findViewById(R.id.edit_text)
        ivEmoji = expressioLayout?.findViewById(R.id.iv_emoji)
        emojiView = expressioLayout?.findViewById(R.id.emoji_view)
        tvSend = expressioLayout?.findViewById(R.id.tv_send)
        rootDataBinding.root.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootDataBinding.root.getWindowVisibleDisplayFrame(rect)
            val height = rootDataBinding.root.rootView.height
            val mainInvisibleHeight = height - rect.bottom
            isShowKeyBoard = if (mainInvisibleHeight > height / 4) {
                expressioLayout.visible()
                if (isShowKeyBoard) return@addOnGlobalLayoutListener
                true
            } else {
                if (!ivEmoji?.isSelected!!) {
                    expressioLayout.gone()
                }
                if (!isShowKeyBoard) return@addOnGlobalLayoutListener
                false
            }
        }
        editText?.setOnTouchListener { v, event ->
            emojiView.gone()
            ivEmoji?.isSelected = false
            handler.postDelayed({
                if (!isShowKeyBoard) {
                    editText?.requestFocus()
                    Utils.showSoftInput(activity, v)
                }
            }, 200)
            return@setOnTouchListener true
        }
        tvSend?.setOnClickListener {
            val content = editText?.text.toString().trim()
            if (!content.isNullOrEmpty() && !circleId.equals("0") && !commentUid.equals("0")) {
                editText?.setText("")
                (presenter as TopicDetailsPresenter).comment(circleId!!, commentUid!!, commentid!!, content, type.toInt())
            }
        }
        emojiView?.setEmojiClickListener(object : EmojiViewPagerAdapter.EmojiClickListener {
            override fun deleteEmoji() {
                if (activity.currentFocus is EditText) {
                    val textView = activity.currentFocus as EditText
                    if (!TextUtils.isEmpty(textView.text)) {
                        val event = KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL)
                        textView.dispatchKeyEvent(event)
                    }
                }
            }

            override fun clickEmoji(emoji: Emoji?) {
                val selectionEnd = editText!!.selectionEnd
                editText!!.text.insert(selectionEnd, emoji?.emojiText)
            }
        })
        ivEmoji?.setOnClickListener {
            Logger.e("setOnClickListener", "setOnClickListener")
            ivEmoji?.isSelected = !ivEmoji?.isSelected!!
            if (ivEmoji?.isSelected!!) {
                Utils.hideInputMethod(activity)
                handler.postDelayed({
                    emojiView.visible()
                }, 200)
            } else {
                handler.postDelayed({
                    Utils.showSoftInput(activity, activity.currentFocus)
                }, 200)
                emojiView.gone()
            }
        }
        mOnRefreshEndListener?.let {
            setOnStateChangeListener(it)
        }
    }

    override fun commentSuccess() {
    }

    override fun likeSuccess(type: Int) {
    }

    override fun deleteSuccess(position: Int) {
    }

    override fun getAdapter(): AbsRecyclerAdapter<CommentMine, List<CommentMine>> = mAdapter

    override fun getDataSource(): IAsyncDataSource<List<CommentMine>> = CommentMineDataSource(type)

    fun dispatchTouchEvent(ev: MotionEvent) {
        val v = activity.currentFocus
        if (Utils.isShouldHideInput(v, ev) && Utils.isShouldHideInput(ivEmoji, ev) && Utils.isShouldHideInput(emojiView, ev) && Utils.isShouldHideInput(tvSend, ev)) {
            Utils.hideInputMethod(activity)
//            if (ivEmoji?.isSelected!!) {
            ivEmoji?.isSelected = false
            emojiView.gone()
            expressioLayout.gone()
//            }
            commentUid = "0"
            commentid = "0"
            circleId = "0"
        }
    }
}