package com.xkrs.unionpay.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.xkrs.unionpay.bean.DemoBase;
import com.xkrs.unionpay.service.UnionpayService;
import com.xkrs.unionpay.util.AcpService;
import com.xkrs.unionpay.util.LogUtil;
import com.xkrs.unionpay.util.SDKConfig;
import com.xkrs.unionpay.util.SDKConstants;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * @Author: XinYi Song
 * @Date: 2021/12/28 17:03
 */
@RestController
public class UnionpayController {

    @Resource
    private UnionpayService unionpayService;


    @RequestMapping("/pay")
    public void pay(HttpServletResponse response) throws Exception{
        String qrCode=unionpayService.pay(DemoBase.getOrderId(),"200");
        makeQRCode(qrCode,response.getOutputStream());
    }

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


    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format,
                                     OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }


    public void makeQRCode(String content, OutputStream outputStream) throws Exception{  //生成二维码


        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, 200, 200, hints);
        // 生成二维码
        FileOutputStream outputFile = new FileOutputStream("d:" + File.separator + "new.jpg");
        MatrixToImageWriter.writeToStream(bitMatrix, "jpg", outputFile);

        /*Map<EncodeHintType,Object> map=new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
        map.put(EncodeHintType.MARGIN,2);

        QRCodeWriter qrCodeWriter=new QRCodeWriter();
        BitMatrix bitMatrix=qrCodeWriter.encode(content, BarcodeFormat.QR_CODE,200,200,map);
        MatrixToImageWriter.writeToStream(bitMatrix,"png",outputStream);*/
    }


    @RequestMapping("/notify")
    public void hello2(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Map<String,String> result=new HashMap<>();

        System.out.println("======= 后台通知 ========");
        Enumeration<String> names=request.getParameterNames();
        if (names!=null){
            while (names.hasMoreElements()){
                String name=names.nextElement();
                String value=request.getParameter(name);
                result.put(name,value);
                System.out.println(name+" ==> "+value);

                if (result.get(name)==null||"".equals(result.get(name))){
                    result.remove(name);
                }
            }
        }

        if (AcpService.validate(result, SDKConstants.UTF_8_ENCODING)){
            System.out.println("后台验签成功");
        }else {
            System.out.println("后台验签失败");
        }

        response.getWriter().print("ok");
    }
}
