package com.yidianling.im.ui.page

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
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.BaseFragment
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.RxUtils
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.im.api.event.ImLogoutEvent
import com.yidianling.im.api.event.UpdateBottomBarUnreadNumEvent
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl
import com.yidianling.im.config.constants.ImConstants
import com.yidianling.im.event.MessageListRefreshEvent
import com.yidianling.im.event.ReQureyUnreadNum
import com.yidianling.im.event.UpdateTabUnreadNumEvent
import com.yidianling.im.helper.MsgReceiveHelper
import com.yidianling.im.http.ImHttpImpl
import com.yidianling.im.router.ImIn
import com.yidianling.im.session.SessionHelper
import com.yidianling.im.ui.page.dialog.MessageChatSettingDialog
import com.yidianling.im.ui.page.fragment.ChatFragment
import com.yidianling.im.ui.page.fragment.InteractFragment
import com.yidianling.im.ui.page.fragment.NoticeFragment
import com.yidianling.im.ui.page.fragment.adapter.ChatPagerAdapter
import com.yidianling.im.ui.page.fragment.bean.UnreadMessageBean
import com.yidianling.im.ui.page.popupWindow.ChatSettingPopupWindow
import com.yidianling.im.ui.param.ClearMessageParam
import com.yidianling.im.ui.param.UnreadParam
import de.greenrobot.event.EventBus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.im_new_multi_message_fragment.*
import java.util.concurrent.TimeUnit

/**
 * Created by xj on 2019/10/14.
 */
@Route(path = "/im/im")
class NewMultiMessageFragment : BaseFragment() {

    private lateinit var mContext: Context
    private var defaultTranslateX: Float? = null
    private var mFragmentsList: ArrayList<Fragment> = ArrayList(3)
    private var chatSettingPopupWindow: ChatSettingPopupWindow? = null  //右上角弹框
    private var messageChatSettingtDialog: MessageChatSettingDialog? = null //全部已读弹框

    private var chatListUnreadNum: Int = 0 // 私聊列表未读数
    private var interactListUnreadNum: Int = 0 //互动列表未读数
    private var noticeListUnreadNum: Int = 0 //通知列表未读数

    override fun initDataAndEventLazy() {
    }

    override fun layoutResId(): Int {
        return R.layout.im_new_multi_message_fragment
    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = requireContext()
        EventBus.getDefault().register(this)
    }

    override fun onResume() {
        super.onResume()

        getMsgData()

        NIMClient.getService(MsgService::class.java).setChattingAccount(
            MsgService.MSG_CHATTING_ACCOUNT_NONE,
            SessionTypeEnum.None
        )
    }

    override fun onPause() {
        super.onPause()
        NIMClient.getService(MsgService::class.java).setChattingAccount(
            MsgService.MSG_CHATTING_ACCOUNT_NONE,
            SessionTypeEnum.None
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && getIsViewCreated()) {
            getMsgData()
        }
    }

