package com.zj365.mime.act

import android.view.View
import android.widget.CheckBox
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseListAct
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.MessageReadEvent
import com.xty.common.getImageUrl
import com.xty.common.util.CommonToastUtils
import com.zj365.mime.R
import com.zj365.mime.adapter.MessageAdapter
import com.zj365.mime.databinding.ActMessageBinding
import com.zj365.mime.vm.MessageVm
import com.zj365.mime.weight.MessagePop
import com.xty.network.model.MessageBean
import com.xty.network.model.MessageTypeDataBean
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder

/**
 * 我的消息
 */
@Route(path = ARouterUrl.MESSAGE_TYPE)
class MessageTypeListAct : BaseListAct<MessageVm>() {
    var choiceMode:Boolean = false
    val binding by lazy { ActMessageBinding.inflate(layoutInflater) }
    val adapter by lazy { MessageAdapter() }
    var clickBean: MessageTypeDataBean.MessageTypeBean? = null
    var clickPosition = 0
    val array by lazy { resources.getStringArray(R.array.msg_array) }
    var nowPosition = 1

    var msgType:Int = 1  //根据type消息获取消息列表 消息类型1，消息消息，2，福利官，3，小助手
    val popWindow by lazy {
        MessagePop(this) {
            if (it != nowPosition) {
                page = 1
                nowPosition = it
//                binding.mSpinner.text = array[nowPosition]
                loadData()
            }
        }
    }

    override fun setLayout() = binding.root

    override fun initData() {
        super.initData()
        isDarkBar = true

        msgType = intent.getIntExtra("msgType",0)
    }

    override fun initView() {
        super.initView()

        var title = intent.getStringExtra("msgTitle")
        binding.title.apply {
            statusBar(mView)
            mTvTitle.text =title
            mTvRight.visibility = View.VISIBLE
            mTvRight.text = getString(R.string.message_manager)
            mTvRight.setTextColor(ContextCompat.getColor(this@MessageTypeListAct,R.color.col_02c))
            titleBg.setBackgroundColor(ContextCompat.getColor(this@MessageTypeListAct,R.color.white))

            mTvRight.setOnClickListener {
               if (choiceMode){  //全选
                   adapter.choiceAll()
               }else{  //选择模式
                   if (adapter.data.isEmpty()){
                       CommonToastUtils.showToast("暂无数据")
                   }else{
                       choiceMode(true)
                   }
               }
            }
        }

        //删除
        binding.llDelete.setOnClickListener{
            val ids = StringBuilder()
            adapter.data.forEachIndexed{ pos, any ->
               var msg = any as MessageTypeDataBean.MessageTypeBean
                if(msg.isChoice){
                    ids.append("${msg.id},")
                }
            }
            mViewModel.deleteMsgs(ids.toString())
        }

        setRecycleRefresh(binding.mRecycle, binding.mRefresh)
        binding.title.mIvBack.setOnClickListener {
            finish()
        }
    }

    private fun choiceMode(mode:Boolean){
        choiceMode = mode
        adapter.setChoiceMode(choiceMode)
        if (choiceMode){
            binding.title.mTvRight.text = getString(R.string.message_choice_all)
            binding.llDelete.visibility = View.VISIBLE
        }else{
            binding.title.mTvRight.text = getString(R.string.message_manager)
            binding.llDelete.visibility = View.GONE
        }
    }

    override fun initAdapter() {
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = adapter
        adapter.addChildClickViewIds(R.id.mContentView, R.id.mDelete,R.id.cbChoice)
        adapter.setOnItemChildClickListener { adapter, view, position ->
            var bean = adapter.getItem(position)
            when (view.id) {
                R.id.mContentView -> {
                    if (bean is MessageBean.Msg) {
                        bundle.putString("title", bean.realname)
                        when (bean.isMe) {
                            1 -> {
                                bundle.putString("toUserId", bean.to_user_id)
                                bundle.putString("fromUserId", bean.from_user_id)
                            }
                            2 -> {
                                bundle.putString("fromUserId", bean.to_user_id)
                                bundle.putString("toUserId", bean.from_user_id)
                            }

                        }

                        bundle.putString("chatImage", getImageUrl(bean.avatar))
                        RouteManager.goAct(ARouterUrl.CHAT_MSG, bundle)
                    } else {
                        val data = bean as MessageTypeDataBean.MessageTypeBean
                        if (data.notifyStatus == 0) {
                            clickBean = data
                            mViewModel.readMsg(data.id, data.notifyId)
                            clickPosition = position
                        } else {
                            bundle.clear()
                            bundle.putSerializable("bean", data)
                            RouteManager.goAct(ARouterUrl.MESSAGE_DETAIL_NEW, bundle)
                        }
                    }
                }
                R.id.mDelete -> {
                    val sysBean = bean as MessageTypeDataBean.MessageTypeBean
                    mViewModel.deleteMsg(sysBean.notifyId)
                }

                R.id.cbChoice->{
                    val sysBean = bean as MessageTypeDataBean.MessageTypeBean
                    val choiceView = view as CheckBox
                    sysBean.isChoice = choiceView.isChecked
                    if(choiceView.isChecked){
                        this.adapter.getDeletePos().add(position)
                    }else{
                        this.adapter.getDeletePos().remove(position)
                    }
                }
            }
        }
    }

    override fun liveObserver() {
        mViewModel.readLive.observe(this) {
            (adapter.data[clickPosition] as MessageTypeDataBean.MessageTypeBean).notifyStatus = 1
            adapter.notifyItemChanged(clickPosition)
            bundle.clear()
            bundle.putSerializable("bean", clickBean)
            RouteManager.goAct(ARouterUrl.MESSAGE_DETAIL_NEW, bundle)
            EventBus.getDefault().post(MessageReadEvent())
        }
        mViewModel.messageLive.observe(this) {
            when (nowPosition) {
                3 -> {
                    val list = mutableListOf<Any>()
                    list.add(it.data.records)
                    setDate(adapter, list)
                }
                0 -> {
                    val list = mutableListOf<Any>()
                    list.add(it.data.records)
                    it?.data?.let {
                        it.records.let { it1 -> list.addAll(it1) }
                    }
                    setDate(adapter, list)
                }
                else -> {
                    it?.data?.let {
                        setDate(adapter, it?.records as MutableList<Any>)
                    }
                }
            }
        }
        mViewModel.deleteLive.observe(this) {
            mViewModel.getMessageList(page, msgType)
        }

        mViewModel.deletesLive.observe(this){
            adapter.getDeletePos().forEachIndexed{_, any ->
                if (adapter.data.size > any){
                    adapter.data.removeAt(any)
                    EventBus.getDefault().post(MessageReadEvent())
                }else{
                    CommonToastUtils.showLoserToast("删除失败")
                }
            }
            adapter.data.forEachIndexed{_, any ->
                val msg = any as MessageTypeDataBean.MessageTypeBean
                msg.isChoice = false
            }
            adapter.getDeletePos().clear()
            choiceMode(false)
            CommonToastUtils.showSucceedToast("删除成功")
            EventBus.getDefault().post(MessageReadEvent())
        }
    }

    override fun loadData() {
        adapter.getDeletePos().clear()
        mViewModel.getMessageList(page, msgType)
    }
}