package com.remax.visualnovel.repository.ext

import com.remax.visualnovel.entity.imbean.IMAIInMessage
import com.remax.visualnovel.entity.imbean.IMBaseInfoMessage
import com.remax.visualnovel.entity.imbean.IMCallMessage
import com.remax.visualnovel.entity.imbean.IMGiftMessage
import com.remax.visualnovel.entity.imbean.IMInImageMessage
import com.remax.visualnovel.entity.imbean.IMLevelMessage
import com.remax.visualnovel.entity.imbean.IMMessageWrapper
import com.remax.visualnovel.entity.imbean.IMOutImageMessage
import com.remax.visualnovel.entity.imbean.raw.CustomAlbumData
import com.remax.visualnovel.entity.imbean.raw.CustomCallData
import com.remax.visualnovel.entity.imbean.raw.CustomGiftData
import com.remax.visualnovel.entity.imbean.raw.CustomLevelChangeData
import com.remax.visualnovel.entity.imbean.raw.CustomRawData
import com.remax.visualnovel.entity.imbean.voice.IMVoice
import com.remax.visualnovel.entity.request.SimpleTypeDTO
import com.remax.visualnovel.entity.response.Character
import com.remax.visualnovel.extension.convertFromJson
import com.remax.visualnovel.manager.nim.FetchResult
import com.remax.visualnovel.manager.nim.NimManager
import com.remax.visualnovel.ui.chat.message.call.manager.RTCManager
import com.remax.visualnovel.ui.wallet.manager.WalletManager
import com.netease.nimlib.sdk.v2.message.V2NIMMessage
import com.netease.nimlib.sdk.v2.message.V2NIMMessageCreator
import com.netease.nimlib.sdk.v2.message.enums.V2NIMMessageSendingState
import com.netease.nimlib.sdk.v2.message.enums.V2NIMMessageType

/**
 * Created by HJW on 2025/8/26
 */


/**
 * 转化一下消息类
 * 适配一下多布局
 */
fun List<V2NIMMessage>?.convertMessage(hasMore: Boolean, character: Character?): List<IMMessageWrapper> {
    val result = this?.map { v2NIMMessage -> v2NIMMessage.convertMessage(true) }
        ?.filter { messageWrapper -> messageWrapper?.fetchType != FetchResult.FetchType.Remind }
        ?.toMutableList()
    if (!hasMore) {
        result?.add(0, IMBaseInfoMessage(character))
        /**
         * 没有聊过天需要添加开场白
         */
        if (character?.isDelChatted != true) {
            val prologueMsg = V2NIMMessageCreator.createTextMessage(character?.dialoguePrologue)
            val prologue = IMAIInMessage(prologueMsg, IMVoice(prologueMsg.messageClientId ?: ""))
            result?.add(0, prologue)
        }
    }
    return result?.filterNotNull() ?: emptyList()
}

/**
 * @param fromHistory 是否从消息历史解析
 */
fun V2NIMMessage.convertMessage(fromHistory:Boolean = false): IMMessageWrapper? {
    var aiIsSending = true
    var fetchType = when {
        // 收到的消息总是展示
        !this.isSelf -> FetchResult.FetchType.Add
        // 自己发送的消息先loading
        this.sendingState == V2NIMMessageSendingState.V2NIM_MESSAGE_SENDING_STATE_SENDING -> FetchResult.FetchType.Add
        // AI只回复发送成功的
        else -> {
            aiIsSending = this.sendingState == V2NIMMessageSendingState.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED
            FetchResult.FetchType.Update
        }
    }
    NimManager.log("消息转换 messageServerId:${this.messageServerId} text:${this.text}  attachment.raw:${this.attachment?.raw}  serverExtension:${this.serverExtension}")
    val res = when (messageType) {
        V2NIMMessageType.V2NIM_MESSAGE_TYPE_TEXT -> {
            if (isSelf) IMMessageWrapper(this)
            else IMAIInMessage(this, IMVoice(this.messageServerId.toString()))
        }

        V2NIMMessageType.V2NIM_MESSAGE_TYPE_CUSTOM -> {
            val type = attachment?.raw?.convertFromJson<SimpleTypeDTO>()?.type?.uppercase()
            when (type) {
                /**
                 * 用户发送给AI的图片消息
                 */
                CustomRawData.IMAGE -> {
                    if (isSelf) {
                        IMOutImageMessage(this, attachment?.raw?.convertFromJson<CustomRawData>())
                    } else {
                        IMInImageMessage(this, attachment?.raw?.convertFromJson<CustomAlbumData>())
                    }
                }

                /**
                 * 用户发送给AI的礼物消息
                 */
                CustomRawData.GIFT -> {
                    if (isSelf) {
                        IMGiftMessage(this, attachment?.raw?.convertFromJson<CustomGiftData>())
                    } else null
                }

                /**
                 * 心动等级变化
                 */
                CustomRawData.HEARTBEAT_LEVEL_UP, CustomRawData.HEARTBEAT_LEVEL_DOWN -> {
                    fetchType = FetchResult.FetchType.Remind
                    aiIsSending = false
                    val msg = IMLevelMessage(this, attachment?.raw?.convertFromJson<CustomLevelChangeData>())
                    RTCManager.sendIMLevelMessage(msg)
                    msg
                }

                CustomRawData.VOICE_CHAT_EMOTION_SCORE -> {
                    aiIsSending = false
                    fetchType = FetchResult.FetchType.Remind
                    null
                }

                CustomRawData.INSUFFICIENT_BALANCE -> {
                    aiIsSending = false
                    fetchType = FetchResult.FetchType.Remind
                    WalletManager.refreshWallet()
                    if (!fromHistory){
                        RTCManager.balanceInsufficient()
                    }
                    null
                }

                /**
                 * 拨打语音电话
                 * 语音通话消息不需要回话
                 */
                CustomRawData.CALL -> {
                    aiIsSending = false
                    IMCallMessage(this, attachment?.raw?.convertFromJson<CustomCallData>())
                }

                else -> null
            }
        }

        else -> null
    }

    return res?.apply {
        this.fetchType = fetchType
        this.aiIsSending = aiIsSending
    }
}
