package com.bc_chat.circle.activity

import android.annotation.SuppressLint
import android.databinding.ViewDataBinding
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
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.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.entity.contact.Comment
import com.bc_chat.bc_base.entity.contact.CommentModel
import com.bc_chat.bc_base.utils.*
import com.bc_chat.circle.adapetr.CommentAdapter
import com.bc_chat.circle.contract.TopicDetailsContract
import com.bc_chat.circle.dataSource.CommentDataSource
import com.bc_chat.circle.entity.Emoji
import com.bc_chat.circle.presenter.TopicDetailsPresenter
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.DynamicImageAdapter
import com.bc_chat.contacts.adapter.EmojiViewPagerAdapter
import com.bc_chat.contacts.view.EmojiPickerView
import com.umeng.socialize.utils.DeviceConfig.context
import com.zhaohaoting.framework.abs.BaseRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.abs.presenter.BasePresenter
import com.zhaohaoting.framework.imagepicker.ImagePicker
import com.zhaohaoting.framework.imagepicker.bean.MediaItem
import com.zhaohaoting.framework.imagepicker.ui.ImagePreviewActivity
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ActivityUtils
import com.zhaohaoting.framework.utils.Check
import com.zhaohaoting.framework.utils.Utils
import com.zhaohaoting.framework.utils.format.MsTransformation
import com.zhaohaoting.framework.utils.glid.GlideUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/8/28
 * email：526309416@qq.com
 * desc：
 */
class TopicDetailsActivity : BaseRecyclerActivity<Comment, CommentModel>(), TopicDetailsContract.View {

    private val cid by lazy {
        intent.getStringExtra("cid")
    }
    private val commentId by lazy {
        intent.getStringExtra("commentId")
    }
    private val selection by lazy {
        intent.getStringExtra("selection")
    }

    private val commentAdapter by lazy {
        CommentAdapter(this)
    }
    private val dynamicImageAdapter by lazy {
        DynamicImageAdapter(this)
    }

    private var tvPhoto: ImageView? = null
    private var tvNick: TextView? = null
    private var tvTime: TextView? = null
    private var tvLike: TextView? = null
    private var tvTitle: TextView? = null
    private var tvDesc: TextView? = null
    private var rvImage: RecyclerView? = null
    private val handler = Handler(Looper.getMainLooper())
    private var isShowKeyBoard: Boolean = false //当前键盘是否显示

    private var commentUid: String? = ""
    private var commentid: String? = "0"
    private var commentType = 1 //1-常规评论 2-指定回复评论
    private var userTag: TextView? = null


    override fun getAdapter(): AbsRecyclerAdapter<Comment, CommentModel> = commentAdapter

    override fun getDataSource(): IAsyncDataSource<CommentModel> = CommentDataSource(cid)

    override fun initPresenter(): BasePresenter<*> {
        return TopicDetailsPresenter(this)
    }

    private fun findPositionById(): Int {
        comment?.let {
            it.commentsList?.forEachIndexed { index, comment ->
                comment.list?.map {
                    if (it.id.equals(commentId)) {
                        return index
                    }
                }
                if (comment.id.equals(commentId)) {
                    return index
                }
            }
        }
        return 0
    }

    override fun addHeadViews(adapter: AbsRecyclerAdapter<Comment, CommentModel>?) {
        val view = LayoutInflater.from(this).inflate(R.layout.activity_topic_details, recyclerView, false)
        tvPhoto = view.findViewById(R.id.iv_photo)
        rvImage = view.findViewById(R.id.rv_image)
        tvNick = view.findViewById(R.id.tv_nick)
        tvTime = view.findViewById(R.id.tv_time)
        tvLike = view.findViewById(R.id.tv_like)
        tvTitle = view.findViewById(R.id.tv_title)
        tvDesc = view.findViewById(R.id.tv_desc)
        userTag = view.findViewById(R.id.user_tag)

        adapter?.addHeaderView(view)
        tvLike?.setOnClickListener {
            comment?.let {
                (presenter as TopicDetailsPresenter).like(it.uid, if (it.is_focus == 1) 2 else 1)
            }
        }
        tvPhoto?.setOnClickListener {
            comment?.let {
                ActivityUtils.newInstance(this)
                        .putExtra("cuid", it.uid)
                        .navigation(UserCircleDetailsActivity::class.java)
            }
        }
        tvNick?.setOnClickListener {
            comment?.let {
                ActivityUtils.newInstance(this)
                        .putExtra("cuid", it.uid)
                        .navigation(UserCircleDetailsActivity::class.java)
            }
        }
        rvImage?.setHasFixedSize(true)
        rvImage?.isNestedScrollingEnabled = false
        rvImage?.layoutManager = GridLayoutManager(context, 3)
        rvImage?.adapter = dynamicImageAdapter
    }

