package com.base.scanqr.utils

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract

object 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(
                    ContentUris.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
    }
}