package com.renrenliao.im.ui.fragment

import android.graphics.Point
import android.os.Bundle
import android.view.Menu
import android.view.MotionEvent

import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ktx.statusBarHeight
import com.renrenliao.im.R
import com.renrenliao.im.base.BaseVMFragment
import com.renrenliao.im.im.AlarmEntity
import com.renrenliao.im.im.AlarmType
import com.renrenliao.im.model.repository.LocalDataSource
import com.renrenliao.im.ui.activity.MainActivity
import com.renrenliao.im.ui.adapter.AlarmAdapter
import com.renrenliao.im.ui.adapter.diff.AlarmDiffCallback
import com.renrenliao.im.utils.DeviceUtils
import com.renrenliao.im.utils.GlideUtils
import com.renrenliao.im.utils.LogUtils
import com.renrenliao.im.utils.RouteUtils
import com.renrenliao.im.viewmodel.AlarmViewModel
import com.renrenliao.im.widget.floatmenu.FloatMenu
import com.renrenliao.im.widget.floatmenu.MenuItem
import com.renrenliao.im.widget.view.VerticalDecoration
import kotlinx.android.synthetic.main.fragment_alarm.*
import net.openmob.mobileimsdk.android.ClientCoreSDK
import org.koin.androidx.viewmodel.ext.android.getViewModel

/**
 **@ClassName AlarmsFragment
 **@Description
 **@Author gan
 **@Date 2022/5/26 12:53
 **/
class AlarmFragment : BaseVMFragment<AlarmViewModel>() {

    private val TAG = AlarmFragment::class.java.simpleName

    private val floatMenuShowPoint_forRecy = Point()

    private val DELETE = Menu.FIRST //删除
    private val TOP = Menu.FIRST + 1 //置顶
    private val CANCLE_TOP = Menu.FIRST + 2 //取消置顶
    private val READ = Menu.FIRST + 3 //标记已读
    private val UNREAD = Menu.FIRST + 4 //标记未读

    private val msgAdapter by lazy { AlarmAdapter() }

    override fun initVM(): AlarmViewModel = getViewModel()

    override fun getLayoutResId(): Int = R.layout.fragment_alarm

    override fun initView() {

        initTouchListener()

        ll_parent.setPadding(0, statusBarHeight, 0, 0)

        tool_bar.setTvLeft("消息")
        tool_bar.findViewById<ImageView>(R.id.iv_right_more).setImageResource(R.drawable.ic_im_add)
        tool_bar.findViewById<ImageView>(R.id.iv_title_search)
            .setImageResource(R.drawable.ic_im_search)

        //设置分割线
        val mDivider = ContextCompat.getDrawable(requireContext(), R.drawable.divider_left_77)
        recy_msg.addItemDecoration(
            VerticalDecoration(
                requireContext(),
                mDivider,
                DeviceUtils.dip2px(requireContext(), 0.6f).toInt()
            )
        )
        recy_msg.run {
            adapter = msgAdapter
            layoutManager = LinearLayoutManager(recy_msg.context)
        }
        //设置diffCallback
        msgAdapter.setDiffCallback(AlarmDiffCallback())
        //item单击事件
        msgAdapter.setOnItemClickListener { _, _, position ->
            //是好友请求的
            if (msgAdapter.data[position].msgType == AlarmType.ADDFRIENDREQUEST.value) {
                RouteUtils.gotoVerification(requireContext())
            }
        }

        //长按
        msgAdapter.setOnItemLongClickListener { _, _, position ->
            val alarmEntity = msgAdapter.data[position]
            val menuList = mutableListOf<MenuItem>()
            addContextMenuItems(menuList, alarmEntity)
            val floatMenu = FloatMenu(activity)
            floatMenu.items(menuList, DeviceUtils.dip2px(requireContext(), 100f).toInt())
            floatMenu.setOnItemClickListener { _, index ->
                val menuItem = menuList[index]
                fireContextMenuItemSelected(menuItem, alarmEntity)
            }
            floatMenu.show(floatMenuShowPoint_forRecy)

            true
        }


    }

    override fun initData() {
        //读取消息的任务 显示消息界面  同时监听消息 刷新界面

    }

