package com.bc_chat.im.activity

import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.net.Uri
import android.view.View
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.entity.CollectMessage
import com.bc_chat.bc_base.entity.ListModel
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.im.R
import com.bc_chat.im.adapter.CollectAdapter
import com.bc_chat.im.dataSource.CollectionDataSource
import com.bc_chat.im.dataSource.DelCollectionTask
import com.google.gson.JsonObject
import com.zhaohaoting.framework.abs.BaseRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.requset.NetWorkCallBack
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ToastUtils
import io.rong.imkit.manager.AudioPlayManager
import io.rong.imkit.manager.IAudioPlayListener
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.message.SightMessage
import io.rong.message.VoiceMessage
import java.lang.Exception

/**
 * author：Created by zhaohaoting on 2019/3/16
 * email：526309416@qq.com
 * desc：收藏
 */
@Route(path = RouteConfig.COLLECTION_ACTIVITY)
class CollectionActivity : BaseRecyclerActivity<CollectMessage, ListModel<CollectMessage>>(), CollectAdapter.OnCollectClickListener {

    private var mConversationType: Conversation.ConversationType? = null
    private var mTargetId: String? = null
    private var videoMessage: SightMessage? = null
    override fun onInit() {
        mTargetId = intent.getStringExtra("targetId")
        mConversationType = intent.getSerializableExtra("conversationType") as Conversation.ConversationType
    }

    override fun getAdapter(): AbsRecyclerAdapter<CollectMessage, ListModel<CollectMessage>> {
        val collectAdapter = CollectAdapter(this)
        collectAdapter.setOnCollectClickListener(this)
        return collectAdapter
    }

    override fun getDataSource(): IAsyncDataSource<ListModel<CollectMessage>> = CollectionDataSource()

    override fun onClick(view: View, updateView: View, data: CollectMessage?) {
        when (view.id) {
            R.id.iv_cover -> {
                val intent = Intent(this,PicturePreviewActivity::class.java)
                intent.setPackage(packageName)
                intent.putExtra("message", data?.content)
                startActivity(intent)
            }
            R.id.iv_switch -> {
                if (data?.type == Const.CollectionType.TYPE_VOICE_MESSAGE) {
                    AudioPlayManager.getInstance().startPlay(this, (data.content as VoiceMessage).uri, object : IAudioPlayListener {
                        override fun onComplete(p0: Uri?) {
                            play(updateView, false)
                        }

                        override fun onStart(p0: Uri?) {
                            play(updateView, true)
                        }

                        override fun onStop(p0: Uri?) {
                            play(updateView, false)
                        }
                    })
                } else {
                    videoMessage = data?.content as SightMessage
                    judgePermission(Const.Permission.Key.STORAGE, *Const.Permission.Value.STORAGE)
                }
            }
        }
    }


    override fun onItemClick(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val message = adapter.data.list[position].content
        CustomDialog.Builder(this).setMessage("你确定要发送该收藏消息吗？").setNegativeButton("取消", null).setPositiveButton("确定") { dialog, which ->
            val sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
            message?.userInfo = sendUserInfo
            ARouter.getInstance().navigation(ImRongService::class.java).sendMessage(mTargetId!!, mConversationType!!, message!!)
            finish()
        }.create().show()
    }

    override fun itemLongClicked(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val collectMessage = adapter.data.list[position]
        CustomDialog.Builder(this).setMessage("你确定要删除该收藏吗？").setNegativeButton("取消", null).setPositiveButton("确定") { dialog, which ->
            taskHelper.execute<Any>(DelCollectionTask(collectMessage.id!!), object : NetWorkCallBack<JsonObject>() {

                override fun onPreExecute(task: Any?) {
                    showLoading(task)
                }

                override fun onPostExecuteFailure(task: Any?, exception: Exception?) {
                    super.onPostExecuteFailure(task, exception)
                    dismissLoading(task)
                }

                override fun onPostExecuteSuccess(task: Any?, data: JsonObject?) {
                    dismissLoading(task)
                    ToastUtils.show("移除成功")
                    adapter.data.list.remove(collectMessage)
                    adapter.notifyItemRemoved(position)
                    adapter.notifyDataSetChanged()
                }
            })
        }.create().show()
    }

    private fun play(updateView: View, playing: Boolean) {
        val animationDrawable = resources.getDrawable(io.rong.imkit.R.drawable.rc_an_voice_receive) as AnimationDrawable
        if (playing) {
            (updateView as ImageView).setImageDrawable(animationDrawable)
            animationDrawable.start()
        } else {
            (updateView as ImageView).setImageDrawable(resources.getDrawable(io.rong.imkit.R.drawable.rc_ic_voice_receive))
            animationDrawable.stop()
        }
    }


    override fun requestPermissionSuccess(requestCode: Int) {
        super.requestPermissionSuccess(requestCode)
        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", videoMessage)
        intent.putExtra("Message", Message.obtain(mTargetId, mConversationType, videoMessage))
        startActivity(intent)
    }

}