package com.mayi.fastdevelop.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;

import com.mayi.fastdevelop.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;

public class ImageUtil {


    /**
     * 保存网络图片
     *
     * @param context
     * @param url
     */
    public static void saveBitmap(Context context, String url) {
        final WeakReference<Context> weakReference = new WeakReference<>(context);
        if (TextUtils.isEmpty(url)) {
            ToastUtil.show(context, context.getString(R.string.save_img_failed_2));
            return;
        }
        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Context c = weakReference.get();
                if (c != null) {
                    saveBitmap(bitmap, Environment.getExternalStorageDirectory().toString() + "/" + c.getPackageName() + "/picture/" + System.currentTimeMillis() + ".jpg");
                    //刷新相册
                    c.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString() + "/" + c.getPackageName()))));
                    ToastUtil.show(c, c.getString(R.string.save_img_success));
                }
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Context c = weakReference.get();
                if (c != null) {
                    ToastUtil.show(c, c.getString(R.string.save_img_failed));
                }
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };
        Picasso.with(context).load(url).into(target);
    }


    /**
     * 保存图片
     *
     * @param mBitmap  目标图片
     * @param fileName 目标文件
     */
    public static void saveBitmap(Bitmap mBitmap, String fileName) {
        try {
            File file = new File(fileName);
            FileOutputStream out = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某个view的截图
     *
     * @param view 目标view
     */
    public static Bitmap getViewImage(View view) {
        Bitmap image = null;
        try {
            view.setDrawingCacheEnabled(true); //获取view缓存
            view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
            // 拷贝图片，否则在setDrawingCacheEnabled(false)以后该图片会被释放掉
            Bitmap cacheBitmap = view.getDrawingCache();

            //方案1 （图片显示模糊）
//         image = Bitmap.createBitmap(cacheBitmap);

            //方案2 （图片显示模糊）

//            float scale = 320f / cacheBitmap.getWidth();
//            int height = (int) (cacheBitmap.getHeight() * scale);
//            image = Bitmap.createScaledBitmap(cacheBitmap, 320, height, true);

            //方案3
//            image = scaleImageCavans(cacheBitmap, DensityUtil.dip2px(view.getContext(), 320), DensityUtil.dip2px(view.getContext(), 240));
//            image = scaleImageCavans(cacheBitmap, 320, 240);

            //方案4
            // Matrix类进行图片处理（缩放）
            Matrix matrix = new Matrix();
            // 缩小
            matrix.setScale(320f / cacheBitmap.getWidth(), 320f / cacheBitmap.getWidth());
            // 生成新的图片
            image = Bitmap.createBitmap(cacheBitmap, 0, 0, cacheBitmap.getWidth(), cacheBitmap.getHeight(), matrix, true);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            view.setDrawingCacheEnabled(false);//释放缓存
        }
        return image;
    }


    private static PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

    public static Bitmap scaleImageCavans(Bitmap bm, int newWidth, int newHeight) {
        //应用图标缩放
        if (bm == null) {
            return null;
        }
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Bitmap newbm = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(newbm);
        Paint mPaint = new Paint();
        mPaint.setXfermode(null);
        mPaint.setAntiAlias(true);
        mCanvas.save();
        mCanvas.scale(scaleWidth, scaleHeight);
        //保证图标不失真
        mCanvas.setDrawFilter(pfd);
        mCanvas.drawBitmap(bm, 0, 0, null);
        mCanvas.restore();
        if (!bm.isRecycled()) {
            bm.recycle();
        }
        return newbm;
    }

}
