package com.ydl.ydlcommon.actions.imagepicker;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;

import com.miracle.view.imageeditor.utils.FileUtils;
import com.yidianling.common.tools.RxFileTool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ImageCompress {
    public static File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );
        return image;
    }

    public static File scal(FragmentActivity activity, String path, int size) {
//		String path = fileUri.getPath();
        File outputFile = FileUtils.INSTANCE.getFileByUri(activity,path);
        if (!outputFile.exists()){
            return null;
        }
        long fileSize = outputFile.length();
        final long fileMaxSize = size * 1024;
        if (fileSize >= fileMaxSize) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;

            double scale = Math.sqrt((float) fileSize / fileMaxSize);
            options.outHeight = (int) (height / scale);
            options.outWidth = (int) (width / scale);
            options.inSampleSize = (int) (scale + 0.5);
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            outputFile = new File(PhotoUtil.createImageFile().getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("", "sss ok " + outputFile.length());
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(PhotoUtil.createImageFile().getPath());
                PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
            }

        }
        return outputFile;

    }

    public static File scaln(String path, int size) {
//		String path = fileUri.getPath();
        File outputFile = new File(path);
//		long fileSize = outputFile.length();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap imagebm = BitmapFactory.decodeFile(path);
        imagebm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//		final long fileMaxSize = size * 1024;
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > size) {
            // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            imagebm.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
            if (options <= 0) {
                break;
            }
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        // 把ByteArrayInputStream数据生成图片
        imagebm = BitmapFactory.decodeStream(isBm, null, null);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputFile);
            imagebm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!imagebm.isRecycled()) {
            imagebm.recycle();
        } else {
            File tempFile = outputFile;
            outputFile = new File(PhotoUtil.createImageFile().getPath());
            PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
        }

        return outputFile;

    }

    public static File scaln2(String path, int size) {
        Bitmap bm = BitmapFactory.decodeFile(path);
        bm=cQuality(bm,size);
        File outputFile = null;
        try {
            outputFile = SaveBitmap(bm,path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputFile;

    }
    public static File SaveBitmap(Bitmap mBitmap, String path) throws IOException {
        File file;
        RxFileTool.fileExists(path);
        File f = new File(path);
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file=new File(path);
        return file;
    }

    /**
     * 根据bitmap压缩图片质量
     *
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    public static Bitmap cQuality(Bitmap bitmap,int size) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        int beginRate = 100;
        //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
        while (bOut.size() / 1024 / 1024 > size) {  //如果压缩后大于100Kb，则提高压缩率，重新压缩
            beginRate -= 10;
            bOut.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
        }
        ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        if (newBitmap != null) {
            return newBitmap;
        } else {
            return bitmap;
        }
    }
}
