package com.swfarm.biz.warehouse.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.warehouse.bo.Warehouse;
import com.swfarm.biz.warehouse.dto.SearchWarehouseLogsCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.PaginationSupport;

public class EnterTransferStockKeepingUnitsController extends
		AbstractController {

	private WarehouseService warehouseService;

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

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		User user = (User) req.getSession().getAttribute("credential");
		String startIndexStr = req.getParameter("startIndex");
		int startIndex = 0;
		int pageSize = 50;
		if (StringUtils.isNotEmpty(startIndexStr)) {
			startIndex = new Integer(startIndexStr).intValue();
		} else {
			String pageStr = req.getParameter("page");
			if (StringUtils.isNotEmpty(pageStr)) {
				startIndex = PaginationSupport.getPageStartIndex(new Integer(
						pageStr), pageSize);
			}
		}
		Map dataMap = new HashMap();
		String warehouseIdStr = req.getParameter("warehouse");
		Long warehouseId = null;
		if (StringUtils.isNotEmpty(warehouseIdStr)) {
			warehouseId = new Long(warehouseIdStr);
		} else {
			Warehouse defaultWarehouse = this.warehouseService
					.findDefaultWarehouse();
			warehouseId = defaultWarehouse.getId();

		}
		SearchWarehouseLogsCriteria criteria = new SearchWarehouseLogsCriteria();
		criteria.setWarehouseId(warehouseId);
		criteria.setActor(user.getUsername());
		PaginationSupport pagination = this.warehouseService.searchWarehouseLogs(criteria, pageSize, startIndex);
		int page = pagination.getPage(startIndex);
		int[] pageRange = pagination.getPageRange(page);
		List warehouses = this.warehouseService.findWarehouses();
		List stockLocations = this.warehouseService.findStockLocations();
		dataMap.put("pagination", pagination);
		dataMap.put("currentPage", page);
		dataMap.put("pageRange", pageRange);
		dataMap.put("warehouses", warehouses);
		dataMap.put("stockLocations", stockLocations);
		return new ModelAndView("warehouse/transfer_stockkeepingunits", dataMap);
	}
}
