package com.common.commonlib.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*


object PhotoUtils {
    private const val TAG = "PhotoUtils";

    /**
     * 根据时间生成照片文件
     */
    fun generatePhotoFileByTime(context: Context, photoPath: String): File {
        val rootPath: String = context.applicationContext.getExternalFilesDir(null)?.path ?: ""
        val savePhotoFolderPath: String = rootPath + photoPath
        val savePhotoFolder = File(savePhotoFolderPath)
        if (!savePhotoFolder.exists()) {
            //创建路径，需要权限
            savePhotoFolder.mkdirs()
        }
        val photoName = SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS").format(Date()) + ".png"

        return File(savePhotoFolder, photoName)

    }

    fun initPicPath(context: Context?, photoPath: String): String {
        val rootPath: String = context?.getExternalFilesDir(null)?.path ?: ""
        val savePhotoFilePath: String = rootPath + photoPath
        val file = File(savePhotoFilePath)
        if (!file.exists()) {
            //创建路径，需要权限
            file.mkdirs()
        }
        val photoName = SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS").format(Date()) + ".png"
        return "$savePhotoFilePath/$photoName"
    }

    /**
     * 得到保存图片的文件夹地址
     */
    fun getImageParentPath(context: Context, photoPath: String): String {
        val rootPath: String = context.getExternalFilesDir(null)?.path ?: ""
        val savePhotoFilePath: String = rootPath + photoPath
        val file = File(savePhotoFilePath)
        if (!file.exists()) {
            //创建路径，需要权限
            file.mkdirs()
        }
        return savePhotoFilePath
    }

    /**
     * 压缩图片，使用Luban框架压缩处理
     */
    fun compressPicture(
        context: Context,
        file: File,
        targetDir: String,
        listener: OnCompressListener
    ) {
        Luban.with(context.applicationContext)
            .load(file)
            .ignoreBy(100)
            .setTargetDir(targetDir)
            .setCompressListener(listener).launch()
    }

    /**
     *把其他格式的图片转换成png格式的图片，耗时操作
     * originImageFile：原图片文件
     * imgSavePath：图片要保存的地址，如：/sdcard/0/emulator/data/xxx.xxx.xx/file/test.png
     */
    fun tans2PNGSave(originImageFile: File?, imgSavePath: String?, callBack: TransformCallBack) {
        GlobalScope.launch(Dispatchers.IO) {
            val decodeFile = BitmapFactory.decodeFile(originImageFile?.absolutePath)
            var out: FileOutputStream? = null
            try {
                out = FileOutputStream(File(imgSavePath))
                decodeFile.compress(Bitmap.CompressFormat.PNG, 90, out)
                out.flush()
                out.close()
            } catch (e: Exception) {
                Log.e(TAG, "tans2PNGSave error==" + e.message)
            } finally {
                out?.close()
            }

            GlobalScope.launch(Dispatchers.Main) {
                //通知主线程图片保存成功
                callBack.onSuccess()
            }
        }
    }

    interface TransformCallBack {
        fun onSuccess()
        fun onError();
    }
}
