package com.swfarm.biz.chain.srv;

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

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.bo.ShippingGroup;
import com.swfarm.biz.chain.bo.ShippingMethod;
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.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.NumberUtils;

public class BrtSzpyShippingOrderGenerator extends CommonShippingOrderGenerator implements ShippingOrderGenerator {

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

	private WarehouseService warehouseService = null;

	private ChainService chainService = null;

	private BarCodeGenerator barCodeGenerator;

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

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

	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 = warehouseService.findAllocationProductVoucherList(apvlId);
		AllocationProductVoucherListDTO apvlDTO = ChainFrontHelper.getApvlDTOFromApvl(apvl);
		return generateShippingOrders(apvlDTO);
	}

	public ByteArrayOutputStream generateShippingOrders(AllocationProductVoucherListDTO apvlDTO) {
		BarCodeGenerator barCodeGenerator = new BarCodeGenerator();
		barCodeGenerator.setWarehouseService(warehouseService);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(100d);
			float height = PdfUtils.mmToPound(100d);
			Document document = new Document(new Rectangle(width, height));
			document.setMargins(2, 2, 2, 2);
			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();
				List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
				if (!CollectionUtils.isEmpty(apviDTOs)) {
					generateShippingInfoTable(apvDTO, "1/1", document, canvas, baseFont);
					document.newPage();
					logger.warn("is generate apv table [" + ChainFrontHelper.getIsGenerateApvTable() + "]");
					if (ChainFrontHelper.getIsGenerateApvTable() == true) {
						if (apvDTO.getAllocationProductVoucherItemDTOs().size() > 1
								|| StringUtils.isNotEmpty(apvDTO.getCustomerServiceMessage())
								|| Env.NOT_GENERATE_APV_TABLE == false) {
							generateAllocationProductVoucherTable(apvDTO, document, baseFont);
							document.newPage();
						}
					}
				}
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public ByteArrayOutputStream generateShippingOrder(Long apvId) {
		AllocationProductVoucher apv = warehouseService.findAllocationProductVoucher(apvId);
		AllocationProductVoucherDTO apvDTO = ChainFrontHelper.getApvDTOFromApv(apv);
		return generateShippingOrder(apvDTO);
	}

	public ByteArrayOutputStream generateShippingOrder(AllocationProductVoucherDTO apvDTO) {
		BarCodeGenerator barCodeGenerator = new BarCodeGenerator();
		barCodeGenerator.setWarehouseService(warehouseService);
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {
			float width = PdfUtils.mmToPound(100d);
			float height = PdfUtils.mmToPound(100d);
			Document document = new Document(new Rectangle(width, height));
			Rectangle pageSize = document.getPageSize();
			document.setMargins(2, 2, 2, 2);
			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, "1/1", document, canvas, baseFont);
				if (apviDTOs.size() > 1) {
					document.newPage();
					Boolean isGenerateApvTable = false;
					if (AppContext.getContextData().getPayload() instanceof Boolean) {
						isGenerateApvTable = (Boolean) AppContext.getContextData().getPayload();
					}
					if (isGenerateApvTable == null) {
						isGenerateApvTable = false;
					}
					if (isGenerateApvTable == true) {
						generateAllocationProductVoucherTable(apvDTO, document, baseFont);
						document.newPage();
					}
				}
			}
			writer.flush();
			document.close();
			writer.close();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		return ba;
	}

	public void generateShippingInfoTable(AllocationProductVoucherDTO apvDTO, String pageIndex, 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[] { width * 5 / 18, width * 3 / 18, width * 3 / 18, width * 3 / 18, width * 4 / 18 });
			table.setLockedWidth(true);
			table.setTotalWidth(width - 4);
			table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
			table.getDefaultCell().setBackgroundColor(null);
			table.getDefaultCell().setNoWrap(false);
			table.getDefaultCell().setMinimumHeight(0f);

			Image chinaPostImage = Image.getInstance(Env.APP_REAL_PATH + "images/chinapost.jpg");
			chinaPostImage.setAlignment(Element.ALIGN_LEFT);
			chinaPostImage.scaleAbsolute(80, 15);

			PdfPCell chinaPostCell = new PdfPCell();
			chinaPostCell.addElement(chinaPostImage);
			chinaPostCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			chinaPostCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			chinaPostCell.disableBorderSide(PdfPCell.RIGHT);
			table.addCell(chinaPostCell);

			Font msyhFont = new Font(baseFont, 6, Font.NORMAL);
			PdfPCell smallPacketCell = new PdfPCell(new Paragraph("Small Packet BY AIR", msyhFont));
			smallPacketCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			smallPacketCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			smallPacketCell.disableBorderSide(PdfPCell.LEFT);
			smallPacketCell.setColspan(2);
			table.addCell(smallPacketCell);

			msyhFont = new Font(baseFont, 6, Font.NORMAL);
			String buyerCountry = apvDTO.getBuyerCountry();
			String destCountryName = CountryMap.getCountryShortName(buyerCountry);
			PdfPCell destCountryCell = new PdfPCell(new Paragraph(destCountryName, msyhFont));
			destCountryCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			destCountryCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(destCountryCell);

			Image wishPostImage = Image.getInstance(Env.APP_REAL_PATH + "images/inspected.png");
			wishPostImage.setAlignment(Element.ALIGN_RIGHT);
			wishPostImage.scaleAbsolute(50, 15);

			PdfPCell wishPostCell = new PdfPCell();
			wishPostCell.addElement(wishPostImage);
			wishPostCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
			wishPostCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(wishPostCell);

			StringBuffer sellerFullAddressBuffer = getSellerAddress();
			Font addressFont = new Font(baseFont, 7, Font.NORMAL);
			Paragraph sellerFullAddressPara = new Paragraph(sellerFullAddressBuffer.toString(), addressFont);
			PdfPCell sellerFullAddressCell = new PdfPCell(sellerFullAddressPara);
			sellerFullAddressCell.setLeading(2f, 1f);
			sellerFullAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			sellerFullAddressCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
			sellerFullAddressCell.setColspan(2);
			table.addCell(sellerFullAddressCell);

			addressFont = new Font(baseFont, 9, Font.BOLD);
			String buyerFullAddress = this.getBuyerFullAddress(apvDTO).toString();
			Paragraph buyerFullAddressPara = new Paragraph(buyerFullAddress, addressFont);
			PdfPCell buyerFullAddressCell = new PdfPCell(buyerFullAddressPara);
			buyerFullAddressCell.setLeading(2f, 1f);
			buyerFullAddressCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			buyerFullAddressCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
			buyerFullAddressCell.setColspan(3);
			buyerFullAddressCell.setRowspan(2);
			table.addCell(buyerFullAddressCell);

			addressFont = new Font(baseFont, 8, Font.NORMAL);
			Paragraph sellerOrderNoPara = new Paragraph("自编号：" + apvDTO.getApvNo(), addressFont);
			PdfPCell sellerOrderNoCell = new PdfPCell(sellerOrderNoPara);
			sellerOrderNoCell.setLeading(2f, 1f);
			sellerOrderNoCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			sellerOrderNoCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
			sellerOrderNoCell.setColspan(2);
			table.addCell(sellerOrderNoCell);

			Paragraph noTrackingPara = new Paragraph("untracked", addressFont);
			PdfPCell noTrackingCell = new PdfPCell(noTrackingPara);
			noTrackingCell.setLeading(2f, 1f);
			noTrackingCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			noTrackingCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			noTrackingCell.disableBorderSide(PdfPCell.RIGHT);
			table.addCell(noTrackingCell);

			String shippingOrderNo = apvDTO.getShippingOrderNo();
			if (StringUtils.isEmpty(shippingOrderNo)) {
				shippingOrderNo = apvDTO.getApvNo();
			}
			Image trackingNumberImage = this.getBarCodeGenerator().getAllocationProductVoucherNo(shippingOrderNo,
					canvas);
			trackingNumberImage.scaleAbsolute(150, 10);
			trackingNumberImage.setAlignment(Image.ALIGN_MIDDLE);
			PdfPCell trackingNumberCell = new PdfPCell();
			trackingNumberCell.addElement(trackingNumberImage);
			trackingNumberCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			trackingNumberCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			trackingNumberCell.disableBorderSide(PdfPCell.LEFT);
			trackingNumberCell.setColspan(4);
			table.addCell(trackingNumberCell);

			msyhFont = new Font(baseFont, 6, Font.NORMAL);
			PdfPCell returnLabelCell = new PdfPCell(new Paragraph("退件单位：EMS苏虹营业部 苏虹中路77号", msyhFont));
			returnLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			returnLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			returnLabelCell.setColspan(2);
			table.addCell(returnLabelCell);

			msyhFont = new Font(baseFont, 6, Font.NORMAL);
			PdfPCell customerNameLabelCell = new PdfPCell(new Paragraph("客户名称：博瑞特", msyhFont));
			customerNameLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			customerNameLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			customerNameLabelCell.setColspan(3);
			table.addCell(customerNameLabelCell);

			PdfPCell descLabelCell = new PdfPCell(new Paragraph("Description of Contents", msyhFont));
			descLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			descLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			descLabelCell.disableBorderSide(PdfPCell.TOP);
			descLabelCell.setColspan(3);
			table.addCell(descLabelCell);

			PdfPCell weightLabelCell = new PdfPCell(new Paragraph("kg.", msyhFont));
			weightLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			weightLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			weightLabelCell.disableBorderSide(PdfPCell.TOP);
			table.addCell(weightLabelCell);

			PdfPCell valueLabelCell = new PdfPCell(new Paragraph("Val(US $)", msyhFont));
			valueLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			valueLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			valueLabelCell.disableBorderSide(PdfPCell.TOP);
			table.addCell(valueLabelCell);

			int index = 0;

			Double totalWeight = 0d;
			Double totalValue = 0d;
			Double totalQuantity = 0d;
			Double avgValue = 0d;

			for (Iterator itemIter = apvDTO.getAllocationProductVoucherItemDTOs().iterator(); itemIter.hasNext();) {
				if (index < 5) {
					AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) itemIter.next();
					totalQuantity += apviDTO.getQuantity();
					totalValue += apviDTO.getPrice() * apviDTO.getQuantity();
				} else {
					break;
				}
				index++;
			}
			if (totalValue > apvDTO.getTotalPrice()) {
				totalValue = apvDTO.getTotalPrice();
				avgValue = NumberUtils.round(totalValue / totalQuantity, 2);
			}
			if (totalValue > 15) {
				totalValue = 14.9d;
				avgValue = NumberUtils.round(totalValue / totalQuantity, 2);
			}

			index = 0;
			totalWeight = 0d;
			totalValue = 0d;
			for (Iterator itemIter = apvDTO.getAllocationProductVoucherItemDTOs().iterator(); itemIter.hasNext();) {
				if (index < 5) {
					AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) itemIter.next();
					StringBuffer itemDescBuffer = new StringBuffer();

					String declareEnName = apviDTO.getDeclareEnName();
					String declareCnName = apviDTO.getDeclareCnName();

					if (StringUtils.isNotEmpty(declareEnName)) {
						itemDescBuffer.append(declareEnName);
					}

					String itemDesc = itemDescBuffer.toString();
					if (itemDesc.length() > 25) {
						itemDesc = itemDesc.substring(0, 25);
					}
					itemDesc = itemDesc + " X " + apviDTO.getQuantity();
					if (apvDTO.getAllocationProductVoucherItemDTOs().size() == 1) {
						itemDesc = itemDesc + "\n";
						itemDesc = itemDesc + apviDTO.getArticleNumber() + " X " + apviDTO.getQuantity().intValue()
								+ " [" + apviDTO.getStockLocation() + "]";
						itemDesc = itemDesc + "\n";
						itemDesc = itemDesc + apviDTO.getSkuName();
						msyhFont = new Font(baseFont, 10, Font.NORMAL);
					}
					Paragraph lineSixFirstPara = new Paragraph(itemDesc, msyhFont);
					PdfPCell lineSixFirstCell = new PdfPCell(lineSixFirstPara);
					lineSixFirstCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
					lineSixFirstCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
					lineSixFirstCell.setColspan(3);
					table.addCell(lineSixFirstCell);

					StringBuffer weightBuffer = new StringBuffer();
					Double itemWeight = NumberUtils.round(apviDTO.getSkuWeight() * apviDTO.getQuantity() * 0.001, 3);
					weightBuffer.append(itemWeight);
					totalWeight += itemWeight;
					Paragraph lineSixSecondPara = new Paragraph(weightBuffer.toString(), msyhFont);
					PdfPCell lineSixSecondCell = new PdfPCell(lineSixSecondPara);
					lineSixSecondCell.setMinimumHeight(8f);
					lineSixSecondCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					lineSixSecondCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
					table.addCell(lineSixSecondCell);

					Double declareValue = apviDTO.getPrice() * apviDTO.getQuantity();
					if (avgValue > 0) {
						declareValue = avgValue * apviDTO.getQuantity();
					}
					declareValue = NumberUtils.round(declareValue, 2);
					StringBuffer valueBuffer = new StringBuffer();
					valueBuffer.append(declareValue);
					totalValue += declareValue;
					Paragraph lineSixThirdPara = new Paragraph(valueBuffer.toString(), msyhFont);
					PdfPCell lineSixThirdCell = new PdfPCell(lineSixThirdPara);
					lineSixThirdCell.setMinimumHeight(8f);
					lineSixThirdCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					lineSixThirdCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
					table.addCell(lineSixThirdCell);
				} else {
					break;
				}
				index++;
			}
			totalWeight = NumberUtils.round(totalWeight, 3);
			totalValue = NumberUtils.round(totalValue, 2);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			PdfPCell totalLabelCell = new PdfPCell(new Paragraph("Total Gross Weight(kg)", msyhFont));
			totalLabelCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			totalLabelCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			totalLabelCell.setColspan(3);
			table.addCell(totalLabelCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer totalWeightBuffer = new StringBuffer();
			totalWeightBuffer.append(totalWeight);
			Paragraph lineEightSecondPara = new Paragraph(totalWeightBuffer.toString(), msyhFont);
			PdfPCell lineEightSecondCell = new PdfPCell(lineEightSecondPara);
			lineEightSecondCell.setMinimumHeight(8f);
			lineEightSecondCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			lineEightSecondCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(lineEightSecondCell);

			msyhFont = new Font(baseFont, 8, Font.NORMAL);
			StringBuffer totalValueBuffer = new StringBuffer();
			totalValueBuffer.append(totalValue);
			Paragraph lineEightThirdPara = new Paragraph(totalValueBuffer.toString(), msyhFont);
			PdfPCell lineEightThirdCell = new PdfPCell(lineEightThirdPara);
			lineEightThirdCell.setMinimumHeight(8f);
			lineEightThirdCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			lineEightThirdCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(lineEightThirdCell);

			StringBuffer declarationBuffer = new StringBuffer();
			declarationBuffer.append("I,the undersigned, certify the particulars given in this declaration are correct "
					+ "and this item does not contain any dangerous articles prohibited by legislation "
					+ "or customs regulations                                    CN22");
			Paragraph declarationPara = new Paragraph(declarationBuffer.toString(), msyhFont);
			PdfPCell declarationCell = new PdfPCell(declarationPara);
			declarationCell.setMinimumHeight(16f);
			declarationCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			declarationCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			declarationCell.setColspan(5);
			table.addCell(declarationCell);

			document.add(table);
		}
	}

	private StringBuffer getSellerAddress() {
		StringBuffer sellerFullAddressBuffer = new StringBuffer();
		if (Env.COMPANY_CODE.equalsIgnoreCase("accecity")) {
			sellerFullAddressBuffer.append("From:\n");
			sellerFullAddressBuffer.append("4/f,14th building To:DaYuan industry park,\n");
			sellerFullAddressBuffer.append("Fengze District,\n");
			sellerFullAddressBuffer.append("PingShan Rd, Nanshan\n");
			sellerFullAddressBuffer.append("Shenzhen,China, 51800 \n");
			sellerFullAddressBuffer.append("phone：13428786019");
		} else if (Env.COMPANY_CODE.equalsIgnoreCase("bright")) {
			sellerFullAddressBuffer.append("From:\n");
			sellerFullAddressBuffer.append("BRTSZ\n");
			sellerFullAddressBuffer.append("FLOOR 2, NO. 6 DONG WANG ROAD, \n");
			sellerFullAddressBuffer.append("INDUSTRIAL PARK DISTRICT, \n");
			sellerFullAddressBuffer.append("SUZHOU, JIANGSU, CHINA, 215000\n");
			sellerFullAddressBuffer.append("PHONE：18051115815");
		}
		return sellerFullAddressBuffer;
	}

	public void generateAllocationProductVoucherTable(AllocationProductVoucherDTO apvDTO, Document document,
			BaseFont baseFont) throws DocumentException, Exception {
		Font msyhFont = new Font(baseFont, 8, Font.NORMAL);
		AllocationProductVoucherListDTO apvlDTO = apvDTO.getAllocationProductVoucherListDTO();
		if (apvlDTO != null) {
			Paragraph apvlNoPara = new Paragraph(apvlDTO.getApvlNo(), msyhFont);
			document.add(apvlNoPara);
		}
		String customerServiceMessage = apvDTO.getCustomerServiceMessage();
		if (StringUtils.isNotEmpty(customerServiceMessage)) {
			Paragraph customerServiceMessagePara = new Paragraph(customerServiceMessage, msyhFont);
			document.add(customerServiceMessagePara);
		}
		List packingMemoList = new ArrayList();
		List apviDTOs = apvDTO.getAllocationProductVoucherItemDTOs();
		for (Iterator iter = apviDTOs.iterator(); iter.hasNext();) {
			AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) iter.next();
			String packingMemo = apviDTO.getSkuPackingMemo();
			if (StringUtils.isNotEmpty(packingMemo)) {
				if (!packingMemoList.contains(packingMemo)) {
					packingMemoList.add(packingMemo);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(packingMemoList)) {
			String packingMemos = StringUtils.join(packingMemoList, "\n");
			Paragraph packingMemoPara = new Paragraph("包装注意: " + packingMemos, msyhFont);
			document.add(packingMemoPara);
		}
		PdfPTable table = new PdfPTable(new float[] { 3, 4, 3, 3, 9 });
		table.setLockedWidth(true);
		table.setTotalWidth(document.getPageSize().getWidth() - 4);
		table.setSpacingBefore(0f);
		table.setSpacingAfter(0f);
		table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
		PdfPCell apvNoCell = new PdfPCell(new Phrase(apvDTO.getApvNo(), msyhFont));
		apvNoCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		apvNoCell.disableBorderSide(PdfPCell.TOP);
		apvNoCell.disableBorderSide(PdfPCell.LEFT);
		apvNoCell.disableBorderSide(PdfPCell.RIGHT);
		apvNoCell.disableBorderSide(PdfPCell.BOTTOM);
		apvNoCell.setMinimumHeight(15f);
		apvNoCell.setColspan(4);
		table.addCell(apvNoCell);
		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(1);
		table.addCell(packingMaterialCell);
		table.getDefaultCell().setUseAscender(true);
		table.getDefaultCell().setUseDescender(true);
		table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		table.getDefaultCell().setNoWrap(true);
		for (int i = 0; i < 1; i++) {
			Phrase posHeadPhrase = new Phrase("序号", msyhFont);
			table.addCell(posHeadPhrase);
			Phrase articleHeadPhrase = new Phrase("货号", msyhFont);
			table.addCell(articleHeadPhrase);
			Phrase quantityHeadPhrase = new Phrase("数量", msyhFont);
			table.addCell(quantityHeadPhrase);
			Phrase slHeadPhrase = new Phrase("库位", msyhFont);
			table.addCell(slHeadPhrase);
			Phrase titleHeadPhrase = new Phrase("产品", msyhFont);
			table.addCell(titleHeadPhrase);
		}
		table.getDefaultCell().setBackgroundColor(null);
		table.getDefaultCell().setNoWrap(false);
		table.getDefaultCell().setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		table.getDefaultCell().setHorizontalAlignment(table.getDefaultCell().ALIGN_LEFT);
		table.getDefaultCell().setPaddingTop(2);
		table.getDefaultCell().setPaddingBottom(2);
		table.setHeaderRows(2);
		int index = 1;

		Long apvlId = apvDTO.getAllocationProductVoucherListDTO().getApvlId();
		WarehouseCheckOutVoucherDTO wcovDTO = this.chainService
				.generateTransitWarehouseCheckOutVoucherDTOByApvl(apvlId);

		for (Iterator iter = apvDTO.getAllocationProductVoucherItemDTOs().iterator(); iter.hasNext();) {
			AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) iter.next();
			Phrase posPhrase = new Phrase(index++ + " / " + apvDTO.getAllocationProductVoucherItemDTOs().size(),
					msyhFont);
			table.addCell(posPhrase);
			String articleNumber = apviDTO.getArticleNumber();
			Phrase articlePhrase = new Phrase(articleNumber, msyhFont);
			PdfPCell articleCell = new PdfPCell();
			articleCell.setPhrase(articlePhrase);
			articleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			table.addCell(articleCell);
			Phrase quantityPhrase = new Phrase(String.format("%d", (int) (apviDTO.getQuantity().doubleValue())),
					msyhFont);
			table.addCell(quantityPhrase);
			StringBuffer slBuffer = new StringBuffer();
			String transitStockLocation = wcovDTO.getTransitStockLocation(articleNumber);
			if (StringUtils.isNotEmpty(transitStockLocation)) {
				slBuffer.append(transitStockLocation);
				slBuffer.append("\n");
			}
			slBuffer.append(apviDTO.getStockLocation());
			Phrase slPhrase = new Phrase(slBuffer.toString(), msyhFont);
			table.addCell(slPhrase);
			Phrase titlePhrase = new Phrase(apviDTO.getSkuName(), msyhFont);
			table.addCell(titlePhrase);
		}
		document.add(table);
	}

	private StringBuffer getBuyerFullAddress(AllocationProductVoucherDTO apvDTO) {
		StringBuffer buyerInfoBuffer = new StringBuffer();
		buyerInfoBuffer.append("Ship To: ");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerFullname())) {
			buyerInfoBuffer.append(apvDTO.getBuyerFullname());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1()) || StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress1())) {
				buyerInfoBuffer.append(apvDTO.getBuyerAddress1());
			}
			if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
				buyerInfoBuffer.append(" ");
				buyerInfoBuffer.append(apvDTO.getBuyerAddress2());
			}
			buyerInfoBuffer.append("\n");
		}
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCity())) {
			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");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerZip())) {
			buyerInfoBuffer.append(apvDTO.getBuyerZip());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
			sb = new StringBuffer();
			if (StringUtils.isNotEmpty(apvDTO.getBuyerCountry())) {
				String originalCountry = apvDTO.getBuyerCountry();
				String mappingCountry = CountryMap.getMappingCountry(originalCountry);

				String countryAlias = CountryMap.getCountryAlias(mappingCountry);
				sb.append(mappingCountry);

				String shippingForwarderMethod = apvDTO.getSfmCode();
				String[] showGroupMethods = new String[] { "CNPY", "FZPY", "QZCNPY", "SZCNPY", "CNGH", "QZCNGH",
						"SZCNGH" };
				String groupName = null;
				if (ArrayUtils.contains(showGroupMethods, shippingForwarderMethod)) {
					String buyerCountry = apvDTO.getBuyerCountry();
					if (null != buyerCountry) {
						ShippingGroup shippingGroup = chainService.getShippingGroupByCountryCode(buyerCountry,
								shippingForwarderMethod, null);
						if (shippingGroup != null) {
							groupName = shippingGroup.getName();
						} else {
							logger.warn("no ShippingGroup ,buyercountry=" + buyerCountry);
						}
					} else {
						logger.warn("no buyer country:" + apvDTO.getApvId());
					}
				}
				if (StringUtils.isNotEmpty(groupName)) {
					sb.append(" ");
					sb.append(groupName);
				}
				if (StringUtils.isNotEmpty(countryAlias)) {
					sb.append(" ");
					sb.append(countryAlias);
				}
			}
			buyerInfoBuffer.append(sb.toString());
			buyerInfoBuffer.append("\n");
		}
		if (StringUtils.isNotEmpty(apvDTO.getBuyerPhoneNumber()) || StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
			if (StringUtils.isNotEmpty(apvDTO.getBuyerPhoneNumber())) {
				buyerInfoBuffer.append("Phone: " + apvDTO.getBuyerPhoneNumber());
				if (StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
					buyerInfoBuffer.append("\\");
					buyerInfoBuffer.append(apvDTO.getBuyerMobile());
				}
			} else {
				if (StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
					buyerInfoBuffer.append("Phone: " + apvDTO.getBuyerMobile());
				}
			}
		}

		return buyerInfoBuffer;
	}

	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);
	}

	public String getShippingForwarderMethodName(String shippingForwarderMethod) {
		if (StringUtils.isNotEmpty(shippingForwarderMethod)) {
			ShippingMethod shippingMethod = this.chainService.findShippingMethodByCode(shippingForwarderMethod);
			if (shippingMethod != null) {
				return shippingMethod.getName();
			}
		}
		return shippingForwarderMethod;
	}

	public ByteArrayOutputStream generateShippingOrders(List customerOrders) {
		return null;
	}
}
