package com.common.print.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.utils.StringUtils;
import com.common.lib_base.utils.log.CommonLogUtils;
import com.common.print.R;
import com.common.print.bean.PrintBean;
import com.common.print.bean.PrintContentBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.jx800r09.sdk_800r09_library.enumdata.PageTypeEnum;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import static android.graphics.Bitmap.createBitmap;

public class BitmapUtils {



    public static String getLogcatDir() {
        //获取外存路径
        String externalStoragePath = PathUtils.getExternalAppFilesPath();//   /storage/emulated/0/Android/data/com.hh.arome/files
//        String externalStoragePath = PathUtils.getExternalStoragePath(); // /storage/emulated/0
        Log.e("HHArome","externalStoragePath:"+externalStoragePath);
        //命名存储目录
        String logPath = externalStoragePath + File.separator + "picture";
//        String logPath = externalStoragePath;
        //判断目录是否存在，不存在则判断是否建立成功
        FileUtils.createOrExistsDir(logPath);
        return logPath;
    }

    public static String createFileName() {
        String fileName = "";
        String pattern = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.CHINA);

        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        String curDate = dateFormat.format(calendar.getTime());
        //品牌+时间
        String model = Build.MODEL;
        fileName = model + "_" + curDate+"_"+ hour + ".png";

//        fileName = "a1.png";