    //跳转到下一个未读消息列
    fun nextUnReadItem() {
        if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
            (mFragmentsList[0] as ChatFragment).nextUnReadItem()
        }
        if (mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
            (mFragmentsList[1] as InteractFragment).nextUnReadItem()
        }
        if (mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
            (mFragmentsList[2] as NoticeFragment).nextUnReadItem()
        }
    }

    override fun initDataAndEvent() {

        chat_btn.setOnClickListener {
            view_pager.currentItem = 0
        }
        communite_btn.setOnClickListener {
            view_pager.currentItem = 1
        }
        notification_btn.setOnClickListener {
            view_pager.currentItem = 2
        }

        defaultTranslateX = custom_indicator.translationX

        initKefu()

        initMore()

        initViewPager()

    }

    /**
     * 刷新当前展示的消息列表的数据，刷新顶部三个消息未读数，刷新底部消息未读数
     */
    fun getMsgData(isRefreshInteractList: Boolean = false) {
        /**
         * 登录状态
         */
        if (ImIn.isLogin()) {
            if (view_pager.currentItem == 0 && mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
                (mFragmentsList[0] as ChatFragment).getChatMessageData()
            }
            //互动列表单独刷新被点击的item。不进行列表的刷新，列表的刷新操作只在互动列表从私聊或者通知或者其余fragment切换过来的时候刷新
            if (isRefreshInteractList) {
                if (view_pager.currentItem == 1 && mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
                    (mFragmentsList[1] as InteractFragment).getInteractMessageData(refresh = true)
                }
            }
            if (view_pager.currentItem == 2 && mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
                (mFragmentsList[2] as NoticeFragment).getNoticeMessageData()
            }
        }

        requestTopUnReadNumber()
    }

    /**
     * 刷新顶部未读数量（接口返回成功后调用的方法中会触发事件刷新底部导航栏的角标）
     */
    fun requestTopUnReadNumber() {
        if (ImIn.getUserInfo()?.uid != "0") {
            var dis =
                ImHttpImpl.getInstance().getUnreadMessage(UnreadParam("${ImIn.getUserInfo()?.uid}"))
                    .compose<UnreadMessageBean>(RxUtils.resultJavaData())
                    .compose(RxUtils.applySchedulers(this))
                    .subscribe({ it ->
                        resetTopUnReadNumber(it)
                    }, { t ->
                        ToastUtil.toastShort("您的网络出现了问题")
                    })
        } else {
            //退出登录情况下，全部不显示
            chat_top_unread_num.visibility = View.GONE
            chatListUnreadNum = 0
            interact_top_unread_num.visibility = View.GONE
            interactListUnreadNum = 0
            notice_top_unread_num.visibility = View.GONE
            noticeListUnreadNum = 0
            EventBus.getDefault().post(UpdateBottomBarUnreadNumEvent(0))
        }
    }

    /**
     * 重置顶部未读数量
     */
    private fun resetTopUnReadNumber(bean: UnreadMessageBean) {

        val chatUnreadNum = ImIn.getInUnreadNum()//私聊未读数移动端自己读取云信
        if (chatUnreadNum > 0) {
            chatListUnreadNum = chatUnreadNum
            chat_top_unread_num.visibility = View.VISIBLE
            chat_top_unread_num.text = if (chatUnreadNum > 99) "99+" else "${chatUnreadNum}"
        } else {
            chat_top_unread_num.visibility = View.GONE
            chatListUnreadNum = 0
        }

        if (bean.interactiveNum > 0) {
            interactListUnreadNum = bean.interactiveNum
            interact_top_unread_num.visibility = View.VISIBLE
            interact_top_unread_num.text =
                if (bean.interactiveNum > 99) "99+" else "${bean.interactiveNum}"
        } else {
            interact_top_unread_num.visibility = View.GONE
            interactListUnreadNum = 0
        }

        if (bean.notifyNum > 0) {
            noticeListUnreadNum = bean.notifyNum
            notice_top_unread_num.visibility = View.VISIBLE
            notice_top_unread_num.text = if (bean.notifyNum > 99) "99+" else "${bean.notifyNum}"
        } else {
            notice_top_unread_num.visibility = View.GONE
            noticeListUnreadNum = 0
        }

        MsgReceiveHelper.isHasUnread =
            chatListUnreadNum > 0 || interactListUnreadNum > 0 || noticeListUnreadNum > 0
        // 同步底部导航栏的角标数量
        EventBus.getDefault().post(
            UpdateBottomBarUnreadNumEvent(
                chatListUnreadNum + interactListUnreadNum + noticeListUnreadNum
            )
        )
    }

    /**
     * 初始化更多点击
     */
    private fun initMore() {
        ll_more.setOnClickListener {
            if (!ImIn.isLogin()) {
                ToastUtil.toastShort("请登录后再试")
            } else {
                chatSettingPopupWindow = ChatSettingPopupWindow(
                    mContext,
                    object : ChatSettingPopupWindow.OnChatSettingClickListener {
                        override fun onAllReadClick() {
                            messageChatSettingtDialog = MessageChatSettingDialog(
                                mContext,
                                object : MessageChatSettingDialog.OnMessageChatSettingDialog {
                                    override fun onSure() {
                                        markAllMessageRead()
                                        messageChatSettingtDialog?.dismiss()
                                    }

                                    override fun onCancel() {
                                        messageChatSettingtDialog?.dismiss()
                                    }
                                })
                            messageChatSettingtDialog?.show()
                        }

                        override fun onChatSettingClick() {
                            ARouter.getInstance().build("/user/notifysetting").navigation()
                        }

                        override fun onSafeInfoSetting() {
                            startActivity(ImIn.getUserService().privacyIntent(activity!!))
                        }

                        override fun onDismissAction() {
                            setWindowBg(1f)
                        }
                    })
                chatSettingPopupWindow?.contentView!!.measure(
                    View.MeasureSpec.UNSPECIFIED,
                    View.MeasureSpec.UNSPECIFIED
                ); //这句代码必须要才能获得正确的popupwindow的宽度
                val popupWindowWidth = chatSettingPopupWindow?.contentView!!.measuredWidth
                setWindowBg(0.4f)
                chatSettingPopupWindow?.showAsDropDown(
                    ll_more,
                    -(popupWindowWidth - ll_more.measuredWidth + 20),
                    0
                )
            }
        }
    }

    /**
     * 全部已读（私聊是单独处理的）
     */
    fun markAllMessageRead() {
        var dis = ImHttpImpl.getInstance().clearMessage(
            ClearMessageParam(
                "${ImIn.getUserInfo()?.uid}",
                "1"
            )
        )
            .compose(RxUtils.applySchedulers(this))
            .subscribe({ it ->
                if (it.data) {
                    //清除私聊群聊未读数
                    MsgReceiveHelper.markAllRead()
                    getMsgData(true)
                    ToastUtil.toastShort("已全部标记为已读")
                } else {
                    ToastUtil.toastShort("标记失败")
                }
            }, { t ->
                ToastUtil.toastShort("您的网络出现了问题")
            })
    }

    /**
     * 初始化客服点击
     */
    private fun initKefu() {
        ll_kefu.setOnClickListener {
            if (ImIn.isLogin()) {
                SessionHelper.startP2PSession(context, -1, ImConstants.KEFUXIAOYI, null,
                        P2PCustomActionHandlerImpl(ImConstants.KEFUXIAOYI, "客服小壹", ImConstants.KEFUXIAOYI)
                )
            } else {
                ToastUtil.toastShort("请登录后再试")
            }
        }
    }
    /**
     * 设置页面背景色
     */
    private fun setWindowBg(alpha: Float) {
        val lp = activity?.window!!.attributes
        lp.alpha = alpha
        activity?.window!!.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        activity?.window!!.attributes = lp
    }

    /**
     * 初始化viewPager
     */
    private fun initViewPager() {

        if (mFragmentsList.size == 0) {
            mFragmentsList.add(0, ChatFragment())
            mFragmentsList.add(1, InteractFragment())
            mFragmentsList.add(2, NoticeFragment())
        }
        view_pager.offscreenPageLimit = 3
        view_pager.adapter = ChatPagerAdapter(childFragmentManager, mFragmentsList!!)

        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(p0: Int) {
            }

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
            }

            @SuppressLint("CheckResult")
            override fun onPageSelected(index: Int) {
                setSelectTab(index)
                // 这边延迟300毫秒加载，是为了不让动画进行时有卡顿
                Observable.timer(300, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        getMsgData(true)
                    }
            }
        })
    }

    /**
     * tab选择
     */
    private fun setSelectTab(index: Int) {
        if (index == 0) {
            setLeftMargin(0)
        } else if (index == 1) {
            setLeftMargin(1)
        } else if (index == 2) {
            setLeftMargin(2)
        }
    }

    /**
     * 属性动画设置下划线距离左边的距离
     */
    private fun setLeftMargin(index: Int) {
        val currentTranslateX = custom_indicator.translationX
        var anim = ObjectAnimator.ofFloat(
            custom_indicator,
            "translationX",
            currentTranslateX,
            defaultTranslateX!! + index * chat_btn.width
        )
        anim.duration = 300
        anim.start()
    }

    fun onEvent(event: ReQureyUnreadNum) {
        getMsgData()
    }

    /**
     * 私聊未读数变化触发的事件，不进行互动和通知未读数的更新
     */
    fun onEvent(event: UpdateTabUnreadNumEvent) {
        try {
            val chatUnreadNum = ImIn.getInUnreadNum() //私聊未读数移动端自己读取云信
            if (chatUnreadNum > 0) {
                chatListUnreadNum = chatUnreadNum
                chat_top_unread_num.visibility = View.VISIBLE
                chat_top_unread_num.text = if (chatUnreadNum > 999) "999+" else "${chatUnreadNum}"
            } else {
                chat_top_unread_num.visibility = View.GONE
                chatListUnreadNum = 0
            }
            // 刷新私聊列表
            if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
                (mFragmentsList[0] as ChatFragment).getChatMessageData()
            }
            // 同步底部导航栏的角标数量
            EventBus.getDefault().post(
                UpdateBottomBarUnreadNumEvent(
                    chatListUnreadNum + interactListUnreadNum + noticeListUnreadNum
                )
            )
        } catch (e: Exception) {
        }
    }

    /**
     * 私聊，互动，通知列表下拉刷新触发
     */
    fun onEvent(event: MessageListRefreshEvent) {
        requestTopUnReadNumber()
    }

    /**
     * 云信登出
     */
    fun onEvent(event: ImLogoutEvent) {
        if (mFragmentsList.size > 0 && mFragmentsList[0] is ChatFragment) {
            (mFragmentsList[0] as ChatFragment).clearData()
        }
        if (mFragmentsList.size > 1 && mFragmentsList[1] is InteractFragment) {
            (mFragmentsList[1] as InteractFragment).clearData()
        }
        if (mFragmentsList.size > 2 && mFragmentsList[2] is NoticeFragment) {
            (mFragmentsList[2] as NoticeFragment).clearData()
        }
    }
}