package com.swfarm.biz.chain.web;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.SaleChannelAccount;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.utils.ImageUtils;

public class DownloadSmtTrackingListController extends AbstractController {

	private static final String[] titles = { "订单编号", "发货单号", "平台单号", "货运单号",
			"店铺编号" };

	private static final double MAGIC_FACTOR = 1.112877583;

	private WarehouseService warehouseService;

	private ChainService chainService;

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

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

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		Long apvlId = new Long(req.getParameter("apvl"));
		AllocationProductVoucherList allocationProductVoucherList = this.warehouseService
				.findAllocationProductVoucherList(apvlId);
		HSSFWorkbook wb = new HSSFWorkbook();
		Map<String, CellStyle> styles = createStyles(wb);
		HSSFSheet sheet = wb.createSheet("客户订单");
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(false);
		sheet.setAutobreaks(true);
		printSetup.setFitHeight((short) 1);
		printSetup.setFitWidth((short) 1);
		HSSFRow headerRow = sheet.createRow(0);
		headerRow.setHeightInPoints(12.75f);
		for (int i = 0; i < titles.length; i++) {
			HSSFCell cell = headerRow.createCell(i);
			cell.setCellValue(titles[i]);
			cell.setCellStyle(styles.get("header"));
		}
		HSSFRow row = null;
		HSSFCell cell = null;
		for (int i = 0; i < 4; i++) {
			sheet.setColumnWidth(i, (int) (15 * 256 * MAGIC_FACTOR));
		}
		int rowCounter = 1;
		for (Iterator iter = allocationProductVoucherList
				.getAllocationProductVoucherList().iterator(); iter.hasNext();) {
			AllocationProductVoucher apv = (AllocationProductVoucher) iter
					.next();
			CustomerOrder customerOrder = apv.getCustomerOrder();
			String sfmCode = apv.getShippingForwarderMethod();
			String[] ywPySfmCodes = new String[] { "YUB", "YWCNPY", "BJGH", "BKGH" };
			row = sheet.createRow(rowCounter);
			int cellCounter = 0;
			// A
			cell = row.createCell(cellCounter++);
			cell.setCellValue(customerOrder.getCustomerOrderNo());
			cell.setCellStyle(styles.get("cell_normal"));
			// B
			cell = row.createCell(cellCounter++);
			cell.setCellValue(apv.getAllocationProductVoucherNo());
			cell.setCellStyle(styles.get("cell_normal"));
			// C
			cell = row.createCell(cellCounter++);
			cell.setCellValue(customerOrder.getSaleChannelOrderId());
			cell.setCellStyle(styles.get("cell_normal"));
			// D
			cell = row.createCell(cellCounter++);
			if (ArrayUtils.contains(ywPySfmCodes, sfmCode)) {
				cell.setCellValue(apv.getRefShippingOrderNo());
			} else {
				cell.setCellValue(apv.getShippingOrderNo());
			}
			cell.setCellStyle(styles.get("cell_normal"));
			// E
			cell = row.createCell(cellCounter++);
			String accountNumber = customerOrder.getAccountNumber();
			if (StringUtils.isNotEmpty(accountNumber)) {
				SaleChannelAccount saleChannelAccount = this.chainService
						.findSaleChannelAccountByAccountNumber(accountNumber);
				cell.setCellValue(saleChannelAccount.getAccountNumberSeq());
			}
			cell.setCellStyle(styles.get("cell_normal"));
			rowCounter++;
		}
		res.setContentType("application/ms-excel");
		String fileName = "客户订单.xls";
		res.setHeader("Content-Disposition", "attachment; filename="
				+ java.net.URLEncoder.encode(fileName, "UTF-8"));
		OutputStream out = res.getOutputStream();
		wb.write(out);
		return null;
	}

	private static Map<String, CellStyle> createStyles(HSSFWorkbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
		DataFormat df = wb.createDataFormat();

		CellStyle style;
		Font headerFont = wb.createFont();
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setFont(headerFont);
		styles.put("header", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setFont(headerFont);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("header_date", style);

		Font font1 = wb.createFont();
		font1.setBoldweight(Font.BOLDWEIGHT_BOLD);
		font1.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font1);
		styles.put("cell_b", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFont(font1);
		styles.put("cell_b_centered", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_b_date", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_g", style);

		Font font2 = wb.createFont();
		font2.setColor(IndexedColors.BLUE.getIndex());
		font2.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font2);
		styles.put("cell_bb", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setFont(font1);
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_bg", style);

		Font font3 = wb.createFont();
		font3.setFontHeightInPoints((short) 10);
		font3.setColor(IndexedColors.DARK_BLUE.getIndex());
		font3.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setFont(font3);
		style.setWrapText(true);
		styles.put("cell_h", style);

		Font normalFont = wb.createFont();
		normalFont.setFontHeightInPoints((short) 10);
		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setWrapText(true);
		style.setFont(normalFont);
		styles.put("cell_normal", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setWrapText(true);
		styles.put("cell_normal_centered", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		style.setWrapText(true);
		style.setDataFormat(df.getFormat("d-mmm"));
		styles.put("cell_normal_date", style);

		style = createBorderedStyle(wb);
		style.setAlignment(CellStyle.ALIGN_LEFT);
		style.setIndention((short) 1);
		style.setWrapText(true);
		styles.put("cell_indented", style);

		style = createBorderedStyle(wb);
		style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		styles.put("cell_blue", style);

		return styles;
	}

	private static CellStyle createBorderedStyle(HSSFWorkbook wb) {
		CellStyle style = wb.createCellStyle();
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		return style;
	}

	private static byte[] getImage(String url) {
		return ImageUtils.generateImage(url);
	}

}
