package com.xty.common.picture

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.text.TextUtils
import android.widget.ImageView
import cc.shinichi.library.ImagePreview
import cc.shinichi.library.bean.ImageInfo
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.xty.common.R
import com.xty.common.getImageUrl
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.*


/**
 * 拍照调用
 */
class PictureUtils {

    companion object {
        /**
         *  选择图片或者拍照
         */
        fun openCamera(act: Activity, type: Int = PictureMimeType.ofImage(), selectMax: Int = 1) {
            PictureSelector.create(act)
                //  .openGallery(PictureMimeType.ofAll())
                .openGallery(type)
                .imageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .isCompress(true)//是否压缩
                .maxSelectNum(selectMax)
                .minimumCompressSize(100)//图片压缩后输出质量
                .forResult(PictureConfig.CHOOSE_REQUEST)
        }

        fun openTheCamera(act: Activity, type: Int = PictureMimeType.ofImage()){
            PictureSelector.create(act)
                .openCamera(type)
                .imageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .isCompress(true)//是否压缩
                .forResult(PictureConfig.CHOOSE_REQUEST)
        }



        /**
         *  选择图片或者拍照
         */
        fun openCameraShow(
            act: Activity,
            type: Int = PictureMimeType.ofImage(),
            selectMax: Int,
            list: MutableList<LocalMedia>
        ) {
            PictureSelector.create(act)
                //  .openGallery(PictureMimeType.ofAll())
                .openGallery(type)
                .imageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .isCompress(true)//是否压缩
                .maxSelectNum(selectMax)
                .minimumCompressSize(100)//图片压缩后输出质量
                .selectionData(list)
                .forResult(PictureConfig.CHOOSE_REQUEST)
        }

        fun previewImage(act: Activity, position: Int, result: List<LocalMedia>) {
            PictureSelector.create(act)
                .themeStyle(R.style.picture_default_style)
                .isNotPreviewDownload(true)
                .imageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .openExternalPreview(position, result)

        }

        /**
         * prefixUrl  图片如果要加前缀地址 请传入
         */
        fun httpPreviewImage(context: Context, start: Int, list: MutableList<String>,prefixUrl:String="") {
            var listInfo = mutableListOf<ImageInfo>()
            list.forEach {
                listInfo.add(ImageInfo().apply {
                    this.originUrl = getImageUrl(it, prefixUrl)
                    this.thumbnailUrl = getImageUrl(it, prefixUrl)
                })
            }
            ImagePreview
                .getInstance()
                .setContext(context)
                .setIndex(start)// 默认显示第几个
                .setImageInfoList(listInfo)// 图片集合
                .setShowDownButton(false)// 是否显示下载按钮
                .setScaleLevel(1, 3, 8)// 设置三级放大倍数，分别是最小、中等、最大倍数。
                .setZoomTransitionDuration(500)// 设置缩放的动画时长
                .start();// 开始跳转
        }

        //获取视频第一帧
        //仅限本地视频
        fun getVideoThumb(path: String?, imageView: ImageView) {
            MainScope().launch {
                val media = MediaMetadataRetriever()
                media.setDataSource(path) // videoPath 本地视频的路径
                val bitmap = media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
                imageView.setImageBitmap(bitmap)
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                imageView.tag = path
            }
        }


        /**
         * 保存图片到本地
         */
        fun saveBitmapToFile(savePath: String, bitmap: Bitmap) {
            if (TextUtils.isEmpty(savePath)) {
                return
            }
            val bos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
            val buffer = bos.toByteArray()
            if (buffer != null) {
                val file = File(savePath)
                if (file.exists()) {
                    file.delete()
                }
                val os: OutputStream = FileOutputStream(file)
                os.write(buffer)
                os.close()
                bos.close()
            }
        }
    }

}