package com.base.scanqr.utils

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.ContentUris.withAppendedId
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
import com.base.scanqr.bean.MMediaContract

object ContactUtils {

    private val TAG = "ContactUtils"

    @SuppressLint("Range")
    fun Context.queryTel(contactUri: Uri): String? {
        val cursor = contentResolver.query(
            contactUri,
            null,
            null,
            null,
            null
        )
        cursor?.use {
            if (cursor.moveToFirst()) {
                val phoneId = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID))
                val phoneCursor = contentResolver.query(
                    withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneId),
                    null,
                    null,
                    null,
                    null
                )
                phoneCursor?.use {
                    if (phoneCursor.moveToFirst()) {
                        val phoneNumber =
                            phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                        // 使用phoneNumber
                        return phoneNumber
                    }
                }
            }
        }
        return null
    }

    fun Context.getContractId(lookupUri: Uri): String? {
        val contactId = ContactsContract.Contacts.lookupContact(contentResolver, lookupUri)?.lastPathSegment
        return contactId
    }

    @SuppressLint("Range")
    fun Context.getLookupKey(lookupUri: Uri): String {
        val cursor = contentResolver.query(lookupUri, arrayOf(ContactsContract.Contacts.LOOKUP_KEY), null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                return it.getString(it.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY))
            }
        }
        return ""
    }

    @SuppressLint("Range")
    fun Context.queryMediaContract(lookupUri: Uri): MMediaContract? {

        val contractId = getContractId(lookupUri)
        LogEx.logDebug(TAG, "contractId=$contractId")
        val lookupKey = getLookupKey(lookupUri)
        LogEx.logDebug(TAG, "lookupKey=$lookupKey")

        val bean = MMediaContract()

        if (contractId != null) {
            // 构建查询Uri，使用联系人ID
            val contactUri = withAppendedId(ContactsContract.Contacts.CONTENT_URI, contractId.toLong())
            var cursor: Cursor? = null
            try {
                cursor = contentResolver.query(contactUri, null, null, null, null)
                cursor?.use {
                    if (cursor.moveToFirst()) {
                        val name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY))
                        LogEx.logDebug(TAG, "name=$name")
                        bean.name = name
                    }
                }
                cursor?.close()
            } catch (e: Exception) {
                cursor?.close()
            } finally {
                cursor?.close()
            }

            val phones = queryPhones(contractId)
            LogEx.logDebug(TAG, "phones=${phones.size}")
            bean.phoneList = phones

            val emails = queryContactEmails(contractId)
            LogEx.logDebug(TAG, "emails=${emails.size}")
            bean.emailList = emails

            val addressList = queryContactAddressList(contractId)
            LogEx.logDebug(TAG, "addressList=${addressList.size}")
            bean.addressList = addressList

            return bean
        }

        return null

    }

    private fun Context.queryPhones(contactId: String): List<String> {
        val phones = ArrayList<String>()
        val contactPhoneUri = withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, contactId.toLong())
        var cursor: Cursor? = null
        try {
            // 使用提供的 contactUri 来查询电话号码
            cursor = contentResolver.query(
                contactPhoneUri,
                arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER),
                null,
                null,
                null
            )
            cursor?.use {
                if (cursor.moveToFirst()) {
                    do {
                        val phone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER))
                        phones.add(phone)
                    } while (cursor.moveToNext()) // 使用 moveToNext() 而不是 moveToFirst()
                }
            }
            cursor?.close()
        } catch (e: Exception) {
            // 异常处理
            e.printStackTrace()
        } finally {
            cursor?.close() // 确保在 finally 块中关闭 cursor
        }
        return phones
    }


    @SuppressLint("Range")
    fun Context.queryContactEmails(contactId: String): List<String> {

        val emails = mutableListOf<String>()
        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Email.CONTACT_ID,
            ContactsContract.CommonDataKinds.Email.ADDRESS
        )
        val selection = "${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?"

        val cursor = contentResolver.query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
            projection, selection, arrayOf(contactId), null
        )

        if (cursor != null && cursor.moveToFirst()) {
            do {
                val email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS))
                // 处理获取到的联系人ID和邮件地址
                // 例如，显示在UI上或者保存起来
                emails.add(email)
            } while (cursor.moveToNext())
            cursor.close()
        }

        return emails
    }

    @SuppressLint("Range")
    private fun Context.queryContactAddressList(contactId: String): List<String> {

        val addressList = mutableListOf<String>()

        val projection = arrayOf(
            ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID,
            ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS
        )
        val selection = "${ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID} = ?"

        val cursor = contentResolver.query(
            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
            projection, selection, arrayOf(contactId), null
        )

        if (cursor != null) {
            while (cursor.moveToNext()) {
                val address =
                    cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS))
                addressList.add(address)
            }
            cursor.close()
        }


        return addressList
    }
}