package com.ssj.framework.weixin.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ssj.framework.core.util.OSSUtils;
import com.ssj.framework.core.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/** 
 *  
 */
public class BarcodeFactory {
	 private static Logger log = LoggerFactory.getLogger(BarcodeFactory.class);
	// LOGO宽度
	private static final int LOGO_WIDTH = 60;
	// LOGO高度
	private static final int LOGO_HEIGHT = 60;

	private static BufferedImage createImage(String content, String logoPath,int code_width, int code_height,  
			boolean needCompress) throws Exception {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, code_width, code_height, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000
						: 0xFFFFFFFF);
			}
		}
		if (logoPath == null || "".equals(logoPath)) {
			return image;
		}
		// 插入图片
		BarcodeFactory.insertImage(image, logoPath, code_width,code_height,needCompress);
		return image;
	}

	private static BufferedImage createImageAddText(BufferedImage bim,String text,int code_width,int code_height) throws Exception {
		BufferedImage image = bim;
		BufferedImage outImage = new BufferedImage(code_width, code_height+15, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D outg = outImage.createGraphics();
		outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
		outg.setColor(Color.BLACK);
		outg.setFont(new Font("宋体", Font.PLAIN, 18));
		int strWidth = outg.getFontMetrics().stringWidth(text);
		outg.drawString(text, 180 - strWidth / 2 + 8, image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 5);
		outg.dispose();
		outImage.flush();
		image = outImage;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.flush();
        ImageIO.write(image, "png", baos);
        BufferedImage newBufferedImage = new BufferedImage(
                image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        newBufferedImage.createGraphics().drawImage(image, 0, 0,
                Color.WHITE, null);
//            存放本地
     //   ImageIO.write(newBufferedImage, "png", new File("D:\\123.bmp"));

//        com.lowagie.text.Image imageByte = com.lowagie.text.Image.getInstance(baos.toByteArray());
        baos.close();
        image.flush();
		return newBufferedImage;
	}

	/**
	 * 绘制二维码，不带文字
	 *
	 * @param content       扫描内容
	 * @param barcodeFormat 格式
	 * @param width
	 * @param height
	 * @param hints         二维码属性设置
	 * @return 放到内存中，后续再二维码下方添加文字
	 */
	public static BufferedImage generateQRCodeBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, ?> hints) {
		MultiFormatWriter multiFormatWriter = null;
		BitMatrix bm = null;
		BufferedImage image = null;
		try {
			multiFormatWriter = new MultiFormatWriter();
			bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
			int w = bm.getWidth();
			int h = bm.getHeight();
			image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
				}
			}
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return image;
	}
	/**
	 * 设置二维码属性
	 *
	 * @return
	 */
	public static Map<EncodeHintType, Object> getDecodeHintType() {
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 0);
		hints.put(EncodeHintType.MAX_SIZE, 350);
		hints.put(EncodeHintType.MIN_SIZE, 100);
		return hints;
	}

	private static BufferedImage createImage2(String content, String logoPath,int code_width, int code_height,  
			boolean needCompress) throws Exception {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, code_width, code_height, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_BYTE_BINARY);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
						: 0xFFFFFFFF);
			}
		}
		if (logoPath == null || "".equals(logoPath)) {
			return image;
		}
		// 插入图片
		BarcodeFactory.insertImage(image, logoPath, code_width,code_height,needCompress);
		return image;
	}

	/**
	 * 插入LOGO
	 * 
	 * @param source
	 *            二维码图片
	 * @param logoPath
	 *            LOGO图片地址
	 * @param needCompress
	 *            是否压缩
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String logoPath,int code_width, int code_height,  
			boolean needCompress) throws Exception {
		File file = new File(logoPath);
		if (!file.exists()) {
			throw new Exception("logo file not found.");
		}
		Image src = ImageIO.read(new File(logoPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		if (needCompress) { // 压缩LOGO
			if (width > LOGO_WIDTH) {
				width = LOGO_WIDTH;
			}
			if (height > LOGO_HEIGHT) {
				height = LOGO_HEIGHT;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (code_width - width) / 2;
		int y = (code_height - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成二维码(内嵌LOGO)，二维码的绝对路径，logo图片的绝对路径
	 * 
	 * @param content
	 *            内容
	 * @param logoPath
	 *            LOGO地址
	 * @param destPath
	 *            存放地址
	 * @param code_width
	 *            二维码宽度
	 * @param code_height
	 *            二维码高度
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String logoPath,
			String destPath, int code_width, int code_height,  boolean needCompress) throws Exception {
		BufferedImage image = BarcodeFactory.createImage(content, logoPath, code_width,  code_height,  
				needCompress);
		ImageIO.write(image, "JPG", new File(destPath));
	}


	/**
	 * 解析二维码
	 * 
	 * @param file
	 *            二维码图片
	 * @return
	 * @throws Exception
	 */
	public static String decode(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
				image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}
     
	public static void bookencode(String content,int flowId, String destPath, int code_width, int code_height) throws Exception {
		//BufferedImage image = BarcodeFactory.createImage2(content, null, code_width,  code_height,false);
		BufferedImage bim = generateQRCodeBufferedImage(content, BarcodeFormat.QR_CODE, 378, 378, getDecodeHintType());
		//字节数组
		BufferedImage image = BarcodeFactory.createImageAddText(bim, String.valueOf(flowId), 378,  378);
		ImageIO.write(image, "BMP", new File(destPath));
		OSSUtils.uploadFile(destPath,
				destPath.replaceAll(PropertiesUtil.getValue("file_save_path"),""));
	}

	public static void bookencode(String content, String destPath, int code_width, int code_height) throws Exception {
		BufferedImage image = BarcodeFactory.createImage2(content, null, code_width,  code_height,false);
		ImageIO.write(image, "BMP", new File(destPath));
		OSSUtils.uploadFile(destPath,
				destPath.replaceAll(PropertiesUtil.getValue("file_save_path"),""));
	}
	public static void encodePng(String content, String destPath, int code_width, int code_height) throws Exception {
		BufferedImage image = BarcodeFactory.createImage2(content, null, code_width,  code_height,false);
		ImageIO.write(image, "PNG", new File(destPath));
	}
	
	public static String linuxZip(String filePath,String zip,String path) { 
 		StringBuffer sb = new StringBuffer();
 		log.info(" linuxZip ");
 		log.info(" zip -q -r  "+zip+" "+ path);
 		 try {
             String[] cmdA = { "/bin/sh", "-c", " cd "+filePath +"; zip -q -r  "+zip+" "+ path};
             Process process = Runtime.getRuntime().exec(cmdA);
             LineNumberReader br = new LineNumberReader(new InputStreamReader(
                     process.getInputStream()));
             String line;
             while ((line = br.readLine()) != null) {
                 sb.append(line);
             }
         } catch (Exception e) {
             sb.append("-1");
         }
 		log.info("sb.toString()"+sb.toString());
         return sb.toString();
 	}


}

