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

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

import com.dev.swms.client.ui.page.CustomEntity;
import com.dev.swms.client.ui.page.DisplayEntity;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LotInfo;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.Position;
import com.dev.swms.server.model.rules.PutRackRule;
import com.dev.swms.server.service.rule.PutRackRuleManager;
import com.dev.swms.server.tools.format.Format;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.energy.client.utils.StringUtils;
import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;

@SuppressWarnings("unchecked")
public class DefaultPutRackRuleManager extends DefaultBaseManager implements
		PutRackRuleManager {

	public void storePurRackRule(PutRackRule putRackRule,String LP) {
		//上架规则的库位定位分类和默认上架库位必须填写一个或两个都填写
		if((putRackRule.getPosition()==null || putRackRule.getPosition().getId()==0)
				&& ((putRackRule.getDefaultLocation()==null) || putRackRule.getDefaultLocation().getId()==0)){
			throw new BusinessException("PutRackRule.no.StowageAndDefaultLocation");
		}
		//当定位分类和库位均指定时，只存放具体库位
		if((putRackRule.getPosition()!=null && putRackRule.getPosition().getId()!=0)
				&& ((putRackRule.getDefaultLocation()!=null) && putRackRule.getDefaultLocation().getId()!=0)){
			putRackRule.setPosition(null);
		}
		//当垂直补货定位分类和库位均指定时，只存放具体库位
		if((putRackRule.getVerticalPosition()!=null && putRackRule.getVerticalPosition().getId()!=0)
				&& ((putRackRule.getDefaultLocation()!=null) && putRackRule.getDefaultLocation().getId()!=0)){
			putRackRule.setVerticalPosition(null);
		}
		if(LP==null || LP.equals("")){
			putRackRule.setLP(null);
		}
		
		if (putRackRule.getLotInfo() != null) {
			putRackRule.getLotInfo().format();
		}
		
		if ("".equals(putRackRule.getQualityCode())) {
			putRackRule.setQualityCode(null);
		}
		if ("".equals(putRackRule.getItemBigType())) {
			putRackRule.setItemBigType(null);
		}
		if ("".equals(putRackRule.getItemMiddleType())) {
			putRackRule.setItemMiddleType(null);
		}
		if ("".equals(putRackRule.getItemLittleType())) {
			putRackRule.setItemLittleType(null);
		}
		if ("".equals(putRackRule.getItemPutawayType())) {
			putRackRule.setItemPutawayType(null);
		}
		
		if (putRackRule.getAbcType()==null || "".equals(putRackRule.getAbcType())) {
			putRackRule.setAbcType("");
		}
		
		putRackRule.setWarehouse(WarehouseHolder.getWarehouse());//仓库
		if(putRackRule.isNew()){
			if(putRackRule.getLotInfo()!= null && putRackRule.getLotInfo().getPropL1()!=null && putRackRule.getLotInfo().getPropL1()!=0){
				Structure supplier = this.commonDao.load(Structure.class, putRackRule.getLotInfo().getPropL1());
				LotInfo lotInfo = putRackRule.getLotInfo();
				lotInfo.setPropLC1(supplier.getName());
			}
			this.store(putRackRule);
		}
		else{
			this.commonDao.store(mdfPurRackRuleForUpdate(putRackRule));
		}
	}
	/**
	 * 用于commDao的保存
	 * @param putRackRule
	 */
	private PutRackRule mdfPurRackRuleForUpdate(PutRackRule putRackRule){
		int sortIndex = putRackRule.getSortIndex(); //优先级
		
		Structure company = null;
		if(putRackRule.getCompany()!=null && putRackRule.getCompany().getId()!=0)
			company = this.commonDao.load(Structure.class,putRackRule.getCompany().getId());//货主
		
		BillType billType = null;
		if(putRackRule.getBillType()!=null && putRackRule.getBillType().getId()!=0)
			billType = this.commonDao.load(BillType.class,putRackRule.getBillType().getId());//订单类型
		
		String itemPutawayType = putRackRule.getItemPutawayType();
		
		Item item = null;
		if(putRackRule.getItem()!=null && putRackRule.getItem().getId()!=0)
			item = this.commonDao.load(Item.class,putRackRule.getItem().getId());//货品
		
		int packageLineNo = putRackRule.getPackageLineNo();//包装行号
		
		String abcType = putRackRule.getAbcType()==null?"":putRackRule.getAbcType();
		
		Boolean LP = putRackRule.getLP();//是否托盘上架
		Boolean verticalAutoMove = putRackRule.getVerticalAutoMove();//是否垂直补货
		LotInfo lotInfo = putRackRule.getLotInfo();//批次属性
		if(putRackRule.getLotInfo().getPropL1()!=null && putRackRule.getLotInfo().getPropL1()!=0){
			Structure supplier = this.commonDao.load(Structure.class, putRackRule.getLotInfo().getPropL1());
			lotInfo.setPropLC1(supplier.getName());
		}
		
		Position position = null;
		if(putRackRule.getPosition()!=null && putRackRule.getPosition().getId()!=0)
			position = this.commonDao.load(Position.class,putRackRule.getPosition().getId());//库存定位分类
		
		Position verticalPosition = null;
		if(putRackRule.getVerticalPosition()!=null && putRackRule.getVerticalPosition().getId()!=0)
			verticalPosition = this.commonDao.load(Position.class,putRackRule.getVerticalPosition().getId());//垂直补货库存定位分类
	
		String putMethod = putRackRule.getPutMethod();
		
		Location defaultLocation = null;
		if(putRackRule.getDefaultLocation()!=null && putRackRule.getDefaultLocation().getId()!=0){
			defaultLocation = this.commonDao.load(Location.class,putRackRule.getDefaultLocation().getId());
		}
		
		double minQty = putRackRule.getMinQty();
		double maxQty = putRackRule.getMaxQty();
		String qualityCode = putRackRule.getQualityCode();//质损代码		
		String itemBigType = putRackRule.getItemBigType();//货品大类		
		String itemMiddleType = putRackRule.getItemMiddleType();//货品中类		
		String itemLittleType = putRackRule.getItemLittleType();//货品小类
			
		putRackRule = this.commonDao.load(PutRackRule.class,putRackRule.getId());
		
		putRackRule.setSortIndex(sortIndex);
		putRackRule.setCompany(company);
		putRackRule.setBillType(billType);
		putRackRule.setItemPutawayType(itemPutawayType);
		putRackRule.setItem(item);
		putRackRule.setPackageLineNo(packageLineNo);
		putRackRule.setLP(LP);
		putRackRule.setLotInfo(lotInfo);
		putRackRule.setPosition(position);
		putRackRule.setVerticalAutoMove(verticalAutoMove);
		putRackRule.setVerticalPosition(verticalPosition);
		putRackRule.setPutMethod(putMethod);
		putRackRule.setDefaultLocation(defaultLocation);
		putRackRule.setMinQty(minQty);
		putRackRule.setMaxQty(maxQty);
		putRackRule.setQualityCode(qualityCode);//质损代码		
		putRackRule.setItemBigType(itemBigType);//货品大类		
		putRackRule.setItemMiddleType(itemMiddleType);//货品中类		
		putRackRule.setItemLittleType(itemLittleType);//货品小类
		putRackRule.setAbcType(abcType);
		
		return putRackRule;
	}

	public void deletePutRackRule(List<Long> ids) {
		// TODO Auto-generated method stub
		for(Long id:ids){
			this.delete(this.commonDao.load(PutRackRule.class,id));
		}
	}
	/**
	 * 初始化树的时候查当前仓库下策略的所有客户信息
	 */
	public Map getPutRackRuleByWareHouseId(Map param) {
		Map result = new HashMap();
		List<CustomEntity> results = new ArrayList<CustomEntity>();
		Long id = WarehouseHolder.getWarehouse().getId();
		List<Structure> orgs = this.commonDao.findByNamedQuery("getPutRackRuleByWareHouseId",
				new String[]{"warehouseId"},new Object[]{id});
		for(Structure org:orgs){
			CustomEntity en = new CustomEntity();
			if(org!=null){
				en.setId(org.getId());
				en.setName(Format.format("<font style='color:black;font:normal 12px tahoma,arial,helvetica;'>{0}</font> "
						,new String[]{org.getName()+"策略"}));
				en.setCompanyId(org.getId());
				en.setType(1);
				en.setRandomNum(Math.random());
				
				results.add(en);
			}else{
				en.setId(null);
				en.setName(Format.format("<font style='color:black;font:normal 12px tahoma,arial,helvetica;'>{0}</font> "
						,new String[]{"默认客户策略"}));
				en.setCompanyId(null);
				en.setType(1);
				en.setRandomNum(Math.random());
			}
		}
		result.put("result",results);
		return result;
	}
	/**
	 * 展开客户树的时候根据仓库和客户查订单类型信息
	 */
	public Map getBillTypeByCompanyId(Map param) {
		Long companyId = (Long)param.get("id");
		Map result = new HashMap();
		List<CustomEntity> results = new ArrayList<CustomEntity>();
		Long id = WarehouseHolder.getWarehouse().getId();
		List<BillType> bts = new ArrayList<BillType>();
		if(companyId!=null){
			bts = this.commonDao.findByNamedQuery("getPutRackRuleByCompanyId",
					new String[]{"warehouseId","companyId"},new Object[]{id,companyId});
		}else{
			bts = this.commonDao.findByNamedQuery("getPutRackRuleByCompanyIdNull",
					new String[]{"warehouseId"},new Object[]{id});
		}
		CustomEntity tempen = new CustomEntity();//默认订单类型显示在后面	
		for(BillType bt:bts){
			CustomEntity en = new CustomEntity();
			if(bt!=null){
				en.setId(bt.getId());
				en.setName(Format.format("<font style='color:black;font:normal 12px tahoma,arial,helvetica;'>{0}</font> "
						,new String[]{bt.getName()+"策略"}));
				en.setCompanyId(companyId);
				en.setBillTypeId(bt.getId());
				en.setType(2);
				en.setRandomNum(Math.random());
				
				results.add(en);
			}else{
				en.setId(null);
				en.setName(Format.format("<font style='color:black;font:normal 12px tahoma,arial,helvetica;'>{0}</font> "
						,new String[]{"默认订单类型策略"}));
				en.setCompanyId(companyId);
				en.setBillTypeId(null);
				en.setType(2);
				en.setRandomNum(Math.random());
				
				tempen = en;
			}
		}
		if(tempen != null && tempen.getName() != null)
			results.add(tempen);
		result.put("billTypes",results);
		return result;
	}
	/**
	 * 点击树节点的时候现实节点下所有的策略
	 */
	public Map getPutRackRules(Map param) {
		Map result = new HashMap();
		CustomEntity nodeObj = (CustomEntity)param.get("nodeObj");
		List<PutRackRule> rules = getRulesByObj(nodeObj);
		List<DisplayEntity> des = new ArrayList<DisplayEntity>();
		for(PutRackRule rule:rules){
			DisplayEntity de = new DisplayEntity();
			de.setId(rule.getId());
			de.setLeftDis(rule.toStringForDis(nodeObj));
			if(rule.getDefaultLocation()!=null)
				de.setDefaultLocation(rule.getDefaultLocation().getCode());
			if(rule.getPosition()!=null)
				de.setPosition(rule.getPosition().getName());
			if (!StringUtils.isEmpty(rule.getPutMethod())) {
				if(StringUtils.isEmpty(rule.getPutMethod())){
					de.setMothed("");
				}else{
					de.setMothed(LocalizedMessage.getLocalizedMessage("PutMethod."+rule.getPutMethod(),UserHolder.getReferenceModel(),UserHolder.getUser().getLocale().toString()));
				}
			}
			des.add(de);
		}
		result.put("result",des);
		return result;
	}
	
	private List<PutRackRule> getRulesByObj(CustomEntity nodeObj){
		Long id = WarehouseHolder.getWarehouse().getId();
		List<PutRackRule> rules = new ArrayList<PutRackRule>();
		if(nodeObj.getType()==1){//点击客户节点
			if(nodeObj.getId()==null){
				rules = this.commonDao.findByNamedQuery("getPutRackRuleForCompanyNull",
						new String[]{"warehouseId"},new Object[]{id});
			}else{
				rules = this.commonDao.findByNamedQuery("getPutRackRuleForCompany",
						new String[]{"warehouseId","companyId"},new Object[]{id,nodeObj.getId()});
			}
		}else{
			if(nodeObj.getId()==null){
				if(nodeObj.getCompanyId()==null){
					rules = this.commonDao.findByNamedQuery("getPutRackRuleForAllNull",
							new String[]{"warehouseId"},new Object[]{id});
				}else{
					rules = this.commonDao.findByNamedQuery("getPutRackRuleForBillTypeNull",
							new String[]{"warehouseId","companyId"},new Object[]{id,nodeObj.getCompanyId()});
				}
			}else{
				rules = this.commonDao.findByNamedQuery("getPutRackRuleForBillType",
						new String[]{"warehouseId","companyId","billTypeId"},
						new Object[]{id,nodeObj.getCompanyId(),nodeObj.getId()});
			}
		}
		return rules;
	}
	public void deletePutRackRule(Map params) {
		List<Long> ids = (List)params.get("ids");
		this.deletePutRackRule(ids);
	}

}
