package com.dev.swms.server.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dev.energy.server.dao.CommonDao;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.model.security.User;
import com.dev.energy.server.web.security.UserHolder;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.Line;
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.Structure;
import com.dev.swms.server.model.base.TurnOverMode;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.inventory.TaskLog;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.MoveDocDetail;
import com.dev.swms.server.model.rules.WorkModel;
import com.dev.swms.server.model.shipping.MasterBOL;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.model.shipping.PickTicketStatus;
import com.dev.swms.server.model.shipping.WaveDoc;
import com.dev.swms.server.model.shipping.WaveDocDetail;
import com.dev.swms.server.model.shipping.WaveDocStatus;
import com.dev.swms.server.service.interfaceLog.QueryAppManager;
import com.dev.swms.server.service.picking.MasterBolManager;
import com.dev.swms.server.service.receiving.ASNManager;
import com.dev.swms.server.service.receiving.MoveDocManager;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.shipping.PickTicketManager;
import com.dev.swms.server.service.task.AllocateManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.sun.org.apache.bcel.internal.generic.AALOAD;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.security.krb5.Asn1Exception;

/**
 * Servlet implementation class LoginAppServlet
 */
public class MasterBolServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MasterBolServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init(ServletConfig sc) throws ServletException {
		super.init(sc);
		ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc.getServletContext());
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("==========app装车========"+new Date());
		CommonDao commonDao = (CommonDao) ac.getBean("commonDao");
		request.setCharacterEncoding("utf-8");
		Enumeration enu=request.getHeaderNames(); 
		while(enu.hasMoreElements()){  
		String paraName=(String)enu.nextElement();  
			System.out.println(paraName+": "+request.getHeader(paraName));  
		}
		QueryAppManager app = (QueryAppManager) ac.getBean("queryAppManager");
		String methodType = URLDecoder.decode(request.getHeader("method_type"),"UTF-8");//方法名
		Long workerId = Long.parseLong(URLDecoder.decode(request.getHeader("workerId")==null?"0":request.getHeader("workerId"),"UTF-8"));;
		String mb_code=request.getHeader("mb_code");
		Long mb_id = Long.parseLong(URLDecoder.decode(request.getHeader("mb_id")==null?"0":request.getHeader("mb_id"),"UTF-8"));;
		int lp_count = Integer.parseInt(URLDecoder.decode(request.getHeader("lp_count")==null?"0":request.getHeader("lp_count"),"UTF-8"));;
		Long pick_id = Long.parseLong(URLDecoder.decode(request.getHeader("pick_id")==null?"0":request.getHeader("pick_id"),"UTF-8"));;
		String pick_code=request.getHeader("pick_code");
		Long wId = Long.parseLong(URLDecoder.decode(request.getHeader("wId")==null?"0":request.getHeader("wId"),"UTF-8"));//App登录仓库Id
		JSONObject resultJson = new JSONObject();
		if("scanMbCode".equals(methodType)){
			resultJson=this.scanMbCode(commonDao, mb_code, wId, workerId);
		}else if("getMbDetails".equals(methodType)){
			//resultJson=app.getMbDetails(commonDao, mb_id);
		}else if("scanMbPickCode".equals(methodType)){
			resultJson=this.scanMbPickCode(commonDao, mb_id, pick_code, wId, workerId);
		}else if("mbConfirm".equals(methodType)){
			resultJson=this.mbConfirm(commonDao, mb_id, pick_id, workerId, wId);
		}else if("shipConfirm".equals(methodType)){
			resultJson=this.shipConfirm(commonDao, mb_id, lp_count, workerId, wId);
		}
		System.out.println("======"+resultJson.toString());
		PrintWriter out = null;
		try {
			response.setContentType(resultJson.toString());
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.print(resultJson.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}	
	}
	
	public JSONObject scanMbCode(CommonDao commonDao,String mb_code,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		String hql="select pt.masterBOL.id from PickTicket pt where pt.masterBOL.id is not null and pt.shippedQuantity<pt.pickedQuantity and pt.masterBOL.status!='SHIP_ALL'";
		if(mb_code!=null&&!mb_code.equals("")){
			hql+=" and pt.masterBOL.code='"+mb_code+"'";
		}
		String query=hql+" and pt.masterBOL.worker1.id="+workerId;
		List<Long> ids=commonDao.findByQuery(query);
		if(ids.size()<=0){
			ids=commonDao.findByQuery(hql);
		}
		if(ids.size()>0){
			MasterBOL mb=commonDao.get(MasterBOL.class, ids.get(0));
			MasterBolManager mbManager = (MasterBolManager) ac.getBean("masterBolManager");
			mbManager.refreshMasterBOL(mb.getId());
			JSONObject obj = new JSONObject();
			status="1";
			obj.put("mb_id", mb.getId());
			obj.put("mb_code", mb.getCode());
			String line_name="";
			if(mb.getLine()!=null){
				Line line=commonDao.get(Line.class, mb.getLine().getId());
				line_name=line.getLineName();
			}
			obj.put("line_name", line_name);
			obj.put("driver_name", mb.getPilotName());
			List<PickTicket> zc_qty=commonDao.findByQuery("from PickTicket pt where pt.masterBOL.id="+mb.getId());
			List<PickTicket> un_zc_qty=commonDao.findByQuery("from PickTicket pt where pt.masterBOL.id="+mb.getId()+" and pt.printCount>0");
			obj.put("pt_count", un_zc_qty.size()+"/"+zc_qty.size());
			data=obj.toString();
			Worker wk=commonDao.get(Worker.class, workerId);
			mb.setWorker1(wk);
			commonDao.store(wk);
		}else{
			if(mb_code!=null&&!mb_code.equals("")){
				msg="单号【"+mb_code+"】没有待装车数据";
			}else{
				msg="没有待装车数据";
			}
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject scanMbPickCode(CommonDao commonDao,Long mb_id,String pick_code,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		JSONArray  array = new JSONArray();
		String status="0";
		String msg="";
		String data="";
		String hql="from PickTicket pt where pt.masterBOL.id="+mb_id;
		hql+=" and (pt.code='"+pick_code+"' or pt.relatedBill1='"+pick_code+"')";
		List<PickTicket> pts=commonDao.findByQuery(hql);
		if(pts.size()>0){
			PickTicket pt=pts.get(0);
			JSONObject obj = new JSONObject();
			obj.put("pick_id", pt.getId());
			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("cus_code", pt.getRelatedBill1()==null?"":pt.getRelatedBill1());
			obj.put("md_code", md_code);
			List<PickTicketDetail> ptds=commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId()+" order by d.item.id desc");
			for(PickTicketDetail ptd:ptds){
				JSONObject objd = new JSONObject();
				Item item=commonDao.get(Item.class, ptd.getItem().getId());
				objd.put("item_code", item.getCode());
				objd.put("item_name", item.getName());
				objd.put("pick_info", (int)ptd.getPickedQuantity()+"/"+(int)ptd.getOrderQuantity());
				array.add(objd.toString());
			}
			status="1";
			obj.put("pick_details", array.toString());
			data=obj.toString();
			MasterBolManager mbManager = (MasterBolManager) ac.getBean("masterBolManager");
			mbManager.refreshMasterBOL(mb_id);
		}else{
			msg="单号【"+pick_code+"】不存在该装车单中";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject mbConfirm(CommonDao commonDao,Long mb_id,Long pick_id,Long workerId,Long wId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		PickTicket pt=commonDao.load(PickTicket.class,pick_id);
		if(pt.getPickedQuantity()<pt.getOrderQuantity()){
			msg=pt.getCode()+"未拣货完成，不能装车";
		}else{
			status="1";
			msg="装车成功";
			pt.setPrintCount(1);
			commonDao.store(pt);
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject shipConfirm(CommonDao commonDao,Long mb_id,int lp_count,Long workerId,Long wId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		MasterBOL mb=commonDao.load(MasterBOL.class,mb_id);
		if(mb.getPickQuantity()<mb.getOrderQuantity()){
			msg=mb.getCode()+"未拣货完成，不能发运";
		}else{
			WarehouseHolder.setWarehouse(commonDao.load(Warehouse.class, wId));
			Worker worker=commonDao.load(Worker.class,workerId);
			User user=commonDao.load(User.class,worker.getUser().getId());
			UserHolder.setUser(user);
			MasterBolManager mbManager = (MasterBolManager) ac.getBean("masterBolManager");
			List<Long> ids=new ArrayList<Long>();
			ids.add(mb_id);
			mbManager.multiShipConfirm(ids);
			status="1";
			msg="发运成功";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	

}
