package com.dev.swms.server.service.fee.pojo;

import java.util.Date;
import java.util.List;

import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.fee.InventoryCount;
import com.dev.swms.server.model.fee.InventoryLPCount;
import com.dev.swms.server.service.fee.InventoryCountManager;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.energy.server.service.pojo.DefaultBaseManager;

public class DefaultInventoryCountManager extends DefaultBaseManager implements
		InventoryCountManager {

	/**
	 * 生成某天的库存计数
	 */
	public void countInventoty(Date countDate) {
		countInventotyByWarehouseId(WarehouseHolder.getWarehouse().getId(),countDate);
	}
	
	@SuppressWarnings("unchecked")
	public void countInventoty(){
		List<Long> wavehouseIds = this.commonDao.findByQuery("select id from Warehouse where disabled = false");
		Date date = new Date();
		for(Long warehouseId:wavehouseIds){
			try {
				countInventotyByWarehouseId(warehouseId,date);
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 生成某天的库存计数
	 */
	@SuppressWarnings("unchecked")
	public void countInventotyByWarehouseId(Long warehouseId,Date date) {
		commonDao.executeByNamed("deleteInventoryCountByDate", new String[] {"feeDate","warehouseId"}, new Object[] {date,warehouseId});
		List<InventoryCount> inventoryCounts = this.commonDao.findByNamedQuery("getInventoryCountEveryDay",new String[]{"warehouseId"},new Object[]{warehouseId});
		List<InventoryLPCount> inventoryLPCounts = this.commonDao.findByNamedQuery("getInventoryLPCountEveryDay", new String[]{"warehouseId"},new Object[]{warehouseId});
		for(InventoryCount inventoryCount:inventoryCounts){
			boolean flag = false;
			inventoryCount.setCountDate(date);
			for(InventoryLPCount inventoryLPCount:inventoryLPCounts){
				if(inventoryLPCount.getCompany().getId().equals(inventoryCount.getCompany().getId())
						&&inventoryLPCount.getItemFeeType().equals(inventoryCount.getItemFeeType())
						&&inventoryLPCount.getItem().getId().equals(inventoryCount.getItem().getId())){
					inventoryCount.setLpQty(inventoryLPCount.getLpQty());
					flag = true;
					break;
				}
			}
			if(!flag){
				inventoryCount.setLpQty(0);
			}

			inventoryCount.setWarehouse(this.commonDao.load(Warehouse.class, warehouseId));
			this.store(inventoryCount);
		}
	}

}
