package com.grkj.iscs.util

import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.Manifest.permission.BLUETOOTH_ADVERTISE
import android.Manifest.permission.BLUETOOTH_CONNECT
import android.Manifest.permission.BLUETOOTH_SCAN
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import com.grkj.iscs.MyApplication
import com.grkj.iscs.model.Constants.PERMISSION_REQUEST_CODE
import pub.devrel.easypermissions.EasyPermissions
import java.text.SimpleDateFormat
import java.util.Locale

object CommonUtils {

    val hexRegex = "^[0-9A-Fa-f]+$".toRegex()

    fun dip2px(dpValue: Float): Int {
        val density = MyApplication.instance!!.resources.displayMetrics.density
        return (dpValue * density + 0.5f).toInt()
    }

    fun px2dip(pxValue: Float): Float {
        val density = MyApplication.instance!!.resources.displayMetrics.density
        return pxValue / density
    }

    fun checkPermission(activity: AppCompatActivity, permissions: Array<String>, callBack: () -> Unit) {
        val isPermission = EasyPermissions.hasPermissions(activity, *permissions)
        if (isPermission) {
            callBack.invoke()
        } else {
            EasyPermissions.requestPermissions(activity, "", PERMISSION_REQUEST_CODE, *permissions)
        }
    }

    fun checkBlePermission(activity: AppCompatActivity, callBack: () -> Unit) {
        val permissions: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                BLUETOOTH_SCAN,
                BLUETOOTH_ADVERTISE,
                BLUETOOTH_CONNECT,
                ACCESS_FINE_LOCATION,
                ACCESS_COARSE_LOCATION
            )
        } else {
            arrayOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)
        }
        checkPermission(activity, permissions, callBack)
    }

    fun getStr(textId: Int, ctx: Context? = null): String? {
        return ctx?.resources?.getString(textId) ?: let {
            MyApplication.instance?.applicationContext?.resources?.getString(textId)
        }
    }

    fun getDiffHours(dateString: String?): Int? {
        if (dateString.isNullOrEmpty()) {
            return null
        }
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val date = format.parse(dateString)
        if (date != null) {
            // 将 Date 对象转换为时间戳（毫秒）
            val timestamp = date.time
            // 获取当前时间的时间戳
            val currentTimestamp = System.currentTimeMillis()
            // 计算时间差（毫秒）
            val timeDifferenceInMillis = currentTimestamp - timestamp
            // 将时间差转换为小时数，向下取整
            val hoursDifference = (timeDifferenceInMillis / (1000 * 60 * 60)).toInt()

            return hoursDifference
        }
        return null
    }

    fun isValidHex(hexString: String): Boolean {
        return hexRegex.matches(hexString)
    }
}