        return fileName;
    }



    public static String createPictureDirAndFile() {

        String logcatDir = getLogcatDir();
        String fileName = createFileName();
        String filePath = logcatDir + File.separator + fileName;

        return filePath;
    }


    /**
     * 字符串转换成Bitmap类型
     * @param string
     * @return
     */
    public static Bitmap stringToBitmap(String string) {

        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * 将Bitmap转成本地图片
     * @param path 保存为本地图片的地址
     * @param bitmap 要转化的Bitmap
     */
    public static void saveImage(String path, Bitmap bitmap){

        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
            bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos);
            bos.flush();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        Bitmap newbm = null;
        if (bm != null) {
            // 获得图片的宽高
            int width = bm.getWidth();
            int height = bm.getHeight();
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 得到新的图片
            newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        }
        return newbm;
    }



    /**
     * 根据文字创建一个 bitmap  ， 打印的位图需要 黑字 白底
     *
     * @param text
     * @param height
     * @param width
     * @return
     */
    public static Bitmap createTextToBimtap(String text, int height, int width) {
        Bitmap newBitmap = createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);

        canvas.drawBitmap(newBitmap, 0, 0, null);
        TextPaint textPaint = new TextPaint();
        //       String familyName ="宋体";
        //  Typeface font = Typeface.create(familyName,Typeface.BOLD);
        // textPaint.setTypeface(font);
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(height * 2 / 3);
//        textPaint.setColor(Color.rgb(0, 0, 0));
        textPaint.setColor(Color.BLACK);
        //     "在Android开发中，Canvas.drawText不会换行，即使一个很长的字符串也只会显示一行，超出部分会隐藏在屏幕之外.StaticLayout是android中处理文字的一个工具类，StaticLayout 处理了文字换行的问题";
        StaticLayout sl = new StaticLayout(text, textPaint, newBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        textPaint.setStyle(Paint.Style.FILL);
        canvas.translate(0, height / 10);
        sl.draw(canvas);
        return newBitmap;
    }






    public static Bitmap textToBimtap(String text,int textSizePx){

        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(20);
        textPaint.setColor(Color.BLACK);
        int width = (int) Math.ceil(textPaint.measureText(text));
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        int height = (int) Math.ceil(Math.abs(fontMetrics.bottom) + Math.abs(fontMetrics.top));

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

        canvas.rotate(180);
        canvas.save();

        canvas.drawColor(Color.WHITE);
        canvas.drawText(text,0,Math.abs(fontMetrics.ascent),textPaint);

        return bitmap;
    }


    public static Bitmap textPositionToBitmap(Context context,String text,int textSize,int xPosition,int yPosition){


        TextPaint textPaint = new TextPaint();
        // 80
        textPaint.setTextSize(80);
        textPaint.setColor(Color.BLACK);

        Typeface typeface = ResourcesCompat.getFont(context, R.font.songti);
        textPaint.setTypeface(typeface);// 采用自定义的字体
//        int width = (int) Math.ceil(textPaint.measureText(text));
//        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
//        int height = (int) Math.ceil(Math.abs(fontMetrics.bottom) + Math.abs(fontMetrics.top));

        // bitmap的width=1678 height=2397
        Bitmap bitmap = Bitmap.createBitmap(2000,2000, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        canvas.drawColor(Color.WHITE);
//        canvas.drawText(text,0,Math.abs(fontMetrics.ascent),textPaint);

        canvas.drawText(text,xPosition,yPosition,textPaint);

        canvas.save();

        return bitmap;

    }




    public static Bitmap createTextBitmap(Context context, List<PrintContentBean> printContentList, int printContent){

        Bitmap bitmap;

        /**
         * Page_Type_A4_Normal(0),
         * Page_Type_A4_Roll(1),
         * Page_Type_A4_ANSI_A(2),
         * Page_Type_A5_Normal(3),
         * Page_Type_200mm(4),
         * Page_Type_150mm(5),
         * Page_Type_100mm(6),
         * Page_Type_Customize(7);
         */
        if(0 == printContent){
            // A4
            bitmap = Bitmap.createBitmap(1678,2397, Bitmap.Config.ARGB_8888);
        }else if(3 == printContent){
            // A5
            bitmap = Bitmap.createBitmap(1678,1198, Bitmap.Config.ARGB_8888);
        }else{
            // 默认
            bitmap = Bitmap.createBitmap(1678,2397, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);


        // 绘制文字
//        TextPaint textPaint = new TextPaint();
//        // 80
//        textPaint.setTextSize(80);
//        textPaint.setColor(Color.BLACK);
//        textPaint.setFakeBoldText(true);
//
//        // 设置字体
        Typeface typeface = ResourcesCompat.getFont(context, R.font.songti);
//        textPaint.setTypeface(typeface);// 采用自定义的字体——宋体


        canvas.drawColor(Color.WHITE);



        // 得到文字画笔
        List<TextPaint> textPaintList = new ArrayList<>();

        for (PrintContentBean printContentBean : printContentList) {

            String text = printContentBean.getText();
            if(StringUtils.isNotNull(text)){
                int textSize = printContentBean.getTextSize();
                boolean bold = printContentBean.isBold();

                CommonLogUtils.e("text--"+text,
                        "bold--"+bold);

                TextPaint paint = new TextPaint();

                paint.setTextSize(textSize);
                paint.setColor(Color.BLACK);
                paint.setFakeBoldText(bold);

                paint.setTypeface(typeface);

                textPaintList.add(paint);
            }

        }




        // 循环
//        for (PrintContentBean printContentBean : printContentList) {
        for (int i = 0; i < printContentList.size(); i++) {
            PrintContentBean printContentBean = printContentList.get(i);

            String text = printContentBean.getText();
            int textSize = printContentBean.getTextSize();
            boolean bold = printContentBean.isBold();

            int xPosition = printContentBean.getxPosition();
            int yPosition = printContentBean.getyPosition();

            String imageBase64 = printContentBean.getImageBase64();
            int width = printContentBean.getWidth();
            int height = printContentBean.getHeight();


            if(StringUtils.isNotNull(text)){
//                // 绘制文字
//                TextPaint textPaint = new TextPaint();
//                // 80
//                textPaint.setTextSize(textSize);
//                textPaint.setColor(Color.BLACK);
//                textPaint.setFakeBoldText(bold);
//
//                // 设置字体
//                Typeface typeface = ResourcesCompat.getFont(context, R.font.songti);
//                textPaint.setTypeface(typeface);// 采用自定义的字体——宋体
//
//
//                canvas.drawColor(Color.WHITE);

//                canvas.drawText(text,xPosition,yPosition,textPaint);
                canvas.drawText(text,xPosition,yPosition,textPaintList.get(i));

//                canvas.drawText("测试1",xPosition+10,yPosition+10,textPaint);
//
//                canvas.drawText("测试2",xPosition+10,yPosition+10,textPaint);

                CommonLogUtils.e("text--"+text,
                        "xPosition--"+xPosition,
                        "yPosition--"+yPosition);

//                canvas.save();
            }else if(StringUtils.isNotNull(imageBase64)){
                // 绘制图片

                Paint bitmapPaint = new Paint();

                Bitmap imgBitmap = printContentBean.getPrintBitmap();

//                CommonLogUtils.e("imageBase64--"+imageBase64);
//
//                if(imageBase64.contains("http")){
//                    imgBitmap = BitmapUtils.urlToBitmap(imageBase64);
//                }else{
//                    imgBitmap = BitmapUtils.stringToBitmap(imageBase64);
//                }




                Rect dstRect = new Rect(xPosition, yPosition, width, yPosition + height);

                CommonLogUtils.e("imgBitmap--"+imgBitmap);


//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                })

                canvas.drawBitmap(imgBitmap, null, dstRect, bitmapPaint); // srcRect 为 null

//                canvas.save();
            }
        }


        canvas.save();


        return bitmap;

    }



//    public static Bitmap textPositionToBitmap(String text,int pos1,int pos2){
//
//
//        TextPaint textPaint = new TextPaint();
//        textPaint.setTextSize(80);
//        textPaint.setColor(Color.BLACK);
//        int width = (int) Math.ceil(textPaint.measureText(text));
//        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
//        int height = (int) Math.ceil(Math.abs(fontMetrics.bottom) + Math.abs(fontMetrics.top));
//
//
//        ToastUtils.showLong("text:"+text+"   width:"+width+"  height:"+height);
//
//        Bitmap bitmap = Bitmap.createBitmap(2000,2000, Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(bitmap);
//
////        canvas.rotate(180);
////        canvas.save();
//
//        canvas.drawColor(Color.WHITE);
////        canvas.drawText(text,0,Math.abs(fontMetrics.ascent),textPaint);
//
//        canvas.drawText(text,pos1,pos2,textPaint);
//
//        canvas.save();
//
//        return bitmap;
//
//    }



    /**
     * 生成二维码bitmap 要转换的地址或字符串,可以是中文
     *
     * @param url
     * @param width
     *
     * @param height
     * @return
     */
    public static Bitmap createQRImage(String url, final int width, final int height) {
        try {
            // 判断URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }



//    static Handler mHandler = new Handler();
//
//    public static Bitmap urlToBitmap(final Context context,final String imgUrl){
//
//
//        final Bitmap bitmap = null;
//
//        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
//            @Override
//            public void run() {
//                try {
//
//                    // 子线程获取url对应的bitmap
//                    final Bitmap curBitmap = Glide.with(context)
//                            .asBitmap()
//                            .load(imgUrl)
//                            .submit().get();
//
//                    bitmap = curBitmap;
//
//                    return curBitmap;
//
//
//                } catch (ExecutionException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }





    private static Bitmap bitmap;

    public static Bitmap urlToBitmap(final String url){


        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
            @Override
            public void run() {
                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();
                }
            }
        });


        return bitmap;
    }





}
