package com.kaixed.kchat.repository

import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.Contact
import com.kaixed.kchat.data.objectbox.entity.Contact_
import com.kaixed.kchat.model.friend.FriendRequestItem
import com.kaixed.kchat.model.search.User
import com.kaixed.kchat.network.RetrofitClient
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.utils.Pinyin4jUtil
import com.kaixed.kchat.utils.handle.ContactUtil
import io.objectbox.Box

class ContactRepository {

    private val contactApiService = RetrofitClient.contactApiService

    private val contactBox: Box<Contact> by lazy {
        get().boxFor(Contact::class.java)
    }

    // 获取联系人请求列表
    suspend fun getContactRequestList(username: String): Result<List<FriendRequestItem>?> {
        return try {
            val response = contactApiService.getContactRequestList(username)
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    Result.success(searchUser)
                } ?: Result.failure(Exception("没有好友申请"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 接受联系人请求
    suspend fun acceptContactRequest(
        username: String,
        contactId: String,
        remark: String
    ): Result<Contact?> {
        return try {
            val response = contactApiService.acceptContactRequest(contactId, username, remark)
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    ContactUtil.handleContact(searchUser)
                    Result.success(searchUser)
                } ?: Result.failure(Exception("添加好友失败"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 删除联系人
    suspend fun deleteContact(
        username: String,
        contactId: String,
    ): Result<String?> {
        return try {
            val response = contactApiService.deleteContact(username, contactId)
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    val con =
                        contactBox.query(Contact_.username.equal(contactId)).build().findFirst()
                    contactBox.remove(con!!)
                    Result.success(searchUser)
                } ?: Result.failure(Exception("删除好友失败"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 添加联系人
    suspend fun addContact(contactId: String, message: String): Result<String> {
        return try {
            val response = contactApiService.addContact(
                senderId = contactId,
                receiverId = getUsername(),
                message = message
            )
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    Result.success(searchUser)
                } ?: Result.failure(Exception("添加联系人失败"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 搜索联系人
    suspend fun searchContact(username: String): Result<User?> {
        return try {
            val response = contactApiService.searchContact(username)
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    Result.success(searchUser)
                } ?: Result.failure(Exception("没有找到用户"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 获取联系人列表
    suspend fun getContactList(username: String): Result<List<Contact>?> {
        return try {
            val response = contactApiService.getContactList(username)
            if (response.isSuccess()) {
                val searchUsers = response.getResponseData()
                searchUsers?.let {

                    val uiFriendList = searchUsers?.map { networkItem ->
                        mapToFriendItem(networkItem) // 数据转换
                    }?.sortedWith { f1, f2 ->
                        val str1 = f1.remarkquanpin ?: f1.quanpin ?: f1.nickname
                        val str2 = f2.remarkquanpin ?: f2.quanpin ?: f2.nickname

                        val type1 = when {
                            str1.matches(Regex("[a-zA-Z]+")) -> 1  // 字母
                            str1.matches(Regex("[0-9]+")) -> 2    // 数字
                            else -> 3                            // 特殊字符
                        }

                        val type2 = when {
                            str2.matches(Regex("[a-zA-Z]+")) -> 1  // 字母
                            str2.matches(Regex("[0-9]+")) -> 2    // 数字
                            else -> 3                            // 特殊字符
                        }

                        // 比较类型，如果相同再按字母升序排序
                        if (type1 != type2) {
                            type1 - type2  // 按类型排序
                        } else {
                            str1.compareTo(str2)  // 如果类型相同，按字母顺序排序
                        }
                    }

                    // 设置是否显示分组头
                    uiFriendList?.forEachIndexed { index, item ->
                        item.showHeader =
                            (index == 0 || item.quanpin?.get(index) != uiFriendList[index - 1].quanpin?.get(
                                index - 1
                            ))
                    }

                    Result.success(searchUsers)
                } ?: Result.failure(Exception("当前没有好友"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    private fun mapToFriendItem(response: Contact): Contact {
        val pinyin = Pinyin4jUtil.toPinyin(response.nickname)
        response.remark?.let {
            response.remarkquanpin = Pinyin4jUtil.toPinyin(it)
        }
        response.quanpin = pinyin
        return response
    }
}
