package com.bc_chat.im.activity

import android.content.Intent
import android.net.Uri
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.contacts.dataSource.ChatPictureDataSource
import com.bc_chat.im.R
import com.bc_chat.im.adapter.ChatPictureAdapter
import com.bc_chat.im.entity.TimeMessage
import com.zhaohaoting.framework.abs.BaseRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.message.ImageMessage
import io.rong.message.SightMessage
import org.jetbrains.anko.collections.forEachReversedByIndex


/**
 * Created by zhaoting on 2019/3/2.
 * Desc：聊天图片
 */

@Route(path = RouteConfig.CHAT_PICTURE_ACTIVITY)
class ChatPictureActivity : BaseRecyclerActivity<TimeMessage, List<TimeMessage>>(), ChatPictureAdapter.OnSelectListener, Observer<String> {

    private val conversationType by lazy {
        Conversation.ConversationType.valueOf(intent.getStringExtra("conversationType"))
    }
    private val mTargetId by lazy {
        intent.getStringExtra("mTargetId")
    }
    private var status: Int? = STATUS_DEFAULT // 默认为浏览状态  菜单显示选择

    private var ivPicDel: ImageView? = null
    private var ivPicShare: ImageView? = null
    private var tvSelectCount: TextView? = null
    private var bottomView: View? = null

    private val selectList: ArrayList<Message> = arrayListOf()

    companion object {
        const val STATUS_DEFAULT = 0
        const val STATUS_SELECT = 1
    }

    override fun getLayoutManager(): RecyclerView.LayoutManager {
        val gridLayoutManager = GridLayoutManager(this, 4)
        gridLayoutManager.spanSizeLookup = this.spanSize
        return gridLayoutManager
    }

    private val spanSize = object : GridLayoutManager.SpanSizeLookup() {

        override fun getSpanSize(p0: Int): Int {
            val itemViewType = adapter?.getItemViewType(p0)
            return if (itemViewType == ChatPictureAdapter.ITEM_TIME) {//判断当前类型是否是EmptyView
                4
            } else {
                1
            }
        }
    }
    private var videoTimeMessage: TimeMessage? = null
    override fun onItemClick(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val message = adapter.data[position]
        val content = message.message?.content
        if (content is ImageMessage) {
            val intent = Intent("io.rong.imkit.intent.action.picturepagerview")
            intent.setPackage(packageName)
            intent.putExtra("message", message.message)
            startActivity(intent)
        } else if (content is SightMessage) {
            videoTimeMessage = message;
            judgePermission(Const.Permission.Key.STORAGE, *Const.Permission.Value.STORAGE)
        }
    }

    override fun requestPermissionSuccess(requestCode: Int) {
        val builder = Uri.Builder()
        builder.scheme("rong").authority(packageName).appendPath("sight").appendPath("player")
        val intentUrl = builder.build().toString()
        val intent = Intent("android.intent.action.VIEW", Uri.parse(intentUrl))
        intent.setPackage(packageName)
        intent.putExtra("SightMessage", videoTimeMessage?.message?.content)
        intent.putExtra("Message", videoTimeMessage?.message)
        startActivity(intent)
    }

    override fun getAdapter(): AbsRecyclerAdapter<TimeMessage, List<TimeMessage>> {
        val chatPictureAdapter = ChatPictureAdapter(this)
        chatPictureAdapter.selectListener = this
        return chatPictureAdapter
    }

    override fun getDataSource(): IAsyncDataSource<List<TimeMessage>> = ChatPictureDataSource(conversationType, mTargetId, getLastSentTime(), getLaseHeadId())

    override fun onInit() {
        bottomView = layoutInflater.inflate(R.layout.chat_pic_bottom_layoutm, flBottom, true)
        ivPicDel = bottomView?.findViewById(R.id.iv_pic_delete)
        ivPicShare = bottomView?.findViewById(R.id.iv_pic_share)
        tvSelectCount = bottomView?.findViewById(R.id.tv_select_count)
        ivPicDel?.setOnClickListener {
            CustomDialog.Builder(this)
                    .setMessage("确认要删除选中的项目吗？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        RongIM.getInstance().deleteMessages(getSelectId(), object : RongIMClient.ResultCallback<Boolean>() {
                            override fun onSuccess(p0: Boolean?) {
                                ToastUtils.show("移除成功")
                                selectList.clear()
                                bottomView.gone()
                                refresh()
                            }

                            override fun onError(p0: RongIMClient.ErrorCode?) {
                            }
                        })
                    }.create().show()
        }
        ivPicShare?.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.FORWARD_ACTIVITY).withParcelableArrayList("selectList", selectList).navigation()
        }
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }

    override fun onEvent(key: String?, var1: String?) {
        finish()
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        super.onPrepareOptionsMenu(menu)
        menu?.clear()
        status = if (status == STATUS_DEFAULT) {
            menu?.add(100, 101, 0, "选择")?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            bottomView.gone()
            STATUS_SELECT
        } else {
            menu?.add(100, 102, 0, "取消")?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            if (selectList.size > 0) {
                bottomView.visible()
                tvSelectCount?.text = getString(R.string.chat_pics_select_count, selectList.size)
            } else {
                bottomView.gone()
            }
            STATUS_DEFAULT
        }
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        (adapter as ChatPictureAdapter).isSelect = item?.itemId == 101
        adapter.notifyDataSetChanged()
        invalidateOptionsMenu()
        return super.onOptionsItemSelected(item)
    }

    override fun onSelect(isChecked: Boolean, data: TimeMessage, realPosition: Int) {
        if (isChecked) {
            if (!selectList.contains(data.message))
                selectList.add(data.message!!)
        } else {
            selectList.remove(data.message)
        }
        if (selectList.size > 0) {
            bottomView.visible()
            tvSelectCount?.text = getString(R.string.chat_pics_select_count, selectList.size)
        } else {
            bottomView.gone()
        }
    }

    private fun getSelectId(): IntArray? {
        val ids: ArrayList<Int> = arrayListOf()
        selectList.forEachIndexed { i: Int, timeMessage: Message ->
            ids.add(timeMessage.messageId!!)
        }
        return ids.toIntArray()
    }

    private fun getLastSentTime(): Long? {
        if (adapter == null) {
            return 0
        }
        adapter?.data!!.forEachReversedByIndex {
            val time = it.message?.sentTime ?: 0
            if (time != 0L) {
                return time
            }
        }
        return 0
    }

    private fun getLaseHeadId(): Int? {
        if (adapter == null) {
            return 0
        }
        adapter?.data!!.forEachReversedByIndex {
            val time = it.message?.sentTime ?: 0
            val hashCode = time.hashCode()
            if (hashCode != 0) {
                return hashCode
            }
        }
        return 0
    }

    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }
}
