package com.tofly.ghrq_route.common.util.image;

/**
 * Created by zombiexq on 2016/6/24.
 */

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.common.ui.activity.UiBigImageList;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Locale;

public class ImageUtil implements Serializable{

    /*
     * 图片按比例大小压缩方法（根据Bitmap图片压缩）
     */
    private static ImageLoader loader;

    private ArrayList<String> mPicList;

    private Context mContext;

    public static final String PICS_PATH_KEY = "pics_path";

    public static final String CURRENT_PATH_KEY = "current_path";

    public ArrayList<String> getPicList() {
        return mPicList;
    }

    public void setPicList(ArrayList<String> mPicList) {
        this.mPicList = mPicList;
    }

    public void clearPicList(){
        if (mPicList != null){
            mPicList.clear();
            mPicList = null;
        }
    }

    public void removePic(String path){
        if (mPicList != null){
            int index = mPicList.indexOf(path);
            if (index != -1){
                mPicList.remove(index);
            }
        }
    }

    public ImageUtil (Context context){
        mContext = context;
    }

    public static Bitmap comp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        newOpts.inPreferredConfig = Config.RGB_565;// 降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    public static Bitmap loadImageFromFilePath(String picAbsolutePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(picAbsolutePath, options);
    }

    /*
     * 图片按比例大小压缩方法（根据路径获取图片并压缩）
     */
    public static Bitmap getimage(String srcPath, int mWidth, int mHeight) {
        if (srcPath == null || srcPath.isEmpty())
            return null;

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = mHeight;// 这里设置高度为800f
        float ww = mWidth;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }

    /*
     * 质量压缩法
     */
    private static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            Log.e("[Android]", e.getMessage());
            Log.e("[Android]", "目录为：" + uri);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 文件转换base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String fileToBase64(File file){

        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[(int) file.length()];
        try {
            inputFile.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(buffer, Base64.DEFAULT);//转化为字符串
    }

    public View getViewFromPath(final String path) {
        return getViewFromPath(path, false, 0);
    }

    public View getViewFromPath(final String path, boolean isVideo, long videoLength) {
/*        if (path == null || !FileUtil.fileExists(path))
            return null;*/

        Bitmap bitmap = ImageUtil.getimage(path, 480, 800);
        FrameLayout layout = new FrameLayout(mContext);
        layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        int width = BaseApp.getInstance().dip2px(100);
        int height = BaseApp.getInstance().dip2px(100);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width, height);
        lp.setMargins(10, 10, 10, 10);
        lp.gravity = Gravity.CENTER;

        ImageView imageView = new ImageView(mContext);
        imageView.setLayoutParams(lp);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        if (bitmap != null){
            imageView.setImageBitmap(bitmap);
        }else {
            if (!isVideo)
                imageView.setImageResource(R.mipmap.ic_close_grey_400_24dp);
        }

        if (!isVideo){
            if (mPicList == null)
                mPicList = new ArrayList<>();
            mPicList.add(path);
        }

        layout.addView(imageView);

        if (isVideo) {
            width = BaseApp.getInstance().dip2px(30);
            height = BaseApp.getInstance().dip2px(30);
            lp = new FrameLayout.LayoutParams(width, height);
            lp.gravity = Gravity.CENTER;
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(lp);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageResource(R.mipmap.video_play);
            layout.addView(imageView);

            if (videoLength > 0) {
                lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.BOTTOM | Gravity.END;
                lp.setMargins(0, 0, 25, 5);
                TextView textView = new TextView(mContext);
                textView.setLayoutParams(lp);
                String strLength = String.format(Locale.CHINA, "%d:%02d", videoLength / 1000 / 60, videoLength / 1000 % 60);
                textView.setText(strLength);
                textView.setTextColor(mContext.getResources().getColor(R.color.white));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
                layout.addView(textView, lp);
            }
        }

        layout.setOnClickListener(view -> {
            Bundle mBundle = new Bundle();
            //mBundle.putString("PicPath", path);
            mBundle.putStringArrayList(PICS_PATH_KEY, mPicList);
            mBundle.putString(CURRENT_PATH_KEY, path);
            //mBundle.putSerializable("image_util", ImageUtil.this);
            Intent intent = new Intent(mContext, UiBigImageList.class);
            intent.putExtras(mBundle);
            mContext.startActivity(intent);
        });

        return layout;
    }

    public View getViewFromUrl(TroublePictureBean picture, String path){
        View rootView = getViewFromUrl(path, 0);
        if (rootView != null) {
            rootView.setTag(picture);
        }
        return rootView;
    }

    public View getViewFromUrl(String path){
        return getViewFromUrl(path, 0);
    }

    public View getViewFromUrl(String path, int size) {
        LinearLayout layout = new LinearLayout(mContext);
        int dipSize = 100;
        if (size >0 && size < 100)
            dipSize = size;
        int width = BaseApp.getInstance().dip2px(dipSize);
        int height = BaseApp.getInstance().dip2px(dipSize);

        layout.setLayoutParams(new LayoutParams(width, height));
        layout.setGravity(Gravity.CENTER);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
        lp.setMargins(10, 10, 10, 10);

        layout.setTag(R.id.tag_image_path, path);

        final ImageView imageView = new ImageView(mContext);
        imageView.setLayoutParams(lp);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        if (mPicList == null)
             mPicList = new ArrayList<>();
        mPicList.add(path);

        final ProgressBar progressBar = new ProgressBar(mContext);
        int pbWidth = BaseApp.dip2px(24);
        lp = new LinearLayout.LayoutParams(pbWidth, pbWidth);
        lp.setMargins(10, 10, 10, 10);
        progressBar.setLayoutParams(lp);
        progressBar.setIndeterminate(true);
        progressBar.setVisibility(View.INVISIBLE);

        final ImageView imageFailed = new ImageView(mContext);
        imageFailed.setLayoutParams(lp);
        imageFailed.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageFailed.setImageResource(R.mipmap.ic_close_grey_400_24dp);
        imageFailed.setVisibility(View.INVISIBLE);

        ImageLoader loader = ImageLoader.getInstance();
        DisplayImageOptions displayOptions = BaseApp.getDefaultDisplayOptions();
        loader.displayImage(path, imageView, displayOptions, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {
                progressBar.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                progressBar.setVisibility(View.GONE);
                imageView.setVisibility(View.GONE);
                imageFailed.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                progressBar.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);

                TroublePictureBean pictureBean = (TroublePictureBean) layout.getTag();
                if (pictureBean != null && pictureBean.getFile() != null) {
                    FileUtil.saveImageAsync(bitmap, pictureBean);
                    /*String path[] = new String[1];
                    boolean isOk = FileUtil.saveImage(bitmap, pictureBean.getFile(), false, path);
                    if (isOk) {
                        String localPath = path[0];
                        if (localPath != null && FileUtil.fileExists(localPath)) {
                            pictureBean.setFilepath(localPath);
                        }
                    }*/
                }
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });

        layout.addView(imageView);
        layout.setOnClickListener(v -> {
            // 点击图片查看大图
            Object tag = v.getTag(R.id.tag_image_path);
            if (tag != null) {
                String PicAbsolutePath = tag.toString();
                System.out.println(PicAbsolutePath);
                Bundle mBundle = new Bundle();
                //mBundle.putString("PicPath", PicAbsolutePath);
                mBundle.putStringArrayList(PICS_PATH_KEY, mPicList);
                mBundle.putString(CURRENT_PATH_KEY, PicAbsolutePath);
                //mBundle.putSerializable("image_util", ImageUtil.this);
                Intent intent = new Intent(mContext, UiBigImageList.class);
                intent.putExtras(mBundle);
                mContext.startActivity(intent);
            }
        });

        layout.addView(progressBar);
        return layout;
    }

    public void showBigImage(String filepath) {
        if (mPicList == null)
            mPicList = new ArrayList<>();
        else
            mPicList.clear();
        mPicList.add(filepath);

        Bundle mBundle = new Bundle();
        mBundle.putStringArrayList(PICS_PATH_KEY, mPicList);
        Intent intent = new Intent(mContext, UiBigImageList.class);
        intent.putExtras(mBundle);
        mContext.startActivity(intent);
    }

    /**
     * Bitmap对象转化byte数组
     *
     * @param bitmap Bitmap对象
     * @return byte数组
     */
    public static byte[] bitmapToBytes(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Byte数组转化为Bitmap对象
     *
     * @param data byte数组
     * @return Bitmap对象
     */
    public static Bitmap bytesToBimap(byte[] data)
    {
        if (data.length != 0)
        {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        else
        {
            return null;
        }
    }
}

