package com.yidianling.im.ui.page.fragment.adapter

import android.app.Dialog
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.ydl.ydlcommon.base.lifecycle.ILifecycleable
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.ListNoCancelDialog
import com.yidianling.im.api.param.RmHistoryParam
import com.yidianling.im.api.param.RmTalkParam
import com.yidianling.im.api.param.TopMessageParam
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl
import com.yidianling.im.event.UpdateTabUnreadNumEvent
import com.yidianling.im.helper.IMChatUtil
import com.yidianling.im.helper.MsgReceiveHelper
import com.yidianling.im.http.ImHttpImpl
import com.yidianling.im.session.SessionHelper
import com.yidianling.im.ui.page.fragment.bean.ChatItemBean
import com.yidianling.im.ui.page.fragment.view.ChatItemView
import com.yidianling.im.ui.page.fragment.view.ChatTimeItemView
import de.greenrobot.event.EventBus

/**
 * 互动列表适配器
 * Created by xj on 2019/10/14.
 */
class ChatAdapter(var context: Context, private var mList: ArrayList<ChatItemBean>,private var lifecycleable: ILifecycleable<*>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    companion object {
        const val TYPE_NORMAL_ITEM = 1001 // 正常item
        const val TYPE_TIME_ITEM = 1002 // 三周前item
    }

    fun setData(data: ArrayList<ChatItemBean>) {
        mList.clear()
        mList.addAll(data)
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        if (position < mList.size && !mList[position].isThreeItem) return TYPE_NORMAL_ITEM
        return TYPE_TIME_ITEM
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is ChatItemHolder -> {
                holder.view.initData(mList[position])
                holder.view.setOnClickListener {
                    //点击去私聊
                    if (TextUtils.equals(mList[position].toUid.toString(), "4108805")) {
                        SessionHelper.startP2PSession(context, -1, "4108805", null,
                                P2PCustomActionHandlerImpl("4108805", "课程小助手-壹壹", "4108805"))
                    }else {
//                        IMUtil.startChat(context as AppCompatActivity, mList[position].toUid.toString(), 0, 0, null, 0, true)
                        if (mList[position].chat_type==2){//群聊
                            mChatListener?.alreadyReadAit(mList[position].toUid.toString())
                            SessionHelper.startTeamSession(context,mList[position].toUid.toString())

                        }else{//单聊
                            IMChatUtil.startChat(context as AppCompatActivity, mList[position])
                        }
                    }
                }

                holder.view.setOnLongClickListener {

                    var nowBean = mList[position]
                    val name = java.util.ArrayList<String>()
                    name.add("删除")
                    if (nowBean.is_top == 1) {
                        name.add("取消置顶")
                    } else if (nowBean.is_top == 0) {
                        name.add("置顶该聊天")
                    }

                    val unread = MsgReceiveHelper.getUnNum(nowBean.toUid.toString())//获取未读消息数量
                    if (unread > 0) {
                        name.add("标记为已读")
                    }
                    val builder = ListNoCancelDialog.Builder(context, name, 0)
                    builder.setOnItemClickLister(object : ListNoCancelDialog.Builder.OnItemClickLister {
                        override fun onItemClick(dialog: Dialog, view: View, position1: Int) {
                            val tag = name[position1]
                            when (tag) {
                                "删除" -> {
                                    delete(nowBean)
                                    dialog.dismiss()
                                }
                                "置顶该聊天" -> {
                                    toTop(nowBean, 1)
                                    dialog.dismiss()
                                }
                                "取消置顶" -> {
                                    toTop(nowBean, 0)
                                    dialog.dismiss()
                                }
                                "标记为已读" -> {
                                    mark(nowBean)
                                    dialog.dismiss()
                                }
                            }
                        }

                        override fun onItemLongClick(dialog: Dialog, view: View, position1: Int) {

                        }
                    })
                    builder.create().show()
                    true
                }
            }
            is ChatTimeItemHolder -> {
                holder.view.initData(mList[position])
            }
            else -> {}
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_NORMAL_ITEM -> {
                ChatItemHolder(ChatItemView(context))
            }
            else -> {
                ChatTimeItemHolder(ChatTimeItemView(context))
            }
        }

    }

    override fun getItemCount(): Int {
        return mList.size
    }

    private fun delete(bean: ChatItemBean) {
        LogHelper.getInstance().writeLogSync("删除聊天：uid = " + bean.toUid)
        var dis =  ImHttpImpl.getInstance().rmHistory(
            RmHistoryParam(
                bean.toUid.toString(),
                1
            )
        )
                .compose(RxUtils.applySchedulers(lifecycleable))
                .compose(RxUtils.resultData())
                .subscribe({ o ->
                    LogHelper.getInstance().writeLogSync("删除聊天成功：uid = " + bean.toUid)
                    NIMClient.getService(MsgService::class.java).clearChattingHistory(bean.toUid.toString(), SessionTypeEnum.P2P)
                    deleteItem(bean)
                }, {t ->
                    ToastHelper.show(t.message.toString())
                    LogHelper.getInstance().writeLogSync("删除聊天失败：uid = " + bean.toUid)
                })
    }

    private fun deleteItem(bean: ChatItemBean) {

        var dis = ImHttpImpl.getInstance().rmTalk(RmTalkParam(bean.toUid.toString()))
                .compose(RxUtils.applySchedulers(lifecycleable))
                .compose(RxUtils.resultData())
                .subscribe({ o ->
                    NIMClient.getService(MsgService::class.java).clearUnreadCount(bean.toUid.toString(), SessionTypeEnum.P2P)
                    NIMClient.getService(MsgService::class.java).clearUnreadCount(bean.toUid.toString(), SessionTypeEnum.Team)
                    MsgReceiveHelper.updateNum(bean.toUid.toString(), 0)
                    EventBus.getDefault().post(UpdateTabUnreadNumEvent())
                }, {t ->
                    ToastHelper.show(t.message.toString())
                })

    }

    private fun toTop(bean: ChatItemBean, istop: Int) {
        LogHelper.getInstance().writeLogSync("置顶聊天：uid = " + bean.toUid.toString() +
                "取消置顶 = " + (istop == 0))
        var dis = ImHttpImpl.getInstance().topMessage(
            TopMessageParam(
                bean.toUid.toString(),
                1,
                istop
            )
        )
                .compose(RxUtils.applySchedulers(lifecycleable))
                .compose(RxUtils.resultData())
                .subscribe({ o ->
                    LogHelper.getInstance().writeLogSync("置顶聊天成功：uid = " + bean.toUid.toString() +
                            "取消置顶 = " + (istop == 0))
                    mListener?.onRefresh()
                }, {t ->
                    LogHelper.getInstance().writeLogSync("置顶聊天失败：uid = " + bean.toUid.toString() +
                            "取消置顶 = " + (istop == 0))
                    ToastHelper.show("操作失败")
                })
    }

    private fun mark(bean: ChatItemBean) {
        LogHelper.getInstance().writeLogSync("标记为已读：uid = " + bean.toUid.toString())
        NIMClient.getService(MsgService::class.java).clearUnreadCount(bean.toUid.toString(), SessionTypeEnum.P2P)
        MsgReceiveHelper.updateNum(bean.toUid.toString(), 0)
        mListener?.onRefresh()
        EventBus.getDefault().post(UpdateTabUnreadNumEvent())
    }

    private var mListener: ChatRecyclerViewCallback? = null

    fun setlistener(listener: ChatRecyclerViewCallback) {
        this.mListener = listener
    }

    interface ChatRecyclerViewCallback {
        fun onRefresh() //刷新聊天列表
    }

    private var mChatListener: ChatAitAlreadyRead? = null

    fun setChatAitReadlistener(mChatListener: ChatAitAlreadyRead) {
        this.mChatListener = mChatListener
    }

    interface ChatAitAlreadyRead {
        fun alreadyReadAit( tid:String) //群聊艾特符号
    }

    /**
     * 互动列表正常item的holder
     */
    inner class ChatItemHolder(val view: ChatItemView): RecyclerView.ViewHolder(view)

    /**
     * 互动列表正常item的holder
     */
    inner class ChatTimeItemHolder(val view: ChatTimeItemView): RecyclerView.ViewHolder(view)

}