    private var editText: EditText? = null
    private var ivEmoji: ImageView? = null
    private var emojiView: EmojiPickerView? = null
    private var tvSend: TextView? = null
    private var comment: CommentModel? = null

    @SuppressLint("ClickableViewAccessibility")
    override fun onInit() {
        isTouchHide = false
        flContent.setBackgroundColor(resources.getColor(R.color.white))
        val view = LayoutInflater.from(this).inflate(R.layout.comment_bottom_layout, flBottom, true)
        editText = view.findViewById(R.id.edit_text)
        ivEmoji = view.findViewById(R.id.iv_emoji)
        emojiView = view.findViewById(R.id.emoji_view)
        tvSend = view.findViewById(R.id.tv_send)

        setOnStateChangeListener { _, result ->
            if (result == null || isFinishing) return@setOnStateChangeListener
            comment = result
            if (!result.imgs.isNullOrEmpty()) {
                val split = result.imgs?.split(",")
                val mediaList = arrayListOf<MediaItem>()
                split?.map {
                    mediaList.add(MediaItem(it, ImagePicker.MEDIA_TYPE_IMAGE))
                }
                dynamicImageAdapter.notifyDataChanged(mediaList, true)
            } else {
                dynamicImageAdapter.notifyDataChanged(null, true)
            }
            GlideUtils.loadCircleImage(this, result.photo, tvPhoto)
            tvNick?.text = result.nickname
            tvTime?.text = MsTransformation.formatTimesBefore1(result.c_time * 1000, System.currentTimeMillis())
            tvTitle?.text = result.title
            tvDesc?.text = result.content
            if (Check.isEmpty(result.label)) {
                userTag.gone()
            } else {
                userTag.visible()
                userTag?.text = result.label
            }
            tvLike?.text = if (result.is_focus == 1) {
                "已关注"
            } else {
                "关注"
            }
            editText?.hint = "回复楼主："
            commentUid = result.uid
            commentid = "0"
            commentType = 1
            hideSoftInput()
            if (result.uid.equals(AppConfig.instance.getUser().userId)) {
                tvLike.gone()
            }
            if (Const.PushMethod.TOPIC_CHILD_COMMENT.equals(selection)) {
                val position = findPositionById()
                if (position == 0) return@setOnStateChangeListener
                recyclerView.smoothScrollToPosition(position + adapter.headerLayoutCount)
                adapter.data.commentsList!![position].isExpand = true
                adapter.notifyDataSetChanged()
                MessageHelper.instance.isChildNewComment = false
            } else if (Const.PushMethod.TOPIC_COMMENT.equals(selection)) {
                val position = findPositionById()
                recyclerView.smoothScrollToPosition(position + adapter.headerLayoutCount)
                MessageHelper.instance.isNewComment = false
            }
        }
        rootLayout.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootLayout.getWindowVisibleDisplayFrame(rect)
            val height = rootLayout.rootView.height
            val mainInvisibleHeight = height - rect.bottom
            isShowKeyBoard = if (mainInvisibleHeight > height / 4) {
                if (isShowKeyBoard) return@addOnGlobalLayoutListener
                true
            } else {
                if (!isShowKeyBoard) return@addOnGlobalLayoutListener
                false
            }
        }
        editText?.setOnTouchListener { v, event ->
            emojiView.gone()
            ivEmoji?.isSelected = false
            handler.postDelayed({
                if (!isShowKeyBoard) {
                    editText?.requestFocus()
                    Utils.showSoftInput(this, v)
                }
            }, 200)
            return@setOnTouchListener false
        }
        tvSend?.setOnClickListener {
            val content = editText?.text.toString().trim()
            if (!content.isNullOrEmpty()) {
                comment?.let {
                    editText?.setText("")
                    (presenter as TopicDetailsPresenter).comment(it.cid, if (Check.isEmpty(commentUid)) it.uid else commentUid!!, commentid!!, content, commentType)
                }
            }
        }
        emojiView?.setEmojiClickListener(object : EmojiViewPagerAdapter.EmojiClickListener {
            override fun deleteEmoji() {
                if (currentFocus is EditText) {
                    val textView = 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 {
            ivEmoji?.isSelected = !ivEmoji?.isSelected!!
            if (ivEmoji?.isSelected!!) {
                Utils.hideInputMethod(this)
                handler.postDelayed({
                    emojiView.visible()
                }, 200)
            } else {
                handler.postDelayed({
                    Utils.showSoftInput(this, currentFocus)
                }, 200)
                emojiView.gone()
            }
        }
        commentAdapter.addOnItemViewClickListener { _: AbsRecyclerAdapter.BaseViewHolder<ViewDataBinding>, view: View, i: Int ->
            val comment1 = adapter.data.commentsList!![i]
            if (view.id == R.id.iv_comment) {
                editText?.hint = "回复%s：".format(comment1.nickname)
                commentUid = comment1.uid
                commentid = comment1.id
                commentType = 1
                editText?.requestFocus()
                Utils.showSoftInput(this, editText)
            } else if (view.id == R.id.iv_photo || view.id == R.id.tv_nick) {
                ActivityUtils.newInstance(this)
                        .putExtra("cuid", comment1.uid)
                        .navigation(UserCircleDetailsActivity::class.java)
            }
        }
        dynamicImageAdapter.addOnItemClickListener { vh, position ->
            ActivityUtils.newInstance(this)
                    .putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, ArrayList(dynamicImageAdapter.data!!))
                    .putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
                    .putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
                    .navigation(ImagePreviewActivity::class.java)
        }
        commentAdapter.setChildItemClickListener(object : CommentAdapter.OnChildItemClickListener {
            override fun deleteItemClik(position: Int) {
                val comment1 = commentAdapter.data.commentsList?.get(position)
                deleteComment(comment1!!, position)
            }

            override fun deleteChildItemClik(position: Int, childPosition: Int) {
                val comment1 = commentAdapter.data.commentsList?.get(position)?.list?.get(childPosition)
                deleteComment(comment1!!, position)
            }

            override fun childItemClick(position: Int, childPosition: Int) {
                val comment1 = adapter.data.commentsList!![position]
                val childComment = comment1.list?.get(childPosition)
                editText?.hint = "回复%s：".format(childComment?.nickname)
                commentUid = childComment?.uid
                commentid = comment1.id
                commentType = 2
                editText?.requestFocus()
                Utils.showSoftInput(this@TopicDetailsActivity, editText)
            }
        })
    }

    fun deleteComment(comment: Comment, position: Int) {
        CustomDialog.Builder(this).setTitle("提示").setMessage("删除评论：%s".format(comment.content)).setNegativeButton("取消", null).setPositiveButton("确定") { dialog, which ->
            (presenter as TopicDetailsPresenter).delete(comment.id, position)
        }.create().show()
    }

    override fun commentSuccess() {
        refresh()
    }

    override fun likeSuccess(type: Int) {
        when (type) {
            1 -> {
                comment?.is_focus = 1
                //关注成功
                tvLike?.text = "已关注"
            }
            2 -> {
                comment?.is_focus = 0
                //取消关注成功
                tvLike?.text = "关注"
            }
        }
    }

    override fun deleteSuccess(position: Int) {
        refresh()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (Utils.isShouldHideInput(v, ev) && Utils.isShouldHideInput(ivEmoji, ev) && Utils.isShouldHideInput(emojiView, ev) && Utils.isShouldHideInput(tvSend, ev)) {
                Utils.hideInputMethod(this)
                if (ivEmoji?.isSelected!!) {
                    ivEmoji?.isSelected = false
                    emojiView.gone()
                }
                editText?.hint = "回复楼主："
                commentUid = comment?.uid
                commentid = "0"
                commentType = 1
            }
            return super.dispatchTouchEvent(ev)
        }
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }
}
