package com.swfarm.biz.chain.srv;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.util.HtmlUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.swfarm.biz.chain.utils.PdfUtils;
import com.swfarm.biz.chain.web.ChainFrontHelper;
import com.swfarm.biz.ebay.bo.CountryMap;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.bo.WarehouseCheckOutVoucher;
import com.swfarm.biz.warehouse.bo.WarehouseCheckOutVoucherItem;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherDTO;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherItemDTO;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherListDTO;
import com.swfarm.biz.warehouse.dto.WarehouseCheckOutVoucherDTO;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.AppContext;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.DateUtils;

public class TinxiDeNewShippingOrderGenerator extends CommonShippingOrderGenerator implements ShippingOrderGenerator {

	Logger logger = Logger.getLogger(TinxiDeNewShippingOrderGenerator.class);

	private ChainService chainService;

	private WarehouseService warehouseService;

	private BarCodeGenerator barCodeGenerator;

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public BarCodeGenerator getBarCodeGenerator() {
		if (this.barCodeGenerator == null) {
			this.barCodeGenerator = new BarCodeGenerator();
			this.barCodeGenerator.setWarehouseService(warehouseService);
		}
		return this.barCodeGenerator;
	}

	public ByteArrayOutputStream generateShippingOrders(Long apvlId) {
		AllocationProductVoucherList apvl = this.warehouseService.findAllocationProductVoucherList(apvlId);
		AllocationProductVoucherListDTO apvlDTO = ChainFrontHelper.getApvlDTOFromApvl(apvl);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(108d);
			float height = PdfUtils.mmToPound(150d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(5, 5, 5, 5);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte canvas = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			this.generateFrontCover(apvlDTO, document, canvas, baseFont);
			document.newPage();
			if (AppContext.getContextData().getPayload() instanceof Boolean) {
				Boolean includecheckoutvoucher = (Boolean) AppContext.getContextData().getPayload();
				if (includecheckoutvoucher != null && includecheckoutvoucher == true) {
					WarehouseCheckOutVoucherDTO wcovDTO = this.chainService
							.generateTransitWarehouseCheckOutVoucherDTOByApvl(apvlDTO.getApvlId());
					this.generateCheckoutVoucherTable(apvlDTO.getApvlNo(), wcovDTO, document,
							canvas, baseFont);
					document.newPage();
				}
			}
			List apvDTOs = apvlDTO.getAllocationProductVoucherDTOs();
			for (Iterator apvIter = apvDTOs.iterator(); apvIter.hasNext();) {
				AllocationProductVoucherDTO apvDTO = (AllocationProductVoucherDTO) apvIter.next();
				generateShippingInfoTable(apvDTO, document, canvas, baseFont);
				generateCustomerOrderTable(apvDTO, document, baseFont);
				document.newPage();
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public void generateCheckoutVoucherTable(String allocationProductVoucherListNo,
			WarehouseCheckOutVoucher warehouseCheckOutVoucher, Document document, PdfContentByte canvas,
			BaseFont baseFont) throws DocumentException, IOException {
		Rectangle pageSize = document.getPageSize();
		float width = pageSize.getWidth();
		float height = pageSize.getHeight();

		PdfPTable table = new PdfPTable(new float[] { 4, 4, 6, 3, 7 });
		table.setLockedWidth(true);
		table.setTotalWidth(270f);
		table.setSpacingBefore(0f);
		table.setSpacingAfter(0f);
		Font font = new Font(baseFont, 10, Font.NORMAL);
		Font boldFont = new Font(baseFont, 8, Font.NORMAL);

		table.getDefaultCell().setPaddingTop(2);
		table.getDefaultCell().setPaddingBottom(2);
		table.getDefaultCell().setPaddingLeft(2);
		table.getDefaultCell().setPaddingRight(2);
		table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		table.getDefaultCell().setNoWrap(true);

		PdfPCell apvlNoCell = new PdfPCell();
		Image image = this.getBarCodeGenerator().getAllocationProductVoucherNo(allocationProductVoucherListNo, canvas);
		apvlNoCell.addElement(image);
		apvlNoCell.setColspan(5);
		apvlNoCell.disableBorderSide(PdfPCell.LEFT);
		apvlNoCell.disableBorderSide(PdfPCell.TOP);
		apvlNoCell.disableBorderSide(PdfPCell.RIGHT);
		table.addCell(apvlNoCell);

		PdfPCell slHeadCell = new PdfPCell(new Phrase("序号", boldFont));
		table.addCell(slHeadCell);
		PdfPCell posHeadCell = new PdfPCell(new Phrase("库位", boldFont));
		table.addCell(posHeadCell);
		PdfPCell articleHeadCell = new PdfPCell(new Phrase("货号", boldFont));
		table.addCell(articleHeadCell);
		PdfPCell quantityHeadCell = new PdfPCell(new Phrase("数量", boldFont));
		table.addCell(quantityHeadCell);
		PdfPCell titleHeadCell = new PdfPCell(new Phrase("名称", boldFont));
		table.addCell(titleHeadCell);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(table.getDefaultCell().ALIGN_LEFT);
		int rowCounter = 1;
		int voucherTotalQuantity = 0;
		String articleNumber = null;
		String stockLocation = null;
		int totalRowCount = warehouseCheckOutVoucher.getWarehouseCheckOutVoucherItemList().size();
		for (Iterator itemIter = warehouseCheckOutVoucher.getWarehouseCheckOutVoucherItemList().iterator(); itemIter
				.hasNext();) {
			WarehouseCheckOutVoucherItem warehouseCheckOutVoucherItem = (WarehouseCheckOutVoucherItem) itemIter.next();
			voucherTotalQuantity += warehouseCheckOutVoucherItem.getQuantity();

			Paragraph rowIndexPara = new Paragraph(rowCounter + "/" + totalRowCount);
			PdfPCell rowIndexCell = new PdfPCell(rowIndexPara);
			table.addCell(rowIndexCell);

			stockLocation = warehouseCheckOutVoucherItem.getStockKeepingUnit().getStockLocation();
			if (warehouseCheckOutVoucherItem.getStockLocation() != null
					&& !warehouseCheckOutVoucherItem.getStockLocation().equals(stockLocation)) {
				stockLocation = warehouseCheckOutVoucherItem.getStockLocation();
			}
			PdfPCell stockLocationCell = new PdfPCell(new Phrase(stockLocation, font));
			table.addCell(stockLocationCell);

			articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
			if (StringUtils.isEmpty(articleNumber)) {
				articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
			}
			PdfPCell articleNumberCell = new PdfPCell(new Phrase(articleNumber, font));
			table.addCell(articleNumberCell);
			Integer quantity = (int) warehouseCheckOutVoucherItem.getQuantity().doubleValue();
			PdfPCell quantityCell = new PdfPCell(new Phrase(quantity.toString(), font));
			table.addCell(quantityCell);
			String itemName = StringUtils.abbreviate(warehouseCheckOutVoucherItem.getStockKeepingUnit().getName(), 30);
			PdfPCell itemNameCell = new PdfPCell(new Phrase(itemName, font));
			table.addCell(itemNameCell);
			rowCounter++;
		}

		PdfPCell totalCell = new PdfPCell(new Phrase("TOTAL", boldFont));
		table.addCell(totalCell);

		PdfPCell articleNumberCell = new PdfPCell();
		table.addCell(articleNumberCell);

		PdfPCell itemTitleCell = new PdfPCell();
		table.addCell(itemTitleCell);

		PdfPCell voucherTotalCell = new PdfPCell(new Phrase("" + voucherTotalQuantity, font));
		table.addCell(voucherTotalCell);

		PdfPCell customerOrderNoCell = new PdfPCell();
		table.addCell(customerOrderNoCell);

		document.add(table);
	}

	public void generateFrontCover(AllocationProductVoucherListDTO apvlDTO, Document document, PdfContentByte canvas,
			BaseFont baseFont) throws DocumentException, IOException {
		PdfPTable table = new PdfPTable(new float[] { 4, 10, 3 });
		Font boldFont = new Font(baseFont, 12, Font.NORMAL);
		table.setLockedWidth(true);
		table.setTotalWidth(270f);
		table.setSpacingBefore(2f);
		table.setSpacingAfter(2f);
		table.setHorizontalAlignment(Element.ALIGN_MIDDLE);

		table.getDefaultCell().setPaddingTop(2);
		table.getDefaultCell().setPaddingBottom(2);
		table.getDefaultCell().setPaddingLeft(10);
		table.getDefaultCell().setPaddingRight(2);
		table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
		table.getDefaultCell().setPaddingLeft(10);
		table.getDefaultCell().setNoWrap(true);

		PdfPCell blankCell = new PdfPCell(new Phrase("\n\n\n\n\n", boldFont));
		blankCell.setColspan(3);
		blankCell.disableBorderSide(PdfPCell.LEFT);
		blankCell.disableBorderSide(PdfPCell.TOP);
		blankCell.disableBorderSide(PdfPCell.RIGHT);
		blankCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(blankCell);

		blankCell = new PdfPCell();
		blankCell.setRowspan(6);
		blankCell.disableBorderSide(PdfPCell.LEFT);
		blankCell.disableBorderSide(PdfPCell.TOP);
		blankCell.disableBorderSide(PdfPCell.RIGHT);
		blankCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(blankCell);

		PdfPCell apvlNoCell = new PdfPCell(new Phrase(apvlDTO.getApvlNo(), boldFont));
		apvlNoCell.disableBorderSide(PdfPCell.LEFT);
		apvlNoCell.disableBorderSide(PdfPCell.TOP);
		apvlNoCell.disableBorderSide(PdfPCell.RIGHT);
		apvlNoCell.disableBorderSide(PdfPCell.BOTTOM);
		apvlNoCell.setPaddingBottom(5);
		table.addCell(apvlNoCell);

		blankCell = new PdfPCell();
		blankCell.setRowspan(6);
		blankCell.disableBorderSide(PdfPCell.LEFT);
		blankCell.disableBorderSide(PdfPCell.TOP);
		blankCell.disableBorderSide(PdfPCell.RIGHT);
		blankCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(blankCell);

		String warehouseCode = "";
		if (StringUtils.isNotEmpty(apvlDTO.getWarehouseCode())) {
			warehouseCode = apvlDTO.getWarehouseCode();
		}
		PdfPCell warehouseCodeCell = new PdfPCell(new Phrase("仓库编码：" + warehouseCode, boldFont));
		warehouseCodeCell.disableBorderSide(PdfPCell.LEFT);
		warehouseCodeCell.disableBorderSide(PdfPCell.TOP);
		warehouseCodeCell.disableBorderSide(PdfPCell.RIGHT);
		warehouseCodeCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(warehouseCodeCell);

		String shippingCompany = "";
		if (StringUtils.isNotEmpty(apvlDTO.getSfcCode())) {
			shippingCompany = apvlDTO.getSfcCode();
		}
		PdfPCell sfcCell = new PdfPCell(new Phrase("物流公司：" + shippingCompany, boldFont));
		sfcCell.disableBorderSide(PdfPCell.LEFT);
		sfcCell.disableBorderSide(PdfPCell.TOP);
		sfcCell.disableBorderSide(PdfPCell.RIGHT);
		sfcCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(sfcCell);

		String shippingMethod = "";
		if (StringUtils.isNotEmpty(apvlDTO.getSfmCode())) {
			shippingMethod = apvlDTO.getSfmCode();
		}
		PdfPCell sfmCell = new PdfPCell(new Phrase("物流方式：" + shippingMethod, boldFont));
		sfmCell.disableBorderSide(PdfPCell.LEFT);
		sfmCell.disableBorderSide(PdfPCell.TOP);
		sfmCell.disableBorderSide(PdfPCell.RIGHT);
		sfmCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(sfmCell);

		PdfPCell apvCountCell = new PdfPCell(new Phrase("发货单数：" + apvlDTO.getApvCount(), boldFont));
		apvCountCell.disableBorderSide(PdfPCell.LEFT);
		apvCountCell.disableBorderSide(PdfPCell.TOP);
		apvCountCell.disableBorderSide(PdfPCell.RIGHT);
		apvCountCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(apvCountCell);

		int skuQuantity = 0;
		for (Iterator iterator = apvlDTO.getAllocationProductVoucherDTOs().iterator(); iterator.hasNext();) {
			AllocationProductVoucherDTO apvDTO = (AllocationProductVoucherDTO) iterator.next();
			for (Iterator iterator2 = apvDTO.getAllocationProductVoucherItemDTOs().iterator(); iterator2.hasNext();) {
				AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) iterator2.next();
				if (apviDTO.getQuantity() != null) {
					skuQuantity += apviDTO.getQuantity();
				}
			}
		}
		PdfPCell skuCountCell = new PdfPCell(new Phrase("产品总数：" + skuQuantity, boldFont));
		skuCountCell.disableBorderSide(PdfPCell.LEFT);
		skuCountCell.disableBorderSide(PdfPCell.TOP);
		skuCountCell.disableBorderSide(PdfPCell.RIGHT);
		skuCountCell.disableBorderSide(PdfPCell.BOTTOM);
		table.addCell(skuCountCell);

		document.add(table);
	}

	public ByteArrayOutputStream generateShippingOrder(Long apvId) {
		AllocationProductVoucher apv = warehouseService.findAllocationProductVoucher(apvId);
		AllocationProductVoucherDTO apvDTO = ChainFrontHelper.getApvDTOFromApv(apv);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(108d);
			float height = PdfUtils.mmToPound(150d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(5, 5, 5, 5);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte cb = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			generateShippingInfoTable(apvDTO, document, cb, baseFont);
			generateCustomerOrderTable(apvDTO, document, baseFont);
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	private void generateCheckoutVoucherTable(String allocationProductVoucherListNo,
			WarehouseCheckOutVoucher warehouseCheckOutVoucher, Document document, BaseFont baseFont)
			throws DocumentException, IOException {
		PdfPTable table = new PdfPTable(new float[] { 4, 3, 2, 7, 6 });
		table.setLockedWidth(true);
		table.setTotalWidth(270f);
		table.setSpacingBefore(0f);
		table.setSpacingAfter(0f);
		Font font = new Font(baseFont, 10, Font.NORMAL);
		Font boldFont = new Font(baseFont, 8, Font.NORMAL);
		PdfPCell cell = new PdfPCell(new Phrase(allocationProductVoucherListNo, font));
		cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		cell.disableBorderSide(PdfPCell.TOP);
		cell.disableBorderSide(PdfPCell.LEFT);
		cell.disableBorderSide(PdfPCell.RIGHT);
		cell.disableBorderSide(PdfPCell.BOTTOM);
		cell.setMinimumHeight(30f);
		cell.setColspan(5);
		table.addCell(cell);
		table.getDefaultCell().setPaddingTop(2);
		table.getDefaultCell().setPaddingBottom(2);
		table.getDefaultCell().setPaddingLeft(2);
		table.getDefaultCell().setPaddingRight(2);
		table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		table.getDefaultCell().setNoWrap(true);
		PdfPCell posHeadCell = new PdfPCell(new Phrase("Lager", boldFont));
		table.addCell(posHeadCell);
		PdfPCell articleHeadCell = new PdfPCell(new Phrase("ArtikelNO", boldFont));
		table.addCell(articleHeadCell);
		PdfPCell quantityHeadCell = new PdfPCell(new Phrase("Qty", boldFont));
		table.addCell(quantityHeadCell);
		PdfPCell titleHeadCell = new PdfPCell(new Phrase("Bezeichnung", boldFont));
		table.addCell(titleHeadCell);
		PdfPCell slHeadCell = new PdfPCell(new Phrase("BelegNO", boldFont));
		table.addCell(slHeadCell);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(table.getDefaultCell().ALIGN_LEFT);
		table.setHeaderRows(1);
		int rowCounter = 1;
		int voucherTotalQuantity = 0;
		int groupStartIndex = 0;
		int groupEndIndex = 0;
		int groupTotalQuantity = 0;
		String articleNumber = null;
		String stockLocation = null;
		for (Iterator itemIter = warehouseCheckOutVoucher.getWarehouseCheckOutVoucherItemList().iterator(); itemIter
				.hasNext();) {
			WarehouseCheckOutVoucherItem warehouseCheckOutVoucherItem = (WarehouseCheckOutVoucherItem) itemIter.next();
			voucherTotalQuantity += warehouseCheckOutVoucherItem.getQuantity();
			if (rowCounter == 1) {
				stockLocation = warehouseCheckOutVoucherItem.getStockKeepingUnit().getStockLocation();
				if (warehouseCheckOutVoucherItem.getStockLocation() != null
						&& !warehouseCheckOutVoucherItem.getStockLocation().equals(stockLocation)) {
					stockLocation = warehouseCheckOutVoucherItem.getStockLocation();
				}
				articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
				if (StringUtils.isEmpty(articleNumber)) {
					articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
				}
				groupStartIndex = rowCounter;
				groupTotalQuantity = 0;
				groupEndIndex = rowCounter;
			}
			if (!warehouseCheckOutVoucherItem.getStockLocation().equals(stockLocation)
					|| !warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber().equals(articleNumber)) {
				if (groupEndIndex - groupStartIndex >= 1) {
					PdfPCell stockLocationCell = new PdfPCell();
					table.addCell(stockLocationCell);

					PdfPCell articleNumberCell = new PdfPCell();
					table.addCell(articleNumberCell);

					PdfPCell groupTotalCell = new PdfPCell(new Phrase("" + groupTotalQuantity, boldFont));
					table.addCell(groupTotalCell);

					PdfPCell itemTitleCell = new PdfPCell();
					table.addCell(itemTitleCell);

					PdfPCell customerOrderNoCell = new PdfPCell();
					table.addCell(customerOrderNoCell);
				}
				groupStartIndex = rowCounter;
				groupTotalQuantity = 0;
			}
			rowCounter++;
			groupEndIndex = rowCounter - 1;
			groupTotalQuantity += warehouseCheckOutVoucherItem.getQuantity();

			stockLocation = warehouseCheckOutVoucherItem.getStockKeepingUnit().getStockLocation();
			if (warehouseCheckOutVoucherItem.getStockLocation() != null
					&& !warehouseCheckOutVoucherItem.getStockLocation().equals(stockLocation)) {
				stockLocation = warehouseCheckOutVoucherItem.getStockLocation();
			}
			PdfPCell stockLocationCell = new PdfPCell(new Phrase(stockLocation, font));
			table.addCell(stockLocationCell);

			articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
			if (StringUtils.isEmpty(articleNumber)) {
				articleNumber = warehouseCheckOutVoucherItem.getStockKeepingUnit().getArticleNumber();
			}
			PdfPCell articleNumberCell = new PdfPCell(new Phrase(articleNumber, font));
			table.addCell(articleNumberCell);
			Integer quantity = (int) warehouseCheckOutVoucherItem.getQuantity().doubleValue();
			PdfPCell quantityCell = new PdfPCell(new Phrase(quantity.toString(), font));
			table.addCell(quantityCell);
			String itemName = StringUtils.abbreviate(warehouseCheckOutVoucherItem.getStockKeepingUnit().getName(), 30);
			PdfPCell itemNameCell = new PdfPCell(new Phrase(itemName, font));
			table.addCell(itemNameCell);
			PdfPCell customerOrderNoCell = new PdfPCell(
					new Phrase(warehouseCheckOutVoucherItem.getCustomerOrderNo(), font));
			table.addCell(customerOrderNoCell);
		}

		if (groupEndIndex - groupStartIndex >= 1) {
			PdfPCell stockLocationCell = new PdfPCell(new Phrase(stockLocation, font));
			table.addCell(stockLocationCell);

			PdfPCell articleNumberCell = new PdfPCell(new Phrase(articleNumber, font));
			table.addCell(articleNumberCell);

			PdfPCell itemTitleCell = new PdfPCell();
			table.addCell(itemTitleCell);

			PdfPCell groupTotalCell = new PdfPCell(new Phrase("" + groupTotalQuantity, font));
			table.addCell(groupTotalCell);

			PdfPCell customerOrderNoCell = new PdfPCell();
			table.addCell(customerOrderNoCell);
		}

		PdfPCell totalCell = new PdfPCell(new Phrase("TOTAL", boldFont));
		table.addCell(totalCell);

		PdfPCell articleNumberCell = new PdfPCell();
		table.addCell(articleNumberCell);

		PdfPCell itemTitleCell = new PdfPCell();
		table.addCell(itemTitleCell);

		PdfPCell voucherTotalCell = new PdfPCell(new Phrase("" + voucherTotalQuantity, font));
		table.addCell(voucherTotalCell);

		PdfPCell customerOrderNoCell = new PdfPCell();
		table.addCell(customerOrderNoCell);

		document.add(table);
	}

	private void generateCustomerOrderTable(AllocationProductVoucherDTO apvDTO, Document document, BaseFont baseFont)
			throws DocumentException, IOException {
		Paragraph spacePara = new Paragraph("\n");
		document.add(spacePara);
		PdfPTable table = new PdfPTable(new float[] { 3, 4, 3, 4 });
		table.setLockedWidth(true);
		table.setTotalWidth(270f);
		table.setSpacingBefore(0f);
		table.setSpacingAfter(0f);
		Font font = new Font(baseFont, 10, Font.NORMAL);

		String packingMaterialArticleNumber = apvDTO.getPackingMaterialArticleNumber();
		Phrase pmanPhrase = null;
		if (StringUtils.isNotEmpty(packingMaterialArticleNumber)) {
			pmanPhrase = new Phrase(packingMaterialArticleNumber);
		}
		PdfPCell packingMaterialCell = null;
		if (pmanPhrase != null) {
			packingMaterialCell = new PdfPCell(pmanPhrase);
		} else {
			packingMaterialCell = new PdfPCell();
		}
		packingMaterialCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		packingMaterialCell.disableBorderSide(PdfPCell.TOP);
		packingMaterialCell.disableBorderSide(PdfPCell.LEFT);
		packingMaterialCell.disableBorderSide(PdfPCell.RIGHT);
		packingMaterialCell.disableBorderSide(PdfPCell.BOTTOM);
		packingMaterialCell.setMinimumHeight(15f);
		packingMaterialCell.setColspan(4);
		table.addCell(packingMaterialCell);

		table.getDefaultCell().setPaddingTop(2);
		table.getDefaultCell().setPaddingBottom(2);
		table.getDefaultCell().setPaddingLeft(2);
		table.getDefaultCell().setPaddingRight(2);
		table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		table.getDefaultCell().setNoWrap(true);
		PdfPCell posHeadCell = new PdfPCell(new Phrase("Pos.", font));
		table.addCell(posHeadCell);
		PdfPCell articleHeadCell = new PdfPCell(new Phrase("Artikelnr.", font));
		table.addCell(articleHeadCell);
		PdfPCell quantityHeadCell = new PdfPCell(new Phrase("Menge", font));
		table.addCell(quantityHeadCell);
		PdfPCell slHeadCell = new PdfPCell(new Phrase("Lager", font));
		table.addCell(slHeadCell);
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(table.getDefaultCell().ALIGN_LEFT);
		table.setHeaderRows(2);
		int index = 1;
		List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
		for (Iterator iter = apviDTOs.iterator(); iter.hasNext();) {
			AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) iter.next();
			PdfPCell posCell = new PdfPCell(new Phrase(index++ + " / " + apviDTOs.size(), font));
			table.addCell(posCell);
			PdfPCell articleCell = new PdfPCell(new Phrase(apviDTO.getArticleNumber(), font));
			table.addCell(articleCell);
			PdfPCell quantityCell = new PdfPCell(
					new Phrase(String.format("%d", (int) (apviDTO.getQuantity().doubleValue())), font));
			table.addCell(quantityCell);
			PdfPCell slCell = new PdfPCell();
			slCell.setPhrase(new Phrase(apviDTO.getStockLocation(), font));
			table.addCell(slCell);
		}
		document.add(table);
	}

	private void generateShippingInfoTable(AllocationProductVoucherDTO apvDTO, Document document, PdfContentByte canvas,
			BaseFont baseFont) throws DocumentException, Exception {
		if (CollectionUtils.isNotEmpty(apvDTO.getAllocationProductVoucherItemDTOs())) {

			Rectangle pageSize = document.getPageSize();
			float width = pageSize.getWidth();
			float height = pageSize.getHeight();
			PdfPTable table = new PdfPTable(new float[] { 1, 1, 1, 1 });

			table.setLockedWidth(true);
			table.setTotalWidth(width - 4);
			table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
			table.setSpacingBefore(0f);
			table.setSpacingAfter(0f);
			table.getDefaultCell().setBackgroundColor(null);
			table.getDefaultCell().setNoWrap(false);
			table.getDefaultCell().setMinimumHeight(0f);
			table.getDefaultCell().disableBorderSide(PdfPCell.TOP);
			table.getDefaultCell().disableBorderSide(PdfPCell.RIGHT);
			table.getDefaultCell().disableBorderSide(PdfPCell.BOTTOM);
			table.getDefaultCell().disableBorderSide(PdfPCell.LEFT);

			String shippingMethod = apvDTO.getSfmCode();
			String shippingCompany = getShippingCompany(shippingMethod);

			Font msyhFont = new Font(baseFont, 16, Font.NORMAL);
			PdfPCell briefLogoCell = null;
			if ("Ausland".equalsIgnoreCase(shippingMethod)) {
				briefLogoCell = new PdfPCell();
				Image briefLogoImage = this.getImage("brieflogo.png");
				briefLogoCell.addElement(briefLogoImage);
			} else {
				if (shippingMethod.toUpperCase().startsWith("WARENSENDUNG")) {
					briefLogoCell = new PdfPCell(new Paragraph("WARENSENDUNG", msyhFont));
				} else {
					briefLogoCell = new PdfPCell();
				}
			}
			briefLogoCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			briefLogoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			briefLogoCell.disableBorderSide(PdfPCell.TOP);
			briefLogoCell.disableBorderSide(PdfPCell.RIGHT);
			briefLogoCell.disableBorderSide(PdfPCell.BOTTOM);
			briefLogoCell.disableBorderSide(PdfPCell.LEFT);
			briefLogoCell.setColspan(2);
			table.addCell(briefLogoCell);

			msyhFont = new Font(baseFont, 14, Font.NORMAL);
			String shippingMethodDecideType = apvDTO.getShippingMethodDecideType();
			StringBuffer buffer = new StringBuffer();
			buffer.append(shippingMethod);
			if (StringUtils.isNotEmpty(shippingMethodDecideType)) {
				buffer.append(" (" + shippingMethodDecideType + ")");
			}
			Paragraph shippingMethodPara = new Paragraph(buffer.toString(), msyhFont);
			PdfPCell shippingMethodCell = new PdfPCell(shippingMethodPara);
			shippingMethodCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			shippingMethodCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			shippingMethodCell.disableBorderSide(PdfPCell.TOP);
			shippingMethodCell.disableBorderSide(PdfPCell.RIGHT);
			shippingMethodCell.disableBorderSide(PdfPCell.BOTTOM);
			shippingMethodCell.disableBorderSide(PdfPCell.LEFT);
			shippingMethodCell.setColspan(2);
			table.addCell(shippingMethodCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			String sellerName = null;
			if ("tinxide58".equalsIgnoreCase(Env.TINXIDE_CODE)) {
				// 58服务器
				sellerName = "tinxi.com Boschstrasse.5 76344 Eggenstein-Leo.";
			} else {
				// 47服务器
				sellerName = "DKS Logistik   Schubertstrasse 53   D-15234 Frankfurt(Oder)";
			}
			Paragraph sellerNamePara = new Paragraph(sellerName, msyhFont);
			PdfPCell sellerNameCell = new PdfPCell(sellerNamePara);
			sellerNameCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			sellerNameCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			sellerNameCell.disableBorderSide(PdfPCell.TOP);
			sellerNameCell.disableBorderSide(PdfPCell.RIGHT);
			sellerNameCell.disableBorderSide(PdfPCell.BOTTOM);
			sellerNameCell.disableBorderSide(PdfPCell.LEFT);
			sellerNameCell.setColspan(4);
			table.addCell(sellerNameCell);

			msyhFont = new Font(baseFont, 16, Font.NORMAL);
			StringBuffer buyerInfoBuffer = new StringBuffer();
			if (StringUtils.isNotEmpty(apvDTO.getBuyerFullname())) {
				buyerInfoBuffer.append(unescape(apvDTO.getBuyerFullname()));
				buyerInfoBuffer.append("\n");
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1())) {
				buyerInfoBuffer.append(unescape(apvDTO.getBuyerAddress1()));
				buyerInfoBuffer.append("\n");
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
				buyerInfoBuffer.append(unescape(apvDTO.getBuyerAddress2()));
				buyerInfoBuffer.append("\n");
			}
			StringBuffer sb = new StringBuffer();
			if (StringUtils.isNotEmpty(apvDTO.getBuyerZip())) {
				sb.append(apvDTO.getBuyerZip());
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerCity())) {
				sb.append(" ");
				sb.append(apvDTO.getBuyerCity());
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerState())) {
				sb.append(" ");
				sb.append(apvDTO.getBuyerState());
			}
			String buyerCityState = sb.toString();
			if (StringUtils.isNotEmpty(buyerCityState)) {
				buyerInfoBuffer.append(buyerCityState);
				buyerInfoBuffer.append("\n");
			}
			String buyerCountry = apvDTO.getBuyerCountry();

			if (StringUtils.isNotEmpty(buyerCountry)) {
				String mappingCountry = CountryMap.getMappingCountry(buyerCountry);
				if (StringUtils.isEmpty(mappingCountry)) {
					mappingCountry = buyerCountry;
				}
				buyerInfoBuffer.append(mappingCountry);
				buyerInfoBuffer.append("\n");
			}

			Paragraph buyerInfoPara = new Paragraph(buyerInfoBuffer.toString(), msyhFont);
			PdfPCell buyerInfoCell = new PdfPCell(buyerInfoPara);
			buyerInfoCell.setMinimumHeight(110f);
			buyerInfoCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			buyerInfoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			buyerInfoCell.disableBorderSide(PdfPCell.TOP);
			buyerInfoCell.disableBorderSide(PdfPCell.RIGHT);
			buyerInfoCell.disableBorderSide(PdfPCell.BOTTOM);
			buyerInfoCell.disableBorderSide(PdfPCell.LEFT);
			buyerInfoCell.setColspan(4);
			table.addCell(buyerInfoCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer customerOrderInfoBuffer = new StringBuffer();
			customerOrderInfoBuffer.append("Beleg Nr ");
			customerOrderInfoBuffer.append(apvDTO.getCustomerOrderNo());
			customerOrderInfoBuffer.append(" Kunden Nr ");
			if (StringUtils.isNotEmpty(apvDTO.getCustomerName())) {
				customerOrderInfoBuffer.append(apvDTO.getCustomerName());
			} else {
				customerOrderInfoBuffer.append(apvDTO.getBuyerFullname());
			}
			customerOrderInfoBuffer.append(" Datum ");
			customerOrderInfoBuffer.append(DateUtils.dateToString(apvDTO.getOrderTime(), "dd.MM.yyyy"));
			Paragraph customerOrderInfoPara = new Paragraph(customerOrderInfoBuffer.toString(), msyhFont);
			PdfPCell customerOrderInfoCell = new PdfPCell(customerOrderInfoPara);
			customerOrderInfoCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			customerOrderInfoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			customerOrderInfoCell.disableBorderSide(PdfPCell.TOP);
			customerOrderInfoCell.disableBorderSide(PdfPCell.RIGHT);
			customerOrderInfoCell.disableBorderSide(PdfPCell.BOTTOM);
			customerOrderInfoCell.disableBorderSide(PdfPCell.LEFT);
			customerOrderInfoCell.setColspan(4);
			table.addCell(customerOrderInfoCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			String warningInfo = "Bitter bei alle Rueckfragen angeben!";
			Paragraph warningInfoPara = new Paragraph(warningInfo, msyhFont);
			PdfPCell warningInfoCell = new PdfPCell(warningInfoPara);
			warningInfoCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			warningInfoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			warningInfoCell.disableBorderSide(PdfPCell.TOP);
			warningInfoCell.disableBorderSide(PdfPCell.RIGHT);
			warningInfoCell.disableBorderSide(PdfPCell.BOTTOM);
			warningInfoCell.disableBorderSide(PdfPCell.LEFT);
			warningInfoCell.setColspan(4);
			table.addCell(warningInfoCell);

			Paragraph linePara = new Paragraph("\n", msyhFont);
			PdfPCell spaceCell = new PdfPCell(linePara);
			spaceCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			spaceCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			spaceCell.disableBorderSide(PdfPCell.TOP);
			spaceCell.disableBorderSide(PdfPCell.RIGHT);
			spaceCell.disableBorderSide(PdfPCell.BOTTOM);
			spaceCell.disableBorderSide(PdfPCell.LEFT);
			spaceCell.setColspan(4);
			table.addCell(spaceCell);

			spaceCell = new PdfPCell();
			spaceCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			spaceCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			spaceCell.disableBorderSide(PdfPCell.TOP);
			spaceCell.disableBorderSide(PdfPCell.RIGHT);
			spaceCell.disableBorderSide(PdfPCell.BOTTOM);
			spaceCell.disableBorderSide(PdfPCell.LEFT);
			table.addCell(spaceCell);

			PdfPCell customerOrderNoCell = new PdfPCell();
			Image image = this.getBarCodeGenerator().getAllocationProductVoucherNo(apvDTO.getCustomerOrderNo(), canvas);
			customerOrderNoCell.addElement(image);
			customerOrderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			customerOrderNoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			customerOrderNoCell.disableBorderSide(PdfPCell.TOP);
			customerOrderNoCell.disableBorderSide(PdfPCell.RIGHT);
			customerOrderNoCell.disableBorderSide(PdfPCell.BOTTOM);
			customerOrderNoCell.disableBorderSide(PdfPCell.LEFT);
			customerOrderNoCell.setColspan(2);
			table.addCell(customerOrderNoCell);

			spaceCell = new PdfPCell();
			spaceCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			spaceCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			spaceCell.disableBorderSide(PdfPCell.TOP);
			spaceCell.disableBorderSide(PdfPCell.RIGHT);
			spaceCell.disableBorderSide(PdfPCell.BOTTOM);
			spaceCell.disableBorderSide(PdfPCell.LEFT);
			table.addCell(spaceCell);

			document.add(table);

		}
	}

	private String unescape(String input) {
		String output = HtmlUtils.htmlUnescape(input);
		if (output.contains("&apos;")) {
			output = output.replaceAll("&apos;", "'");
		}
		return output;
	}

	private String getShippingCompany(String shippingMethod) {
		if ("Post1".equalsIgnoreCase(shippingMethod) || "Post2".equalsIgnoreCase(shippingMethod)) {
			return "Warensendung";
		} else if ("DPI".equalsIgnoreCase(shippingMethod)) {
			return "DHL";
		} else {
			return "";
		}
	}

	public BaseFont getBaseFont() throws Exception {
		String fontFileName = "arialuni.ttf";
		String osName = System.getProperty("os.name");
		if ("Windows 7".equals(osName) || "Windows 8".equals(osName)) {
			fontFileName = "MSYHBD.TTF";
		}

		return BaseFont.createFont(this.getClass().getResource("/") + "/fonts/" + fontFileName, BaseFont.IDENTITY_H,
				BaseFont.EMBEDDED, BaseFont.NOT_CACHED, null, null);
	}

	private Image getImage(String imageFile) {
		try {
			Image image = Image.getInstance(Env.APP_REAL_PATH + "images/" + imageFile);
			return image;
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return null;
	}

	public ByteArrayOutputStream generateShippingOrders(AllocationProductVoucherListDTO apvlDTO) {
		return null;
	}

	public ByteArrayOutputStream generateShippingOrder(AllocationProductVoucherDTO apvDTO) {
		BarCodeGenerator barCodeGenerator = new BarCodeGenerator();
		barCodeGenerator.setWarehouseService(warehouseService);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(108d);
			float height = PdfUtils.mmToPound(150d);
			Document document = new Document(new Rectangle(width, height));
			Rectangle pageSize = document.getPageSize();
			document.setMargins(5, 5, 5, 5);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte canvas = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
			if (!CollectionUtils.isEmpty(apviDTOs)) {
				generateShippingInfoTable(apvDTO, document, canvas, baseFont);
				generateCustomerOrderTable(apvDTO, document, baseFont);
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public ByteArrayOutputStream generateShippingOrderInfo(List<AllocationProductVoucherDTO> apvDTOs) {
		return null;
	}

	public void generateShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, Document document,
			PdfContentByte canvas, BaseFont baseFont) throws DocumentException, Exception {
	}

	public ByteArrayOutputStream generateCheckoutVouchers(Long apvlId) {
		AllocationProductVoucherList apvl = this.warehouseService.findAllocationProductVoucherList(apvlId);
		AllocationProductVoucherListDTO apvlDTO = ChainFrontHelper.getApvlDTOFromApvl(apvl);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(108d);
			float height = PdfUtils.mmToPound(150d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(5, 5, 5, 5);
			PdfWriter writer = PdfWriter.getInstance(document, ba);
			document.open();
			PdfContentByte canvas = writer.getDirectContent();
			BaseFont baseFont = this.getBaseFont();
			this.generateFrontCover(apvlDTO, document, canvas, baseFont);
			document.newPage();
			if (AppContext.getContextData().getPayload() instanceof Boolean) {
				Boolean includecheckoutvoucher = (Boolean) AppContext.getContextData().getPayload();
				if (includecheckoutvoucher != null && includecheckoutvoucher == true) {
					WarehouseCheckOutVoucherDTO warehouseCheckOutVoucher = this.chainService
							.generateTransitWarehouseCheckOutVoucherDTOByApvl(apvlDTO.getApvlId());
					this.generateCheckoutVoucherTable(apvlDTO.getApvlNo(),
							warehouseCheckOutVoucher, document, canvas, baseFont);
					document.newPage();
				}
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

}
