package com.teamcenter.rac.kernel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class JFomPdfOperateMethodUtil {
	public List<JFomPdfBean> beanList;

	// public static void main(String[] args) {
	// JFomPdfOperateMethodUtil util = new JFomPdfOperateMethodUtil();
	// try {
	// util.addPdfMark(
	// "C:\\Users\\hub\\Desktop\\继峰PDF\\A4-JFY-210x297.pdf",
	// "C:\\Users\\hub\\Desktop\\继峰PDF\\A4-JFY-210x297_1.pdf",
	// "C:\\Users\\hub\\Desktop\\继峰PDF\\受控章.tif");
	// System.out.println(System.getenv("TEMP"));
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }

	public static void main(String[] args) {

		JFomPdfOperateMethodUtil util = new JFomPdfOperateMethodUtil();
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("设计=胡冰1|设计时间=201608021|");
			sb.append("标准化=胡冰2|标准化时间=201608022|");
			sb.append("审核=胡冰3|审核时间=201608023|");
			sb.append("工艺=胡冰4|工艺时间=201608024|");
			sb.append("批准=胡冰5|批准时间=201608025");
			util.writePdf("F:\\Connor（项目管理）\\东睦项目\\PDF签名模版\\A4.pdf", "F:\\Connor（项目管理）\\东睦项目\\PDF签名模版\\A4_2.pdf",
					sb.toString());
			System.out.println(System.getenv("TEMP"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public JFomPdfOperateMethodUtil() {
		this.beanList = new ArrayList<JFomPdfBean>();
		try {
			// 获取配置文件中的信息
			getBeanMsgList();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取properties配置的信息
	 * 
	 * @throws IOException
	 */
	public void getBeanMsgList() throws IOException {
		Properties properties = new Properties();
		InputStream is = null;
		is = this.getClass().getClassLoader().getResourceAsStream("com/teamcenter/rac/kernel/PDFInfo.properties");
		properties.load(is);
		// properties.getProperty("role_name");
		for (int i = 0; true; i++) {
			// System.out.println();
			String str = properties.getProperty("A" + i);
			if (str == null) {
				break;
			}
			String[] values = str.split(",");
			if (values != null && values.length == 4) {
				JFomPdfBean bean = new JFomPdfBean();
				Float fhValue = 0.0f;
				Float fwValue = 0.0f;
				Float fhiValue = 0.0f;
				Float fwiValue = 0.0f;
				try {
					fhValue = Float.parseFloat(values[0]);
					fwValue = Float.parseFloat(values[1]);
					fhiValue = Float.parseFloat(values[2]);
					fwiValue = Float.parseFloat(values[3]);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				bean.setH(fhValue);
				bean.setW(fwValue);
				bean.setHi(fhiValue);
				bean.setWi(fwiValue);
				this.beanList.add(bean);
			}

		}

		is.close();

	}

	/**
	 * 统一按照宽度压缩
	 * 
	 * @param args
	 */
	public static float getPercent(float h, float w) {
		float p2 = 10.0f;
		// p2 = 820 / w * 100;
		System.out.println(p2);
		return p2;
	}

	public void writePdf(String inPutPath, String outPutPath, String msg) throws Exception {
		float sizeOff = 2.8346f;

		HashMap<String, String> signoffMapping = new HashMap<>();
		String[] textS = msg.split("\\|");
		if (textS != null)
			for (String text : textS) {
				String[] strS = text.split("=");
				System.out.println(strS.length);
				if (strS != null && strS.length == 2)
					signoffMapping.put(strS[0], strS[1]);

			}

		System.out.println(textS.length);
		// PDF 输入文件
		PdfReader reader = new PdfReader(inPutPath, "PDF".getBytes());
		// PDF 输出文件
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPutPath));
		// 水印图片

		// 获取PDF的页数
		int pageSize = reader.getNumberOfPages();
		for (int i = 1; i <= pageSize; i++) {
			Rectangle rectangle = reader.getPageSize(i);
			JFomPdfBean fposition = getSize2(rectangle);
			int x = new BigDecimal(fposition.getH() / sizeOff).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
			int y = new BigDecimal(fposition.getW() / sizeOff).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
			float xx = 0;
			float yy = 0;
			float xxx = 0;
			float yyy = 0;

			// A2
			if (x > 590 && x < 600 && y > 415 && y < 425) {
				xx = 422;
				yy = 29;

			}
			// A3
			else if (x > 415 && x < 425 && y > 292 && y < 302) {
				xx = 246;
				yy = 29;

			}
			// A4
			else if (y > 292 && y < 302 && x > 205 && x < 215) {
				xx = 38;
				yy = 29;

			}

			System.out.println(x + " | " + y);
			PdfContentByte over = stamp.getOverContent(i);
			over.beginText();
			BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1", BaseFont.IDENTITY_H,
					BaseFont.EMBEDDED);
			// BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,//
			// STSongStd-Light
			// BaseFont.WINANSI, false);
			over.setFontAndSize(bf, 9);
			over.setTextMatrix(30, 30);
			Set<Entry<String, String>> set = signoffMapping.entrySet();
			String value = "";
			for (Entry<String, String> entry : set) {
				value = entry.getValue();
				switch (entry.getKey()) {

				case "设计":
					xxx = xx;
					yyy = yy;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "设计时间":
					xxx = xx + 12;
					yyy = yy;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "标准":
					xxx = xx + 40;
					yyy = yy;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "标准时间":
					xxx = xx + 52;
					yyy = yy;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "审核":
					xxx = xx;
					yyy = yy - 15;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "审核时间":
					xxx = xx + 12;
					yyy = yy - 15;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "工艺":
					xxx = xx;
					yyy = yy - 21;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "工艺时间":
					xxx = xx + 12;
					yyy = yy - 21;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "批准":
					xxx = xx + 40;
					yyy = yy - 21;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				case "批准时间":
					xxx = xx + 52;
					yyy = yy - 21;
					over.showTextAligned(Element.ALIGN_LEFT, value, (xxx) * sizeOff, yyy * sizeOff, 0);
					break;
				default:
					break;
				}
				System.out.println(xxx + "/" + yyy);

			}

			over.endText();

		}
		stamp.close();// 关闭
		reader.close();// 关闭
		File tempfile = new File(inPutPath);
		if (tempfile.exists()) {
			// 删除原文件
			// tempfile.delete();
		}

	}

	/**
	 * 给pdf文件添加水印
	 * 
	 * @param InPdfFile     要加水印的原pdf文件路径
	 * @param outPdfFile    加了水印后要输出的路径
	 * @param markImagePath 水印图片路径
	 * @param pageSize      原pdf文件的总页数（该方法是我当初将数据导入excel中然后再转换成pdf所以我这里的值是用excel的行数计算出来的，
	 *                      如果不是我这种可以 直接用reader.getNumberOfPages()获取pdf的总页数）
	 * @throws Exception
	 */
	public void addPdfMark(String InPdfFile, String outPdfFile, String markImagePath) throws Exception {
		// PDF 输入文件
		PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
		// PDF 输出文件
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
		// 水印图片
		Image img = Image.getInstance(markImagePath);
		float imgW = img.getScaledWidth();
		float imgH = img.getScaledHeight();
		// 获取PDF的页数
		int pageSize = reader.getNumberOfPages();
		for (int i = 1; i <= pageSize; i++) {
			Rectangle rectangle = reader.getPageSize(i);
			Float[] fposition = getSize(rectangle);
			// 设置水印的插入位置
			img.setAbsolutePosition(fposition[0] - imgW, fposition[1] - imgH);
			// 向PDF输出文件中插入水印
			PdfContentByte under = stamp.getOverContent(i);//
			stamp.getUnderContent(i);
			PdfGState gs = new PdfGState();
			gs.setFillOpacity(0.4f);// 设置透明度为0.2
			under.setGState(gs);
			under.addImage(img);

		}
		stamp.close();// 关闭
		reader.close();// 关闭
		File tempfile = new File(InPdfFile);
		if (tempfile.exists()) {
			// 删除原文件
			// tempfile.delete();
		}

	}

	public void addPdfMark(String InPdfFile, String outPdfFile) throws Exception {
		InputStream is = null;
		System.getenv("TEMP");

		is = this.getClass().getClassLoader().getResourceAsStream("com/connor/jfeng/pdf/operate/PDFInfo.properties");

		is.close();

	}

	public JFomPdfBean getSize2(Rectangle rectangle) {
		float toleft = rectangle.getLeft();
		float tobottom = rectangle.getBottom();
		float toright = rectangle.getRight();
		float totop = rectangle.getTop();

		JFomPdfBean bean = new JFomPdfBean();
		bean.setH(toright - toleft);
		bean.setW(totop - tobottom);

		return bean;
	}

	/**
	 * 获取PDF的尺寸和图框的匹配并返回需要插入图片的位置
	 * 
	 * @param rectangle
	 * @return
	 */
	public Float[] getSize(Rectangle rectangle) {
		Float[] sizef = new Float[2];
		float toleft = rectangle.getLeft();
		float tobottom = rectangle.getBottom();
		float toright = rectangle.getRight();
		float totop = rectangle.getTop();

		JFomPdfBean bean = new JFomPdfBean();
		bean.setH(toright - toleft);
		bean.setW(totop - tobottom);

		return getPosization(bean);
	}

	/**
	 * 匹配获取插入水印的位置 2.8346
	 * 
	 * @param bean
	 * @return
	 */
	public Float[] getPosization(JFomPdfBean bean) {
		Float size = 2.8346f;
		Float h = (float) (bean.getH() / size);
		Float w = (float) (bean.getW() / size);
		System.out.println(h + " | " + w);
		Float[] sizef = new Float[] { 0.0f, 0.0f };
		if (this.beanList != null) {
			for (int i = 0; i < this.beanList.size(); i++) {
				JFomPdfBean beant = beanList.get(i);
				// System.out.println(bean.getH() + " | "+ beant);
				if ((beant.getH() - 10) < h && h < (beant.getH() + 10) && (beant.getW() - 10) < w
						&& w < (beant.getW() + 10)) {
					sizef[0] = beant.getHi() * size;
					sizef[1] = beant.getWi() * size;
					break;
				}
				if ((beant.getH() - 10) < w && w < (beant.getH() + 10) && (beant.getW() - 10) < h
						&& h < (beant.getW() + 10)) {
					sizef[0] = beant.getHi() * size;
					sizef[1] = beant.getWi() * size;
					break;
				}
			}
		}
		return sizef;
	}
}
