package com.tykj.dev.device.zxing.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.tykj.dev.device.task.repository.TaskDao;
import com.tykj.dev.device.task.subject.domin.Task;
import com.tykj.dev.device.zxing.vo.ZxingTaskVo;
import com.tykj.dev.misc.utils.SpringUtils;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * DATE:2021-7-20
 * Author:zsp
 * 解析二维码
 */
@Component
public class QRCodeUtils {

    /**
     * 解析二维码解析,此方法是解析Base64格式二维码图片
     * baseStr:base64字符串,data:image/png;base64开头的
     */
    public ZxingTaskVo deEncodeByBase64(String baseStr) {
//        String content = null;
        BufferedImage image;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b=null;
        try {
//            int i = baseStr.indexOf("data:image/png;base64,");
//            baseStr = baseStr.substring(i+"data:image/png;base64,".length());//去掉base64图片的data:image/png;base64,部分才能转换为byte[]
            b = decoder.decodeBuffer(baseStr);//baseStr转byte[]
            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(b);//byte[] 转BufferedImage
            image = ImageIO.read(byteArrayInputStream);
            BufferedImage temp = ImageUtils.opening(ImageUtils.binarization(image));
            LuminanceSource source = new BufferedImageLuminanceSource(temp);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
            System.out.println("result:"+result.getText());
            //获取taskDao
            TaskDao taskDao = SpringUtils.getBean("taskDao");
            //返回taskId
            ZxingTaskVo zxingTaskVo = null;
            if (result.getText() != null){
                Task task = taskDao.findByParentTaskId(Integer.valueOf(result.getText()));
                zxingTaskVo = new ZxingTaskVo(task.getParentTaskId(), task.getId());
            }
            return zxingTaskVo;
//            System.out.println("图片中内容：  ");
//            System.out.println("content： " + result.getText());
//            content = result.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析二维码,此方法解析一个字节数组的二维码图片
     * path:图片路径
     */
    public static String deEncodeByBtyes(byte[] bytes) {
        String content = null;
        BufferedImage image;
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            image = ImageIO.read(in);
            BufferedImage temp = ImageUtils.opening(ImageUtils.binarization(image));
            LuminanceSource source = new BufferedImageLuminanceSource(temp);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
            System.out.println("二维码内容：  ");
            System.out.println("content： " + result.getText());
            content = result.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            //这里判断如果识别不了带LOGO的图片，重新添加上一个属性
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                image = ImageIO.read(in);
                BufferedImage temp = ImageUtils.opening(ImageUtils.binarization(image));
                LuminanceSource source = new BufferedImageLuminanceSource(temp);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
                //设置编码格式
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                //设置优化精度
                hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
                //设置复杂模式开启（我使用这种方式就可以识别微信的二维码了）
                hints.put(DecodeHintType.PURE_BARCODE,Boolean.TYPE);
                Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
                System.out.println("二维码内容：  ");
                System.out.println("content： " + result.getText());
                content = result.getText();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (NotFoundException e1) {
                e1.printStackTrace();
            }
        }
        return content;
    }

}
