package xn.hxp.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xn.hxp.ui.PrintBean;

public final class BitmapUtils {

    private BitmapUtils() {
        // 私有构造函数防止实例化
    }

    public static Bitmap generateBitmap(PrintBean printDate) {
        // 设置画布尺寸
        int width = 400;
        int height = 400;

        // 创建 Bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        // 创建 Canvas
        Canvas canvas = new Canvas(bitmap);

        // 设置背景色
        canvas.drawColor(Color.WHITE);

        // 居中绘制二维码
        int qrCodeSize = 225;
        int qrCodeX = (width - qrCodeSize) / 2;
        int qrCodeY = 0;
        drawQRCode(printDate.getWxCode(), canvas, qrCodeX, qrCodeY, 230);

        // 在二维码下方居中绘制文本
        String text = "编码：" + printDate.getTag();
        float textX = (width - getTextWidth(text, 20)) / 2;
        float textY = qrCodeY + qrCodeSize - 6;
        drawText(canvas, text, textX, textY, 19);

        // 计算剩余内容的起始 Y 坐标
        float contentStartY = textY + 30;

        // 绘制剩余的内容，左对齐显示
        List<String> content = List.of(
                printDate.getLevel() + " 一 " + printDate.getName(),
                "CAS：" + printDate.getCasNo() + "      " + printDate.getTypes(),
                "归属人：" + printDate.getPerson()
        );

        int lineHeight = 24;
        for (int index = 0; index < content.size(); index++) {
            drawText(canvas, content.get(index), 10f, contentStartY + index * lineHeight, 20);
        }
        return bitmap;
    }

    public static Bitmap drawBarCode(String number, Canvas canvas, int qrCodeX, int qrCodeY, int barW, int barH) {
        Bitmap bitmap = Bitmap.createBitmap(barW, barH, Bitmap.Config.ARGB_8888);
        try {
//            Map<EncodeHintType, Object> hints = new HashMap<>();
//            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(number, BarcodeFormat.CODE_128, barW, barH);
            int[] pixels = new int[barW * barH];
            for (int y = 0; y < barH; y++) {
                for (int x = 0; x < barW; x++) {
                    pixels[y * barW + x] = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
                }
            }

            bitmap.setPixels(pixels, 0, barW, 0, 0, barW, barH);
            canvas.drawBitmap(bitmap, 0, qrCodeY, null);
        } catch (WriterException e) {
            return null;
        }
        return bitmap;
    }


    public static Bitmap generateBarBitmap(boolean isBelong, PrintBean printBean) {
        int width = 400;
        int height = 400;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        int barH = 180;
        int barW = 400;
        int qrCodeY = 10;
        drawBarCode(printBean.getTag(), canvas, 0, qrCodeY, barW, barH);

        int textSize = 20;
        String text = printBean.getTag();
        float textX = (width - getTextWidth(text, textSize)) / 2;
        float textY = qrCodeY + barH + textSize;
        drawText(canvas, text, textX, textY, textSize);

        float contentStartY = textY + 30;
        String string = isBelong ?
                "归属人：" + printBean.getPerson() :
                "课题组：" + printBean.getPerson();

        List<String> content = List.of(
                printBean.getLevel() + " 一 " + printBean.getName(),
                "CAS：" + printBean.getCasNo() + "      " + printBean.getTypes(),
                string
        );

        int lineHeight = 24;
        for (int index = 0; index < content.size(); index++) {
            drawText(canvas, content.get(index), 10f, contentStartY + index * lineHeight, textSize);
        }
        return bitmap;
    }


    public static Bitmap generateBitmap(boolean isBelong, PrintBean printDate) {
        int width = 400;
        int height = 400;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        int qrCodeSize = 225;
        int qrCodeX = (width - qrCodeSize) / 2;
        int qrCodeY = 0;
        drawQRCode(printDate.getWxCode(), canvas, qrCodeX, qrCodeY, 230);

        String text = "编码：" + printDate.getTag();
        float textX = (width - getTextWidth(text, 20)) / 2;
        float textY = qrCodeY + qrCodeSize - 6;
        drawText(canvas, text, textX, textY, 19);

        float contentStartY = textY + 30;
        String string = isBelong ?
                "归属人：" + printDate.getPerson() :
                "课题组：" + printDate.getPerson();

        List<String> content = List.of(
                printDate.getLevel() + " 一 " + printDate.getName(),
                "CAS：" + printDate.getCasNo() + "      " + printDate.getTypes(),
                string
        );

        int lineHeight = 24;
        for (int index = 0; index < content.size(); index++) {
            drawText(canvas, content.get(index), 10f, contentStartY + index * lineHeight, 20);
        }
        return bitmap;
    }

    private static void drawQRCode(String tag, Canvas canvas, int x, int y, int size) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            BitMatrix bitMatrix = multiFormatWriter.encode(
                    tag,
                    BarcodeFormat.QR_CODE,
                    size,
                    size,
                    hints
            );

            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            int[] pixels = new int[width * height];

            for (int yPos = 0; yPos < height; yPos++) {
                int offset = yPos * width;
                for (int xPos = 0; xPos < width; xPos++) {
                    pixels[offset + xPos] = bitMatrix.get(xPos, yPos) ? Color.BLACK : Color.WHITE;
                }
            }

            Bitmap qrCodeBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            qrCodeBitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            canvas.drawBitmap(qrCodeBitmap, x, y, null);

        } catch (WriterException e) {
            Log.e("BitmapUtils", "Failed to generate QR code: " + e.getMessage());
        }
    }

    private static void drawText(Canvas canvas, String text, float x, float y, int textSize) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);
        paint.setTextSize(textSize);
        paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
        canvas.drawText(text, x, y, paint);
    }

    private static float getTextWidth(String text, int textSize) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(textSize);
        return paint.measureText(text);
    }

    public static Bitmap airBottlePrint(String rfid) {
        int width = 400;
        int height = 400;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        int qrCodeSize = 225;
        int qrCodeX = (width - qrCodeSize) / 2;
        int qrCodeY = 6;
        drawQRCode(rfid, canvas, qrCodeX, qrCodeY, 230);

        String text = rfid;
        float textX = (width - getTextWidth(text, 20)) / 2;
        float textY = qrCodeY + qrCodeSize - 6;
        drawText(canvas, text, textX, textY, 19);

        float contentStartY = textY + 30;
        List<String> content = List.of("", "", "");

        int lineHeight = 24;
        for (int index = 0; index < content.size(); index++) {
            drawText(canvas, content.get(index), 10f, contentStartY + index * lineHeight, 20);
        }
        return bitmap;
    }

    /**
     * 将BitMatrix转换为Bitmap
     */
    private static Bitmap bitMatrixToBitmap(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pixels[y * width + x] = matrix.get(x, y) ? Color.BLACK : Color.WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}