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

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

import com.dev.swms.server.model.base.BoxModel;
import com.dev.swms.server.model.shipping.BOLCaseDetail;
import com.dev.swms.server.service.base.BoxModelManager;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.energy.server.service.pojo.DefaultBaseManager;

public class DefaultBoxModelManager extends DefaultBaseManager implements
		BoxModelManager {

	public void caseStore(BoxModel boxModel) {
		if (boxModel.isNew()) {
			boxModel.setDisabled(false);
			boxModel.setWarehouse(WarehouseHolder.getWarehouse());
		}
		commonDao.store(boxModel);
	}

	public void inActive(List<Long> ids) {
		for (Long id : ids) {
			BoxModel boxModel = commonDao.load(BoxModel.class, id);
			boxModel.setDisabled(true);
		}
	}

	public void restore(List<Long> ids) {
		for (Long id : ids) {
			BoxModel boxModel = commonDao.load(BoxModel.class, id);
			boxModel.setDisabled(false);
		}
	}

	public void backBoxModelManager(Long boxModelId, String shipToName, long quantity) {
		String hql = "select detail from BOLCaseDetail detail where detail.boxModel.id=" + boxModelId +
					" and detail.shipQuantity>detail.backQuantity"+
					" and detail.shipToName='"+shipToName.trim()+"'";
		List<BOLCaseDetail> details = this.commonDao.findByQuery(hql);
		for(BOLCaseDetail detail:details){
			if((detail.getShipQuantity()-detail.getBackQuantity())>=quantity){
				detail.setBackQuantity(detail.getBackQuantity()+quantity);
				break;
			}else{
				quantity = quantity-(detail.getShipQuantity()-detail.getBackQuantity());
				detail.setBackQuantity(detail.getShipQuantity());
			}
			this.commonDao.store(detail);
		}
	}

	public void backBoxModels(Long boxModelId, Map map) {
		BoxModel boxModel = commonDao.load(BoxModel.class, boxModelId);
		for (Object obj : map.keySet()) {
			Long detailId = Long.parseLong(obj.toString());
			List ids = (List)map.get(detailId);
			long quantity = Long.parseLong(ids.get(0).toString()); 
			String hql = "select detail from BOLCaseDetail detail where detail.shipToName = (select dt.shipToName from BOLCaseDetail dt where dt.id="+detailId+")";
			List<BOLCaseDetail> details = this.commonDao.findByQuery(hql);
			for(BOLCaseDetail detail:details){
				if(detail.getSignQuantity()<=detail.getBackQuantity()){//如果没有签收数量，则不返还
					continue;
				}
				if((detail.getSignQuantity()-detail.getBackQuantity())>=quantity){
					detail.setBackQuantity(detail.getBackQuantity()+quantity);
					break;
				}else{
					quantity = quantity-(detail.getShipQuantity()-detail.getBackQuantity());
					detail.setBackQuantity(detail.getShipQuantity());
				}
				this.commonDao.store(detail);
			}
		}
	}
}