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

import com.google.zxing.NotFoundException;
import com.tykj.dev.device.zxing.util.Base64Util;
import com.tykj.dev.device.zxing.util.PdfToImageUtil;
import com.tykj.dev.device.zxing.util.QRCodeUtils;
import com.tykj.dev.device.zxing.util.ZXingUtil;
import com.tykj.dev.device.zxing.vo.ZxingFile;
import com.tykj.dev.device.zxing.vo.ZxingTaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * DATE:2021-7-20
 * Author:zsp
 */
@RestController
@RequestMapping("/zxing")
public class ZxingController {

    @Autowired
    private ZXingUtil zXingUtil;


    @PostMapping("/decode")
    public ZxingTaskVo decode1(@RequestBody ZxingFile file) throws NotFoundException, IOException {
        //生成临时文件
        String stt = ResourceUtils.getURL("classpath:").getPath() + UUID.randomUUID() + ".png";
        String path = file.getFilePath();
        File file1 = new File(path);
        //判断文件的类型
        String name = file1.getName();
        String substring = name.substring(name.lastIndexOf(".")+1);
        List<byte[]> bytes = null;
        String base64;
        if (substring.equals("pdf")) {
             bytes = PdfToImageUtil.pdfToImage(Base64Util.getFileBytes(path));
             Base64Util.byte2image(bytes.get(0), stt);
             base64 = Base64Util.getImageStr(stt);

        }else {
             base64 = Base64Util.getImageStr(path);
        }
        QRCodeUtils qrCodeUtils = new QRCodeUtils();
        return qrCodeUtils.deEncodeByBase64(base64);


    }

}
