package com.zswc.creativity.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;


import com.ysnows.base.utils.UiUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SaveLocalUtils {


    public static Bitmap returnBitMap(final String url) {


//        String url1;

//        try {
//            url1 = url.substring(0, url.indexOf("?"));
//
//        } catch (Exception e) {
//            url1 = url;
//        }


        Bitmap bitmap = null;

        URL imageurl = null;

        try {
            imageurl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("--shy-", "e=: "+e );
        }


        return bitmap;
    }

    /**
     * 保存图片到本地
     *
     * @param context
     * @param bmp
     * @param picName
     */
    public static String saveBmp2Gallery(Context context, Bitmap bmp, String picName) {

//        File appDir = new File(Environment.getExternalStorageDirectory(), "CANDYIMG");
//        if (!appDir.exists()) {
//            appDir.mkdir();
//        }
//        String filePath = Environment.getExternalStorageDirectory() + "/CANDYIMG/";

        //创建文件路径
        File dir=new File(context.getExternalFilesDir(null).getPath()+"CANDYIMG");
        if (!dir.exists()){
            dir.mkdir();
        }

        // 声明文件对象
        File file = null;
        // 声明输出流
        try {

            //创建文件
             file = new File(dir+"/"+picName + ".png");
            if (!file.exists()){
                file.createNewFile();
            }

            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            //file = new File(filePath, picName + ".png");
            // 获得输出流，如果文件中有内容，追加内容
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(new Intent(intent));
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.getStackTrace();

            Log.e("--shy-", "e222=: "+e );

        }
        return "";
    }


    /**
     * 将view转成bitmap
     */
    public static Bitmap setCreateBitmap(String url) {

        URL myFileUrl;
        Bitmap cachebmp = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            cachebmp = BitmapFactory.decodeStream(is);
            return cachebmp;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;



    }


    /**
     * 将view转成bitmap
     */
    public static Bitmap setCreateBitmap2(Context context, Bitmap background, Bitmap foreground) {

        int bgWidthNew = UiUtils.dp2Px(context,214);
        int bgHeightNew = UiUtils.dp2Px(context,380);
        int fgWidthNew = UiUtils.dp2Px(context,54);
        int fgHeightNew = UiUtils.dp2Px(context,54);

        Bitmap bgBitmapNew = restartImg(background,bgWidthNew,bgHeightNew);
        Bitmap fgBitmapNew = restartImg(foreground,fgWidthNew,fgHeightNew);

        Bitmap newBitmap = Bitmap.createBitmap(bgWidthNew, bgHeightNew, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawBitmap(bgBitmapNew, 0, 0, null);
        canvas.drawBitmap(fgBitmapNew, (bgWidthNew - fgWidthNew) / 2,
                        bgHeightNew-fgHeightNew- UiUtils.dp2Px(context,14), null);
        canvas.save();
        canvas.restore();
        return newBitmap;

    }

    public static Bitmap restartImg(Bitmap bitMap, int newWidth, int newHeight){

        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);
        return bitMap;
    }



    /*
     * 保存文件，文件名为当前日期
     */
    public static  boolean saveBitmap(Context context, Bitmap bitmap, String bitName) {


        String fileName;
        File file;
        String brand = Build.BRAND;

        if (brand.equals("xiaomi")) { // 小米手机brand.equals("xiaomi")
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else if (brand.equalsIgnoreCase("Huawei")) {
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
//        fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        if (Build.VERSION.SDK_INT >= 29) {
//            boolean isTrue = saveSignImage(bitName, bitmap);
            saveSignImage(context,bitName,bitmap);
            Log.e("shy", "ss=" + Uri.parse("file://" + fileName));

            return true;
//            file= getPrivateAlbumStorageDir(NewPeoActivity.this, bitName,brand);
//            return isTrue;
        } else {
            Log.v("saveBitmap brand", "" + brand);
            file =new File(fileName);
        }
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
// 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.DATA,  file.getAbsolutePath());
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                }else{
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), bitName, null);

                }

            }

        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", "FileNotFoundException:" + e.getMessage().toString());
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            Log.e("IOException", "IOException:" + e.getMessage().toString());
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            Log.e("IOException", "IOException:" + e.getMessage().toString());
            e.printStackTrace();
            return false;

// 发送广播，通知刷新图库的显示

        }
//        if(Build.VERSION.SDK_INT >= 29){
//            copyPrivateToDownload(this,file.getAbsolutePath(),bitName);
//        }

        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

        return true;

    }


    //将文件保存到公共的媒体文件夹
//这里的filepath不是绝对路径，而是某个媒体文件夹下的子路径，和沙盒子文件夹类似
//这里的filename单纯的指文件名，不包含路径
    public static void saveSignImage(/*String filePath,*/Context context, String fileName, Bitmap bitmap) {
        try {
            //设置保存参数到ContentValues中
            ContentValues contentValues = new ContentValues();
            //设置文件名
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            //兼容Android Q和以下版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
                //RELATIVE_PATH是相对路径不是绝对路径
                //DCIM是系统文件夹，关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
                contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/");
                //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Music/signImage");
            } else {
                contentValues.put(MediaStore.Images.Media.DATA, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
            }
            //设置文件类型
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
            //执行insert操作，向系统文件夹中添加文件
            //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            if (uri != null) {
                //若生成了uri，则表示该文件添加成功
                //使用流将内容写入该uri中即可
                OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
                if (outputStream != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
                    outputStream.flush();
                    outputStream.close();
                }
            }
        } catch (Exception e) {
        }
    }






}
