package com.aiosman.ravenow

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.aiosman.ravenow.entity.ChatItem
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnAdvanceMsgListener
import io.openim.android.sdk.models.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * OpenIM 服务
 * 负责处理 OpenIM 的后台消息监听和通知
 */
class OpenIMService : Service() {
    
    companion object {
        private const val TAG = "OpenIMService"
        private const val CHANNEL_ID = "openim_notification"
        private const val NOTIFICATION_ID = 1001
    }
    
    private var openIMMessageListener: OnAdvanceMsgListener? = null
    
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "OpenIMService onStartCommand")
        createNotificationChannel()
        CoroutineScope(Dispatchers.IO).launch {
            registerMessageListener(applicationContext)
        }
        return START_STICKY
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "OpenIMService onDestroy")
        CoroutineScope(Dispatchers.IO).launch {
            unRegisterMessageListener()
        }
    }
    
    /**
     * 注册 OpenIM 消息监听器
     */
    private fun registerMessageListener(context: Context) {
        val scope = CoroutineScope(Dispatchers.IO)
        
        openIMMessageListener = object : OnAdvanceMsgListener {
            override fun onRecvNewMessage(msg: Message?) {
                Log.d(TAG, "收到新消息: ${msg?.toString()}")
                msg?.let {
                    // 如果应用在前台，不显示通知
                    if (MainActivityLifecycle.isForeground) {
                        return
                    }
                    
                    scope.launch {
                        // 检查通知策略
                        val shouldNotify = shouldShowNotification(it)
                        if (shouldNotify) {
                            sendNotification(context, it)
                        }
                    }
                }
            }
            
            override fun onRecvC2CReadReceipt(list: List<C2CReadReceiptInfo>?) {
                Log.d(TAG, "收到C2C已读回执，数量: ${list?.size}")
                // 处理已读回执，可以更新消息状态
            }
            
            override fun onRecvGroupMessageReadReceipt(groupMessageReceipt: GroupMessageReceipt?) {
                Log.d(TAG, "收到群组消息已读回执")
                // 处理群组消息已读回执
            }
            
            override fun onRecvMessageRevokedV2(info: RevokedInfo?) {
                Log.d(TAG, "消息被撤回: ${info?.clientMsgID}")
                // 处理消息撤回，可以更新UI
            }
            
            override fun onRecvMessageExtensionsChanged(msgID: String?, list: List<KeyValue>?) {
                Log.d(TAG, "消息扩展信息变更: $msgID")
                // 处理消息扩展信息变更
            }
            
            override fun onRecvMessageExtensionsDeleted(msgID: String?, list: List<String>?) {
                Log.d(TAG, "消息扩展信息删除: $msgID")
                // 处理消息扩展信息删除
            }
            
            override fun onRecvMessageExtensionsAdded(msgID: String?, list: List<KeyValue>?) {
                Log.d(TAG, "消息扩展信息添加: $msgID")
                // 处理消息扩展信息添加
            }
            
            override fun onMsgDeleted(message: Message?) {
                Log.d(TAG, "消息被删除: ${message?.clientMsgID}")
                // 处理消息删除
            }
            
            override fun onRecvOfflineNewMessage(msg: List<Message>?) {
                Log.d(TAG, "收到离线新消息，数量: ${msg?.size}")
                // 处理离线新消息
                msg?.forEach { message ->
                    // 为离线消息也可以发送通知
                    if (!MainActivityLifecycle.isForeground) {
                        scope.launch {
                            val shouldNotify = shouldShowNotification(message)
                            if (shouldNotify) {
                                sendNotification(context, message)
                            }
                        }
                    }
                }
            }
            
            override fun onRecvOnlineOnlyMessage(s: String?) {
                Log.d(TAG, "收到仅在线消息: $s")
                // 处理仅在线消息
            }
        }
        
        // 添加消息监听器
        OpenIMClient.getInstance().messageManager.setAdvancedMsgListener(openIMMessageListener)
    }
    
    /**
     * 取消注册消息监听器
     */
    private fun unRegisterMessageListener() {
        openIMMessageListener?.let {
            // OpenIM SDK 可能需要不同的方法来移除监听器
            // 这里假设有类似的方法，具体需要根据SDK文档调整
            Log.d(TAG, "取消注册消息监听器")
        }
        openIMMessageListener = null
    }
    
    /**
     * 判断是否应该显示通知
     * @param message 消息对象
     * @return 是否显示通知
     */
    private suspend fun shouldShowNotification(message: Message): Boolean {
        // 这里可以根据用户设置、消息类型等判断是否显示通知
        // 类似于 TrtcService 中的策略检查
        
        // 示例：检查是否是系统消息或者用户设置了免打扰
        return try {
            // 可以根据发送者ID或会话ID检查通知策略
            val senderId = message.sendID
            
            // 这里可以调用类似 ChatState.getStrategyByTargetTrtcId 的方法
            // 暂时返回 true，表示默认显示通知
            true
        } catch (e: Exception) {
            Log.e(TAG, "检查通知策略失败", e)
            true // 默认显示通知
        }
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "OpenIM 消息通知"
            val descriptionText = "OpenIM 即时消息通知"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
                enableVibration(true)
                enableLights(true)
            }
            
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 发送通知
     * @param context 上下文
     * @param message OpenIM 消息对象
     */
    private fun sendNotification(context: Context, message: Message) {
        try {
            // 创建点击通知后的意图
            val intent = Intent(context, MainActivity::class.java).apply {
                putExtra("ACTION", "OPENIM_NEW_MESSAGE")
                putExtra("SENDER_ID", message.sendID)
                putExtra("CONVERSATION_ID", message.sessionType)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            }
            
            val pendingIntent: PendingIntent = PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            
            // 构建通知内容
            val senderName = getSenderDisplayName(message)
            val messageContent = getMessageDisplayContent(message)
            
            val builder = NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.mipmap.rider_pro_log_round)
                .setContentTitle(senderName)
                .setContentText(messageContent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setVibrate(longArrayOf(0, 300, 300, 300))
                .setLights(0xFF0000FF.toInt(), 300, 300)
            
            // 发送通知
            with(NotificationManagerCompat.from(context)) {
                if (ActivityCompat.checkSelfPermission(
                        context,
                        Manifest.permission.POST_NOTIFICATIONS
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    Log.w(TAG, "没有通知权限，无法发送通知")
                    return
                }
                
                // 使用消息ID的哈希值作为通知ID，确保每条消息都有唯一的通知
                val notificationId = message.clientMsgID?.hashCode() ?: NOTIFICATION_ID
                notify(notificationId, builder.build())
            }
            
            Log.d(TAG, "发送通知成功: $senderName - $messageContent")
            
        } catch (e: Exception) {
            Log.e(TAG, "发送通知失败", e)
        }
    }
    
    /**
     * 获取发送者显示名称
     * @param message 消息对象
     * @return 发送者名称
     */
    private fun getSenderDisplayName(message: Message): String {
        return try {
            // 尝试获取发送者的昵称或显示名
            message.senderNickname?.takeIf { it.isNotEmpty() } 
                ?: message.sendID 
                ?: "未知用户"
        } catch (e: Exception) {
            Log.e(TAG, "获取发送者名称失败", e)
            "未知用户"
        }
    }
    
    /**
     * 获取消息显示内容
     * @param message 消息对象
     * @return 消息内容
     */
    private fun getMessageDisplayContent(message: Message): String {
        return try {
            when (message.contentType) {
                101 -> message.textElem.content ?: "[文本消息]" // 文本消息
                102 -> "[图片]"
                103 -> "[语音]"
                104 -> "[视频]"
                105 -> "[文件]"
                106 -> "[位置]"
                107 -> "[自定义消息]"
                108 -> "[合并消息]"
                109 -> "[名片]"
                110 -> "[引用消息]"
                else -> "[消息]"
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取消息内容失败", e)
            "[消息]"
        }
    }
}
