package com.cheng.blzb.utils

import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.base.extensions.toast
import com.example.base.utils.L
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


object ImageUtils {
    private const val TAG = "ImageUtils"
    @RequiresApi(api = Build.VERSION_CODES.Q)
    fun saveImageToGallery(context: Context, bitmap: Bitmap, folderName: String) {
        val contentResolver = context.contentResolver
        val contentValues = ContentValues()
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, generateFileName())
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + File.separator + folderName)
        var outputStream: OutputStream? = null
        try {
            // 将图片插入相册
            val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            if (uri != null) {
                outputStream = contentResolver.openOutputStream(uri)
                if (outputStream != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
                    outputStream.close()
                    L.d("Image saved to gallery")
                    return
                }
            }
        } catch (e: Exception) {
            L.e("Failed to save image to gallery: " + e.message)
        } finally {
            try {
                outputStream?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        Log.e(TAG, "Failed to save image to gallery")
    }

    fun generateFileName(): String {
        val sdf = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
        return ("IMG_" + sdf.format(Date())) + ".jpeg"
    }

    fun scanImageFile(context: Context?, filePath: String) {
        MediaScannerConnection.scanFile(context, arrayOf(filePath), null, null)
    }

    fun saveBitmap(mContext:Context,image:Bitmap,path:String):Boolean{
        // 首先保存图片

        val appDir = File(path)
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpeg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            // 通过io流的方式来压缩保存图片
            val isSuccess: Boolean = image.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()

            // 保存图片后发送广播通知更新数据库
            val uri = Uri.fromFile(file)
            mContext.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            if (isSuccess) toast("保存成功")
            return isSuccess
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return false
    }

    fun checkPermission(context: Context?): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(context!!, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        } else {
            (ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        }
    }

    fun requestPermission(activity: Activity?, requestCode: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.requestPermissions(
                activity!!, arrayOf<String>(Manifest.permission.READ_MEDIA_IMAGES),
                requestCode
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ActivityCompat.requestPermissions(
                activity!!, arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                requestCode
            )
        } else {
            ActivityCompat.requestPermissions(
                activity!!, arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
                requestCode
            )
        }
    }
}