package com.mayi.fastdevelop.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

/**
 * 二维码工具
 */
public class QrUtil {


    private static int width = 400;                    // 二维码图片显示宽度
    private static final int IMAGE_HALFWIDTH = 45;     // 二维码中间图片显示宽度
    private static int FOREGROUND_COLOR = 0xff000000;  // 前景色
    private static int BACKGROUND_COLOR = 0xffffffff;  // 背景色

    /**
     * 生成二维码
     *
     * @param str 内容
     * @return Bitmap
     */
    public static Bitmap createBitmap(String str) {
        Bitmap bitmap = null;
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1); // 二维码边界空白大小 ，如：1、2、3、4 默认好像是4
            // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
            MultiFormatWriter mutiWriter = new MultiFormatWriter();
            BitMatrix matrix = mutiWriter.encode(str, BarcodeFormat.QR_CODE, width, width, hints);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            // 二维矩阵转为一维像素数组,也就是一直横着排了
            int halfW = width / 2;
            int halfH = height / 2;
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = FOREGROUND_COLOR;
                    } else { // 无信息设置像素点为白色
                        pixels[y * width + x] = BACKGROUND_COLOR;
                    }
                }
            }
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);// 通过像素数组生成bitmap
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 生成二维码 中间插入小图片
     *
     * @param str 内容
     * @return Bitmap
     */
    public static Bitmap createBitmap(Context context, String str, int centerBmpResId) {
        Bitmap iconBigger = null;
        Bitmap iconSmaller = null;
        Bitmap bitmap = null;
        try {
            iconBigger = BitmapFactory.decodeResource(context.getResources(), centerBmpResId);
            iconSmaller = zoomBitmap(iconBigger, IMAGE_HALFWIDTH);// 缩放一个50*50的图片
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1); // 二维码边界空白大小 ，如：1、2、3、4 默认好像是4
            // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
            MultiFormatWriter mutiWriter = new MultiFormatWriter();
            BitMatrix matrix = mutiWriter.encode(str, BarcodeFormat.QR_CODE, width, width, hints);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            // 二维矩阵转为一维像素数组,也就是一直横着排了
            int halfW = width / 2;
            int halfH = height / 2;
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (x + 10 > halfW - IMAGE_HALFWIDTH && x - 10 < halfW + IMAGE_HALFWIDTH && y + 10 > halfH - IMAGE_HALFWIDTH && y - 10 < halfH
                            + IMAGE_HALFWIDTH) {
                        if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH && y < halfH +
                                IMAGE_HALFWIDTH) {
                            pixels[y * width + x] = iconSmaller.getPixel(x - halfW + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
                        } else {
                            pixels[y * width + x] = BACKGROUND_COLOR;
                        }
                    } else {
                        if (matrix.get(x, y)) {
                            pixels[y * width + x] = FOREGROUND_COLOR;
                        } else { // 无信息设置像素点为白色
                            pixels[y * width + x] = BACKGROUND_COLOR;
                        }
                    }
                }
            }
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);// 通过像素数组生成bitmap
        } catch (Throwable ex) {
            ex.printStackTrace();
        } finally {
            recycle(iconBigger);
            recycle(iconSmaller);
        }
        return bitmap;
    }


    public static Bitmap recycle(Bitmap bmp) {
        if (bmp != null && !bmp.isRecycled()) {
            bmp.recycle();
            bmp = null;
        }
        return bmp;
    }

    /**
     * 缩放图片
     *
     * @param icon 源图片
     * @param h    高度
     * @return
     */
    public static Bitmap zoomBitmap(Bitmap icon, int h) {
        // 缩放图片
        Matrix m = new Matrix();
        float sx = (float) 2 * h / icon.getWidth();
        float sy = (float) 2 * h / icon.getHeight();
        m.setScale(sx, sy);
        // 重新构造一个2h*2h的图片
        return Bitmap.createBitmap(icon, 0, 0, icon.getWidth(), icon.getHeight(), m, false);
    }

    //识别二维码的函数
    public static String recogQRcode(Bitmap QRbmp) {
        int width = QRbmp.getWidth();
        int height = QRbmp.getHeight();
        int[] data = new int[width * height];
        QRbmp.getPixels(data, 0, width, 0, 0, width, height);    //得到像素
        int bitmapPixels[];
        bitmapPixels = new int[QRbmp.getWidth() * QRbmp.getHeight()];
        QRbmp.getPixels(data, 0, QRbmp.getWidth(), 0, 0, QRbmp.getWidth(), QRbmp.getHeight());

        // 将int数组转换为byte数组，也就是取像素值中蓝色值部分作为辨析内容
        for (int i = 0; i < data.length; i++) {
            bitmapPixels[i] = (byte) data[i];
        }

        RGBLuminanceSource source = new RGBLuminanceSource(QRbmp.getWidth(), QRbmp.getHeight(), bitmapPixels);   //RGBLuminanceSource对象
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result re = null;
        try {
            //得到结果
            re = reader.decode(bitmap1);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        //Toast出内容
        return re.getText();
    }
}
