package com.iscs.bozzys.ui.pages.vm

import androidx.lifecycle.viewModelScope
import com.iscs.bozzys.api.ApiRequest
import com.iscs.bozzys.api.Message
import com.iscs.bozzys.event.RefreshEvent
import com.iscs.bozzys.event.RefreshEventBus
import com.iscs.bozzys.ui.common.VMBase
import com.iscs.bozzys.ui.dialog.StateTips
import com.iscs.bozzys.utils.DateUtil.getShowDate
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * 通知消息
 */
class VMMessage : VMBase() {

    private val _state = MutableStateFlow(StateMessage())

    val state = _state.asStateFlow()

    fun init() {
        getMessage(StatePageMessage(isRefresh = true, page = 1))
    }

    /**
     * 获取消息列表
     *
     * @param page  页面加载器
     */
    fun getMessage(page: StatePageMessage) {
        viewModelScope.launch {
            _state.value = _state.value.copy(page = _state.value.page.copy(page = page.page, isRefresh = page.isRefresh))
            ApiRequest.getMessages(mutableMapOf("pageNo" to page.page, "pageSize" to page.pageSize)).onSuccess {
                // 如果加载的是第一页数据，这里先做清除操作
                if (page.page == 1) _state.value.messages.clear()
                val newList = _state.value.messages.toMutableList()
                val dataCount = it.data?.total ?: 0
                it.data?.list?.forEach { msg ->
                    // 查找是否有和日期相同的标题，如果没有则插入
                    val findTitle = newList.find { m -> m.createTime.getShowDate() == msg.createTime.getShowDate() && m.uiIsTitle }
                    if (findTitle == null) newList += Message(uiIsTitle = true, title = msg.createTime.getShowDate(), createTime = msg.createTime)
                    newList += msg
                }
                _state.value = _state.value.copy(messages = newList)
                delay(500)
                // 查找消息个数是否和后台返回的消息个数一致
                val noMore = newList.count { m -> !m.uiIsTitle } == dataCount
                _state.value = _state.value.copy(page = _state.value.page.copy(isRefresh = false, noMore = noMore))
            }.onFailure {
                delay(500)
                _state.value = _state.value.copy(page = _state.value.page.copy(page = page.page, isRefresh = false))
                delay(100)
            }
        }
    }

    /**
     * 消息被点击操作，主要是已读操作
     */
    fun onMessage(msg: Message) {
        // 已读不做处理
        if (msg.readStatus) return
        viewModelScope.launch {
            ApiRequest.updateMessageRead(mutableMapOf("ids" to "${msg.id}")).onSuccess {
                val newList = _state.value.messages.map { if (it.id == msg.id) it.copy(readStatus = true) else it }.toMutableList()
                _state.value = _state.value.copy(messages = newList)
                RefreshEventBus.onRefreshData(RefreshEvent.HomeData)
            }
        }
    }

    /**
     * 全部已读
     */
    fun onReadAll() {
        _state.value = _state.value.copy(tips = StateTips(show = true, title = "提示", content = "确定要将所有消息标记为已读吗？", type = "READ_ALL"))
    }

    /**
     * 后台暂不支持删除所有，待支持后开放
     */
    fun onDeleteAll() {
        _state.value = _state.value.copy(tips = StateTips(show = true, title = "提示", content = "确定要删除所有消息吗？", type = "DELETE_ALL"))
    }

    /**
     * 隐藏提示Dialog
     */
    fun hideTips() {
        _state.value = _state.value.copy(tips = _state.value.tips.copy(show = false, type = ""))
    }

    /**
     * 提示窗口确认被点击
     */
    fun onTipsConfirm() {
        viewModelScope.launch {
            val tips = _state.value.tips
            _state.value = _state.value.copy(tips = tips.copy(show = false))
            if (tips.type == "READ_ALL") {
                ApiRequest.updateMessageRead(mutableMapOf()).onSuccess {
                    val newList = _state.value.messages.map { it.copy(readStatus = true) }.toMutableList()
                    _state.value = _state.value.copy(messages = newList)
                    RefreshEventBus.onRefreshData(RefreshEvent.HomeData)
                }
            }
        }
    }

}

/**
 * 消息界面状态类
 *
 * @param messages  消息列表
 * @param page      页面数据
 * @param tips      tipsDialog数据
 */
data class StateMessage(
    val messages: MutableList<Message> = mutableListOf(),
    val page: StatePageMessage = StatePageMessage(),
    val tips: StateTips = StateTips()
)

/**
 * 页面数据
 *
 * @param page      当前页面
 * @param pageSize  页面大小
 * @param type      请求数据类型 unaudited 默认取进行中的
 * @param keywords  关键字
 * @param isRefresh 是否正在刷新
 * @param noMore    没有更多数据
 */
data class StatePageMessage(
    val page: Int = 1,
    val pageSize: Int = 10,
    val type: String = "",
    val keywords: String = "",
    val isRefresh: Boolean = false,
    val noMore: Boolean = true,
)