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

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
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 javassist.NotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * DATE:2021-7-20
 * Author:zsp
 */
@Service
public class ZXingUtil {


    /** 二维码上传位置 */
//    private static String codePath = "src/";
    /** 二维码宽度 */
    private static Integer width = 50;
    /** 二维码高度 */
    private static Integer height = 50;

    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

//    @Autowired
//    private TaskDao taskDao;
    /**
     * 解析二维码
     *
     * @param filePath 文件路径
     * @return 二维码内容
     * @throws IOException
     * @throws NotFoundException
     */
//    public static String decode(String name) throws IOException, com.google.zxing.NotFoundException {
//        String filepath = codePath + name + ".png";
//        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
//        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
//        Binarizer binarizer = new HybridBinarizer(source);
//        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
//        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
//        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//        Result result = new MultiFormatReader().decode(bitmap, decodeHints);
//        return result.getText();
//    }
    public ZxingTaskVo decode(String filePath) throws IOException, com.google.zxing.NotFoundException {
//        String s = PDFUtils.pdfToImagePath(filePath);
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(bitmap, decodeHints);
        //获取taskDao
        TaskDao taskDao = SpringUtils.getBean("taskDao");
        ZxingTaskVo zxingTaskVo = null;
        if (result.getText() != null){
            Task task = taskDao.findByParentTaskId(Integer.parseInt(result.getText()));
            zxingTaskVo = new ZxingTaskVo(task.getParentTaskId(), task.getId());
            return zxingTaskVo;
        }else {
            return null;
        }
    }


    /**
     * 生成二维码
     *
     * @param taskId 任务id
     * @return 二维码路径
     * @throws WriterException
     * @throws IOException
     */
    public static String encode(Integer taskId) throws WriterException, IOException {
        Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>();
        encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        encodeHints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        encodeHints.put(EncodeHintType.MARGIN, 0);
//        encodeHints.put(EncodeHintType.PDF417_COMPACT,)
        BitMatrix bitMatrix = new MultiFormatWriter().encode(taskId+"",
                BarcodeFormat.QR_CODE, width, height, encodeHints);
        String filepath = ResourceUtils.getURL("classpath:").getPath() + UUID.randomUUID() + ".png";
        Path path = FileSystems.getDefault().getPath(filepath);
        MatrixToImageWriter.writeToPath(bitMatrix,"png",path);
        return ImageToBase64ByLocal(filepath);
    }

    /**
     * 本地图片转换成base64字符串
     * @param imgFile    图片本地路径
     * @return
     *
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:40:46
     */
    public static String ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理


        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return  encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }




}
