package com.webchat.controller.client;

import com.webchat.common.util.MD5Utils;
import com.webchat.common.util.QRCodeUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author 程序员七七，https://www.coderutil.com
 * @date 2024/11/8 00:33
 */
@Api(tags = "【基础服务】二维码服务")
@Slf4j
@RestController
@RequestMapping("/api/qr")
public class QRController {

    private static final String QR_DIR = "static/upload/qr/";

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/create")
    public void createTempQRImage(@RequestParam("url") String url) {
        File file = null;
        try {
            // 根据qrCodeUrl生成二维码
            String qrImageName = MD5Utils.md5(url) +".jpg";
            String qrFilePath = QRCodeUtils.encode(url, null, QR_DIR, qrImageName);
            file = new File(qrFilePath);
            // 返回图片
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(file));
            streamResponseQRImage(bufferedImage);
        } catch (Exception e) {
            log.error("INVOKE WEB POSTER API ERROR.", e);
        } finally {
            // 删除本地文件
            deleteLocalFile(file);
        }
    }

    /**
     * 图片流response
     * @param img
     */
    private void streamResponseQRImage(BufferedImage img) {
        response.setContentType("image/png");
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        try {
            ImageIO.write(img, "png", response.getOutputStream());
        } catch (Exception e) {
            log.error("POSTER IMAGE CREATE ERROR.", e);
        }
    }

    private void deleteLocalFile(File file) {
        if (file != null && file.exists()) {
            file.delete();
        }
    }
}
