package com.swfarm.biz.chain.web;

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

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

import org.apache.commons.collections.CollectionUtils;
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.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.dto.FilterApvlsDTO;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.dto.SearchAllocationProductVoucherListsCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseQueryService;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.utils.ImageUtils;

public class FilterApvlsController extends AbstractController {

	private static final String[] titles = { "APVL", "YSTD", "订单号", "平台", "店铺", "物流方式", "包货状态", "单数", "同步失败原因" };

	private static final double MAGIC_FACTOR = 1.112877583;

	private WarehouseService warehouseService;

	private WarehouseQueryService warehouseQueryService;

	public void setWarehouseQueryService(WarehouseQueryService warehouseQueryService) {
		this.warehouseQueryService = warehouseQueryService;
	}

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

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String[] whiteList = new String[] { "HKPY" };
		SearchAllocationProductVoucherListsCriteria criteria = (SearchAllocationProductVoucherListsCriteria) req
				.getAttribute("criteria");
		String[] apvlIdArr = req.getParameterValues("apvlId");
		List<AllocationProductVoucherList> apvlList = new ArrayList<AllocationProductVoucherList>();
		if (!ArrayUtils.isEmpty(apvlIdArr)) {
			List<Long> apvlIds = new ArrayList<Long>();
			for (String apvlIdStr : apvlIdArr) {
				apvlIds.add(new Long(apvlIdStr));
			}
			apvlList = this.warehouseService.findAllocationProductVoucherLists(apvlIds);
		} else if (criteria != null) {
			apvlList = this.warehouseService.searchAllocationProductVoucherLists(criteria);
		}
		List<FilterApvlsDTO> apvls = new ArrayList<FilterApvlsDTO>();
		List<String> successApvlNos = new ArrayList<String>();
		if (CollectionUtils.isNotEmpty(apvlList)) {
			for (Iterator iterator = apvlList.iterator(); iterator.hasNext();) {
				AllocationProductVoucherList apvl = (AllocationProductVoucherList) iterator.next();
				int syncFailureCount = 0;
				List<AllocationProductVoucher> apvs = apvl.getAllocationProductVoucherList();
				if (CollectionUtils.isNotEmpty(apvs)) {
					for (Iterator iterator2 = apvs.iterator(); iterator2.hasNext();) {
						FilterApvlsDTO filterApvlsDTO = new FilterApvlsDTO();
						AllocationProductVoucher apv = (AllocationProductVoucher) iterator2.next();
						if (apv.checkSynShippingOrderNoSuccess() == true) {
							continue;
						} else {
							if (StringUtils.isNotEmpty(apv.getShippingOrderNo())) {
								continue;
							} else if (ArrayUtils.contains(whiteList, apv.getShippingForwarderMethod())) {
								continue;
							} else {
								syncFailureCount++;
								filterApvlsDTO
										.setAllocationProductVoucherListNo(apv.getAllocationProductVoucherListNo());
								filterApvlsDTO.setAllocationProductVoucherNo(apv.getAllocationProductVoucherNo());
								filterApvlsDTO.setSaleChannel(apv.getSaleChannel());
								filterApvlsDTO.setAccountNumber(apv.getAccountNumber());
								filterApvlsDTO.setCustomerOrderNo(apv.getCustomerOrderNo());
								filterApvlsDTO.setShippingForwarderMethod(apv.getShippingForwarderMethod());
								filterApvlsDTO.setPackingStatus(apv.getPackingStatus());
								filterApvlsDTO.setQuantity(new Double(apvl.getApvCount()));
								if (StringUtils.isNotEmpty(apv.getSynShippingOrderNoFailureReason())) {
									filterApvlsDTO.setSyncFailureReason(apv.getSynShippingOrderNoFailureReason());
								} else {
									filterApvlsDTO.setSyncFailureReason(null);
								}
								apvls.add(filterApvlsDTO);
							}
						}
					}
				}
				// 全部同步成功
				if (syncFailureCount == 0) {
					this.addApvlNos(successApvlNos, apvl);
				}
			}
		}
		// 更新发货单的打单状态
		if (CollectionUtils.isNotEmpty(apvls)) {
			List<String> apvlNos = new ArrayList<String>();
			for (FilterApvlsDTO apvl : apvls) {
				if (!(StringUtils.isNotEmpty(apvl.getAllocateStatus())
						&& apvl.getAllocateStatus().contains("含失败发货单"))) {
					apvlNos.add(apvl.getAllocationProductVoucherListNo());
				}
			}
			this.warehouseQueryService.updateApvlAllocateStatus(apvlNos);
		}
		if (CollectionUtils.isNotEmpty(successApvlNos)) {
			this.warehouseQueryService.removeApvlAllocateStatus(successApvlNos);
		}
		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 < 7; i++) {
			sheet.setColumnWidth(i, (int) (15 * 256 * MAGIC_FACTOR));
		}
		int rowCounter = 1;
		if (CollectionUtils.isNotEmpty(apvls)) {
			for (Iterator iterator2 = apvls.iterator(); iterator2.hasNext();) {
				FilterApvlsDTO apvlDTO = (FilterApvlsDTO) iterator2.next();
				int startRowIndex = rowCounter + 1;
				row = sheet.createRow(rowCounter);
				int cellCounter = 0;
				// A APVL
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getAllocationProductVoucherListNo());
				cell.setCellStyle(styles.get("cell_normal"));
				// B YSTD
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getAllocationProductVoucherNo());
				cell.setCellStyle(styles.get("cell_normal"));
				// C 订单号
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getCustomerOrderNo());
				cell.setCellStyle(styles.get("cell_normal"));
				// C 平台
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getSaleChannel());
				cell.setCellStyle(styles.get("cell_normal"));
				// C 店铺
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getAccountNumber());
				cell.setCellStyle(styles.get("cell_normal"));
				// D 物流方式
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getShippingForwarderMethod());
				cell.setCellStyle(styles.get("cell_normal"));
				// E 包货状态
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getPackingStatus());
				cell.setCellStyle(styles.get("cell_normal"));
				// F 单数
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getQuantity());
				cell.setCellStyle(styles.get("cell_normal"));
				// G 同步失败原因
				cell = row.createCell(cellCounter++);
				cell.setCellValue(apvlDTO.getSyncFailureReason());
				cell.setCellStyle(styles.get("cell_normal"));

				if (!iterator2.hasNext()) {
					int endRowIndex = rowCounter + 1;
					if (endRowIndex - startRowIndex > 1) {
						sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + startRowIndex + ":$A$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$B$" + startRowIndex + ":$B$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + startRowIndex + ":$C$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$D$" + startRowIndex + ":$D$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$E$" + startRowIndex + ":$E$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$F$" + startRowIndex + ":$F$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$G$" + startRowIndex + ":$G$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$H$" + startRowIndex + ":$H$" + endRowIndex));
						sheet.addMergedRegion(CellRangeAddress.valueOf("$I$" + startRowIndex + ":$I$" + endRowIndex));
					}
				}
				rowCounter++;
			}
		}
		resp.setContentType("application/ms-excel");
		String fileName = "同步失败发货单.xls";
		resp.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
		OutputStream out = resp.getOutputStream();
		wb.write(out);

		return null;
	}

	private void addApvlNos(List<String> successApvlNos, AllocationProductVoucherList apvl) {
		if (!successApvlNos.contains(apvl.getAllocationProductVoucherListNo())) {
			successApvlNos.add(apvl.getAllocationProductVoucherListNo());
		}
	}

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