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

import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.PackageUnit;
import com.dev.swms.server.model.base.Store;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.ReceivedRecord;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.service.interfaceLog.QueryAppManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dev.energy.server.dao.CommonDao;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
public class DefaultQueryAppManager extends DefaultBaseManager implements QueryAppManager {

	@Override
	public JSONObject queryAsn(String parameter, String date, long workerId,
			long warehouseId, CommonDao commonDao) {
		JSONObject resultJson = new JSONObject();
		String status="0";
		String data="";
		String msg="";
		Session session = ((HibernateDaoSupport)this.commonDao).getSessionFactory().openSession();
		if(workerId>0){
			if(warehouseId>0){
				String sql=" select a.ID  as asnId,hz.name as client,a.code as code,bt.name as  billType,a.RELATED_BILL1 as relatedBill1,"
		       +" a.STATUS as status,DATE_FORMAT(a.ORDER_DATE,'%Y-%m-%d') as orderDate,a.EXPECTED_QUANTITY as qty,a.RECEIVED_QUANTITY as receiveQty,"
		       +" DATE_FORMAT(a.RECEIVED_DATE,'%Y-%m-%d') as receivedDate "
		       +" from ASN a "
		       +" left join STRUCTURE hz on hz.id=a.COMPANY_ID "
		       +" left join BILL_TYPE bt on bt.id=a.BILL_TYPE_ID "
		       +" where 1=1"
		       +" and a.EXPECTED_QUANTITY>a.RECEIVED_QUANTITY"
		       +" and a.WAREHOUSE_ID = "+warehouseId;
		       if(parameter!=null&&parameter.length()>0){
		    	   sql=sql+" and (a.RELATED_BILL1  like upper('%"+parameter+"%') or a.code like upper('%"+parameter+"%') )";
		       }
		       if(date!=null&&date.length()>0){
		    	   sql=sql+" and (DATE_FORMAT(a.ORDER_DATE,'%Y-%m-%d')='"+date+"'   )";
		       }
				sql=sql+" order by a.ID desc";
				Query   query   =   session.createSQLQuery(sql); 
				List<Object[]> list= (List<Object[]>)query.list();
				JSONArray  array = new JSONArray();
				JSONObject d = new JSONObject();
				JSONObject dd = new JSONObject();
				dd.put("xh","序号");
				dd.put("asnId","asnId");
				dd.put("client","货主");
				dd.put("code","ASN号");
				dd.put("relatedBill1","客户订单号");
				dd.put("billType","单据类型");
				dd.put("status","状态");
				dd.put("orderDate","订单日期");
				dd.put("qty","订单数量");
				dd.put("receiveQty","收货数量");
				dd.put("receivedDate","收货日期");
				array.add(dd);
				if(list.size()>0){
					int j=1;
					for(Object[] arrier:list){
						int i=0;
						d.put("xh",j++);
						d.put("asnId", arrier[i++]==null?"":arrier[i-1]);
						d.put("client", arrier[i++]==null?"":arrier[i-1]);
						d.put("code", arrier[i++]==null?"":arrier[i-1]);
						d.put("relatedBill1", arrier[i++]==null?"":arrier[i-1]);
						d.put("billType", arrier[i++]==null?"":arrier[i-1]);
						d.put("status", arrier[i++]==null?"":arrier[i-1]);
						d.put("orderDate", arrier[i++]==null?"":arrier[i-1]);
						d.put("qty", arrier[i++]==null?"":arrier[i-1]);
						d.put("receiveQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("receivedDate", arrier[i++]==null?"":arrier[i-1]);
						array.add(d);
					}
					status="1";
				}else{
					msg="无记录!";
				}
				data = array.toString();	
			}else{
				msg="仓库不存在!";
			}
		}else{
			msg="用户不存在!";
		}
			
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}

	@Override
	public JSONObject scanAsnCode(long asnId,String asn_code, Long workerId,
			long warehouseId, CommonDao commonDao) {
		JSONObject resultJson = new JSONObject();
		String status = "0";
		String msg = "";
		String data = "";
		JSONArray array = new JSONArray();
		if(asn_code!=null&&asn_code.length()>0){
			String hql = " from ASNDetail d where d.asn.id="+asnId+" ( d.item.code= '"
					+ asn_code.trim() + "') and d.expectedQuantity>d.receivedQuantity ";
			hql += " order by d.id desc ";
			List<ASNDetail> ds = commonDao.findByQuery(hql);
			if (ds.size() > 0) {
				ASNDetail d = ds.get(0); 
				JSONObject obj = new JSONObject();
				Item item = commonDao.get(Item.class, d.getItem().getId());
				PackageUnit pu =commonDao.get(PackageUnit.class, d.getPackageUnit().getId());
				String CAdesc="";
				if(item.getCAcoefficient()==0){
					CAdesc=d.getExpectedQuantity()%item.getCAcoefficient()+pu.getUnit();
				}else if(d.getExpectedQuantity()<item.getCAcoefficient()){
					CAdesc=(int)d.getExpectedQuantity()+pu.getUnit();
				}else if(d.getExpectedQuantity()%item.getCAcoefficient()==0){
					CAdesc=Math.floor(d.getExpectedQuantity()/item.getCAcoefficient())+item.getCAname();
				}else if(d.getExpectedQuantity()%item.getCAcoefficient()>0){
					CAdesc=Math.floor(d.getExpectedQuantity()/item.getCAcoefficient())+item.getCAname()+(int)d.getExpectedQuantity()%item.getCAcoefficient()+pu.getUnit();
				}
				obj.put("detail_id", d.getId());
				obj.put("item_code", item.getCode());// 条码
				obj.put("item_name", item.getName());
				obj.put("specs", item.getSpecs());
				obj.put("unit",pu.getUnit());
				obj.put("CAname", item.getCAname());
				obj.put("CAcoefficient",item.getCAcoefficient());
				obj.put("CAdesc", CAdesc);
				obj.put("qty", (int)d.getExpectedQuantity());//待收数量
				obj.put("receiveQty", (int)d.getReceivedQuantity());
				status = "1";
				array.add(obj);
				data = obj.toString();
			}else{
				msg = "无记录!";
			}
		}else{
			msg = "asn_code参数为空!";
		}
		
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}

	@Override
	public JSONObject scanAsnLoc(String loc_code, Long workerId,
			long warehouseId, CommonDao commonDao) {
		JSONObject resultJson = new JSONObject();
		String status="0"; 
		String msg="";
		String data="";
		String hql=" from Location loc where (loc.code='"+loc_code+"')";
		List<Location> list= commonDao.findByQuery(hql);
		if(list.size()>0){
			JSONObject obj = new JSONObject();
			Location l=list.get(0);
			obj.put("loc_id",l.getId());
			obj.put("loc_code",l.getName());
			status="1";
			data = obj.toString();
		}else{
			msg="库位不存在";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}

	@Override
	public JSONObject queryReceiveDetail(long asnId, long workerId,
			long warehouseId, CommonDao commonDao) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		JSONArray array = new JSONArray();
		JSONObject resultJson = new JSONObject();
		String status="0"; 
		String msg="";
		String data="";
		if(asnId>0){
			String hql=" from ReceivedRecord rr where rr.asn.id="+asnId+" ";
			List<ReceivedRecord> ReceivedRecords= commonDao.findByQuery(hql);
			if(ReceivedRecords.size()>0){
				JSONObject dd = new JSONObject();
				dd.put("loc_code", "库位");
				dd.put("item_code", "货品代码");
				dd.put("item_name", "货品名称");
				dd.put("specs", "货品规格");
				dd.put("CAdesc", "包装描述");
				dd.put("receiveQty", "收货数量");
				dd.put("propD1", "生产日期");
				dd.put("propD2", "到期日期");
				dd.put("workerName", "收货人");
				array.add(dd);
				for(ReceivedRecord rr : ReceivedRecords){
					Location loc =commonDao.load(Location.class, rr.getLocation().getId());
					ItemKey ik =commonDao.load(ItemKey.class, rr.getItemKey().getId());
					Item item=commonDao.load(Item.class, ik.getItem().getId());
					PackageUnit pu=commonDao.load(PackageUnit.class,rr.getPackageUnit().getId());
					Worker w=commonDao.load(Worker.class, workerId);
					JSONObject obj = new JSONObject();
					String CAdesc="";
					if(item.getCAcoefficient()==0){
						CAdesc=rr.getReceivedQuantity()%item.getCAcoefficient()+pu.getUnit();
					}else if(rr.getReceivedQuantity()<item.getCAcoefficient()){
						CAdesc=(int)rr.getReceivedQuantity()+pu.getUnit();
					}else if(rr.getReceivedQuantity()%item.getCAcoefficient()==0){
						CAdesc=Math.floor(rr.getReceivedQuantity()/item.getCAcoefficient())+item.getCAname();
					}else if(rr.getReceivedQuantity()%item.getCAcoefficient()>0){
						CAdesc=Math.floor(rr.getReceivedQuantity()/item.getCAcoefficient())+item.getCAname()+(int)rr.getReceivedQuantity()%item.getCAcoefficient()+pu.getUnit();
					}
					obj.put("loc_code",loc.getCode());
					obj.put("item_code",item.getCode());
					obj.put("item_name",item.getName());
					obj.put("specs",item.getSpecs());
					obj.put("CAdesc",CAdesc);
					obj.put("receiveQty",(int)rr.getReceivedQuantity());
					obj.put("propD1",sdf.format(ik.getLotInfo().getPropD1()));
					obj.put("propD2",sdf.format(ik.getLotInfo().getPropD2()));
					obj.put("workerName",w.getName());
					array.add(obj);
				}
				status="1";
				data = array.toString();
			}else{
				msg="无记录!";
			}
		}else{
			msg="asnId参数为空!";
		}
		
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	@Override
	public JSONObject queryCustomerNo(String relatedBill1, long workerId,
			long warehouseId, CommonDao commonDao) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		JSONObject resultJson = new JSONObject();
		JSONArray  array = new JSONArray();
		JSONObject obj = new JSONObject();
		JSONArray  array2 = new JSONArray();
		JSONObject obj2 = new JSONObject();
		String status="0"; 
		String msg="";
		String data="";
		if(relatedBill1!=null&&relatedBill1.length()>0){
			String hql=" from ASN a where upper(a.relatedBill1) like '%"+relatedBill1+"%' ";
			ASN asn=null;
			List<ASN> ASNs= commonDao.findByQuery(hql);
			if(ASNs.size()>0){
				asn=ASNs.get(0);
				obj.put("code", asn.getCode());
				obj.put("relatedBill1", asn.getRelatedBill1());
				obj.put("orderDate",sdf.format(asn.getOrderDate()));
				array.add(obj);
				List<ReceivedRecord> ReceivedRecords =  commonDao.findByQuery(" from ReceivedRecord rr where rr.asn.id=:id and rr.beMoved = false ",
				new String[] { "id"},new Object[] {asn.getId()});
				if(ReceivedRecords.size()>0){
					JSONObject obj3 = new JSONObject();
					obj3.put("rrId", "序号");
					obj3.put("item_code", "货品代码");
					obj3.put("loc_Code", "库位");
					obj3.put("propD1", "生产日期");
					obj3.put("propD2", "到期日期");
					obj3.put("receiveQty", "数量");
					array2.add(obj3);
					for(ReceivedRecord rr:ReceivedRecords){
						Location loc =commonDao.load(Location.class, rr.getLocation().getId());
						ItemKey ik =commonDao.load(ItemKey.class, rr.getItemKey().getId());
						Item item=commonDao.load(Item.class, ik.getItem().getId());
						obj2.put("rrId",rr.getId());
						obj2.put("loc_code",loc.getCode());
						obj2.put("item_code",item.getCode());
						obj2.put("propD1",sdf.format(ik.getLotInfo().getPropD1()));
						obj2.put("propD2",sdf.format(ik.getLotInfo().getPropD2()));
						obj2.put("receiveQty",rr.getReceivedQuantity());
						array2.add(obj2);
						status="1";
						data = array2.toString();
					}
				}else{
					msg="无记录!";
				}
			}else{
				msg="无记录!";
			}
		}else{
			msg="parameter参数错误或为空!";
		}
		Map<String, Object> pm=new LinkedHashMap<String,Object>(0);
		pm.put("data1",array);
		pm.put("data2",array2);
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", pm);
		return resultJson;
	}
	
		
	public JSONObject getMbDetails(CommonDao commonDao,Long mb_id){
		JSONObject resultJson = new JSONObject();
		String status="1";
		String msg="";
		String data="";
		JSONArray  array = new JSONArray();
		List<PickTicket> pts=commonDao.findByQuery("from PickTicket pt where pt.masterBOL.id="+mb_id+" order by pt.sequenceNo asc");
		for(PickTicket pt:pts){
			JSONObject obj = new JSONObject();
			obj.put("pick_code",pt.getCode());
			String md_code="";
			if(pt.getStore()!=null){
				Store st=commonDao.get(Store.class, pt.getStore().getId());
				md_code=st.getCode();
			}
			obj.put("md_code", md_code);
			obj.put("sequence_no",pt.getSequenceNo());
			obj.put("quantity",pt.getOrderQuantity());
			obj.put("is_zc",pt.getPrintCount()==0?"否":"是");
			array.add(obj);
		}
		data=array.toString();
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	@Override
	public JSONObject queryPick(String parameter, String date, long workerId,
			long warehouseId, CommonDao commonDao) {
		JSONObject resultJson = new JSONObject();
		String status="0";
		String data="";
		String msg="";
		Session session = ((HibernateDaoSupport)this.commonDao).getSessionFactory().openSession();
		if(workerId>0){
			if(warehouseId>0){
				String sql=" select pt.ID  as pickId,hz.name as client,pt.code as code,bt.name as  billType,pt.RELATED_BILL1 as relatedBill1,"
		       +" pt.STATUS as status,DATE_FORMAT(pt.ORDER_DATE,'%Y-%m-%d') as orderDate,pt.ORDER_QUANTITY as orderQty,pt.PRE_ALLOCATED_QTY as preQty,"
		       +" pt.ALLOCATED_QUANTITY as allocatQty,pt.PICKED_QUANTITY as pickQty,pt.SHIPPED_QUANTITY as shipQty,DATE_FORMAT(pt.SHIP_DATE,'%Y-%m-%d') as shipDate "
		       +" from PICK_TICKET pt "
		       +" left join STRUCTURE hz on hz.id=pt.COMPANY_ID "
		       +" left join BILL_TYPE bt on bt.id=pt.BILL_TYPE_ID "
		       +" where 1=1"
		       +" and pt.ORDER_QUANTITY>pt.SHIPPED_QUANTITY"
		       +" and pt.WAREHOUSE_ID = "+warehouseId;
		       if(parameter!=null&&parameter.length()>0){
		    	   sql=sql+" and (pt.RELATED_BILL1  like upper('%"+parameter+"%') or pt.code like upper('%"+parameter+"%') )";
		       }
		       if(date!=null&&date.length()>0){
		    	   sql=sql+" and (DATE_FORMAT(pt.ORDER_DATE,'%Y-%m-%d')='"+date+"'   )";
		       }
				sql=sql+" order by pt.ID desc";
				Query   query   =   session.createSQLQuery(sql); 
				List<Object[]> list= (List<Object[]>)query.list();
				JSONArray  array = new JSONArray();
				JSONObject d = new JSONObject();
				JSONObject dd = new JSONObject();
				dd.put("xh","序号");
				dd.put("pickId","ID");
				dd.put("client","货主");
				dd.put("code","发货单号");
				dd.put("relatedBill1","客户订单号");
				dd.put("billType","单据类型");
				dd.put("status","状态");
				dd.put("orderDate","订单日期");
				dd.put("orderQty","订单数量");
				dd.put("preQty","预分配数量");
				dd.put("allocatQty","分配数量");
				dd.put("pickQty","拣货数量");
				dd.put("shipQty","发运数量");
				dd.put("shipDate","发货日期");
				array.add(dd);
				if(list.size()>0){
					int j=1;
					for(Object[] arrier:list){
						int i=0;
						d.put("xh",j++);
						d.put("pickId", arrier[i++]==null?"":arrier[i-1]);
						d.put("client", arrier[i++]==null?"":arrier[i-1]);
						d.put("code", arrier[i++]==null?"":arrier[i-1]);
						d.put("relatedBill1", arrier[i++]==null?"":arrier[i-1]);
						d.put("billType", arrier[i++]==null?"":arrier[i-1]);
						d.put("status", arrier[i++]==null?"":arrier[i-1]);
						d.put("orderDate", arrier[i++]==null?"":arrier[i-1]);
						d.put("orderQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("preQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("allocatQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("pickQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("shipQty", arrier[i++]==null?"":arrier[i-1]);
						d.put("shipDate", arrier[i++]==null?"":arrier[i-1]);
						array.add(d);
					}
					status="1";
				}else{
					msg="无记录!";
				}
				data = array.toString();	
			}else{
				msg="仓库不存在!";
			}
		}else{
			msg="用户不存在!";
		}
			
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}


	
	
}