    override fun startObserve() {
        //观察网络监听
        LocalDataSource.networkStatusLiveData.observe(viewLifecycleOwner) {
            when (it) {
                ClientCoreSDK.IM_STATE_OFFLINE -> {
                    tool_bar.setTvLeft("消息(离线)")
                }
                ClientCoreSDK.IM_STATE_ONLINE -> {
                    tool_bar.setTvLeft("消息")
                }
                ClientCoreSDK.IM_STATE_CONNECTING -> {
                    tool_bar.setTvLeft("消息(连接中)")
                }
            }
        }
        mViewModel.run {
            //观察通知数据变化
            alarmLiveData.observe(viewLifecycleOwner) { alarms ->
                if (alarms.isEmpty()) {
                    msgAdapter.setEmptyView(R.layout.layout_empty_alarm)
                }
                //先把是添加好友的过滤出来 排序
                val addFriends = alarms
                    //过滤
                    .filter { it.msgType == AlarmType.ADDFRIENDREQUEST.value }
                    //倒序排序
                    .sortedByDescending { it.time }
                val list = mutableListOf<AlarmEntity>()

                val chatAlarms = alarms
                    //过滤
                    .filter { it.msgType != AlarmType.ADDFRIENDREQUEST.value }
                    //倒序排序
                    .sortedByDescending { it.time }
                    .sortedByDescending { it.isTop }

                list.addAll(addFriends)
                list.addAll(chatAlarms)

                msgAdapter.setDiffNewData(list)

            }

        }

    }

    private fun addContextMenuItems(
        menuItemsList: MutableList<MenuItem>,
        alarmEntity: AlarmEntity
    ) {
        if (alarmEntity.msgType == AlarmType.REVICEMESSAGE.value ||
            alarmEntity.msgType == AlarmType.TEMPCHATMESSAGE.value ||
            alarmEntity.msgType == AlarmType.GROUPCHATMESSAGE.value
        ) {
            if (alarmEntity.isTop) {
                menuItemsList.add(MenuItem().setItem("取消置顶").setItemActionId(CANCLE_TOP))
            } else {
                menuItemsList.add(MenuItem().setItem("置顶聊天").setItemActionId(TOP))
            }

            if (alarmEntity.num > 0) {
                menuItemsList.add(MenuItem().setItem("标记已读").setItemActionId(READ))
            } else {
                menuItemsList.add(MenuItem().setItem("标记未读").setItemActionId(UNREAD))
            }
            menuItemsList.add(MenuItem().setItem("删除聊天").setItemActionId(DELETE))
        }
    }

    private fun fireContextMenuItemSelected(item: MenuItem, alarmEntity: AlarmEntity) {
        when (item.itemActionId) {
            TOP ->{
                mViewModel.updateIsTop(alarmEntity.account_uid.toString(),alarmEntity.tid.toString(),alarmEntity.msgType,true)
            }
            CANCLE_TOP ->{
                mViewModel.updateIsTop(alarmEntity.account_uid.toString(),alarmEntity.tid.toString(),alarmEntity.msgType,false)
            }
            READ ->{
                mViewModel.updateReadStatus(alarmEntity.account_uid.toString(),alarmEntity.tid.toString(),alarmEntity.msgType,0)
            }
            UNREAD ->{
                mViewModel.updateReadStatus(alarmEntity.account_uid.toString(),alarmEntity.tid.toString(),alarmEntity.msgType,1)
            }
            DELETE -> {
                //从数据库中删除这条记录
                mViewModel.deleteAlarm(alarmEntity)
            }
        }
    }

    private var myTouchListener: MainActivity.MyTouchListener? = null

    private fun initTouchListener() {
        myTouchListener = object : MainActivity.MyTouchListener {
            override fun onTouchEvent(event: MotionEvent) {
                if (event.action == MotionEvent.ACTION_DOWN) {
                    // 保存此时的长按点信息
                    floatMenuShowPoint_forRecy.x = event.rawX.toInt()
                    floatMenuShowPoint_forRecy.y = event.rawY.toInt()
                }
            }
        }
        if (myTouchListener != null) {
            (activity as MainActivity).registerMyTouchListener(myTouchListener as MainActivity.MyTouchListener)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        LogUtils.error(TAG + "onViewCreated")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LogUtils.error(TAG + "onDestroyView")
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtils.error(TAG + "onDestroy")
        if (myTouchListener != null) {
            (activity as MainActivity).unRegisterMyTouchListener(myTouchListener!!)
        }
    }
}