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.Location;
import com.dev.swms.server.model.base.PackageUnit;
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.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.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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.security.krb5.Asn1Exception;

/**
 * Servlet implementation class LoginAppServlet
 */
public class WaveDocServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WaveDocServlet() {
        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 {
		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));  
		}
		System.out.println("==========app补货========"+new Date());
		QueryAppManager app = (QueryAppManager) ac.getBean("queryAppManager");
		String methodType = URLDecoder.decode(request.getHeader("method_type"),"UTF-8");//方法名
//		Long workerId = app.convertLong(request.getHeader("workerId"));
//		Long task_id = app.convertLong(request.getHeader("task_id"));
//		int move_qty = app.convertInteger(request.getHeader("move_qty"));
//		Long item_id=app.convertLong(request.getHeader("item_id"));
//		String item_code=app.convertString(request.getHeader("item_code"));
//		Long wId = Long.parseLong(URLDecoder.decode(request.getHeader("wId")==null?"1":request.getHeader("wId"),"UTF-8"));//App登录仓库Id
		JSONObject resultJson = new JSONObject();
//		if("scanItemCodeBh".equals(methodType)){
//			resultJson=app.scanItemCodeBh(commonDao, workerId, item_code);
//		}else if("createWaveDoc".equals(methodType)){
//			resultJson=this.createWaveDoc(commonDao, item_id, move_qty, wId, workerId);
//		}else if("getWaveDocTask".equals(methodType)){
//			resultJson=this.getWaveDocTask(commonDao, workerId, wId);
//		}else if("scanTaskItemCode".equals(methodType)){
//			resultJson=app.scanTaskItemCode(commonDao, task_id, item_code, workerId);
//		}else if("pickConfirm".equals(methodType)){
//			resultJson=this.pickConfirm(commonDao, task_id, move_qty, wId, workerId);
//		}
		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 pickConfirm(CommonDao commonDao,Long task_id,int move_qty,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		Task t=commonDao.get(Task.class, task_id);
		if(t.getPlanQuantity()-t.getMovedQuantityMU()>=move_qty){
			PickTicketManager ptManager = (PickTicketManager) ac.getBean("pickTicketManager");
			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);
			ptManager.pickConfirm(task_id, move_qty, workerId);
			status="1";
			msg="拣货成功";
		}else{
			msg="拣货数量不正确";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject createWaveDoc(CommonDao commonDao,Long item_id,int move_qty,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		Item item=commonDao.get(Item.class, item_id);
		BussinessCodeManager bm = (BussinessCodeManager) ac.getBean("swmsBussinessCodeManager");
		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);
		WaveDoc waveDoc=EntityFactory.getEntity(WaveDoc.class);
		waveDoc.setCode(bm.generateDayCode("BC", 3));
		waveDoc.setStatus(WaveDocStatus.OPEN);
		waveDoc.setWorkModel(WorkModel.PICK_ITEM_MODEL);
		waveDoc.setStartDate(new Date());
		waveDoc.setTurnOverMode(TurnOverMode.FIFO_VALIDDATE);
		waveDoc.setUserTracking();
		waveDoc.setCreateDate(new Date());
		waveDoc.setCompany(commonDao.get(Structure.class, item.getCompany().getId()));
		waveDoc.setWarehouse(WarehouseHolder.getWarehouse());
		waveDoc.setOrderQuantity(move_qty);
		waveDoc.setQuantity(move_qty);
		commonDao.store(waveDoc);
		WaveDocDetail wdd=EntityFactory.getEntity(WaveDocDetail.class);
		wdd.setItem(item);
		wdd.setOrderQuantity(move_qty);
		wdd.setOrderQtyOfMasterUnit(move_qty);
		wdd.setCaCoefficient(item.getCAcoefficient()==null?0:item.getCAcoefficient());
		wdd.setLocType(null);
		wdd.setNewLotInfo(null);
		List<PackageUnit> units=commonDao.findByQuery("from PackageUnit unit where unit.item.id="+item.getId());
		wdd.setPackageUnit(units.get(0));
		wdd.setPlanBhQty(move_qty);
		wdd.setQuantity(move_qty);
		wdd.setWaveDoc(waveDoc);
		commonDao.store(wdd);
		status="1";
		msg="创建成功";
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject getWaveDocTask(CommonDao commonDao,Long workerId,Long wId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="";
		String data="";
		Worker worker=commonDao.load(Worker.class,workerId);
		List<WaveDoc> wds=commonDao.findByQuery("from WaveDoc w where w.workModel='PICK_ITEM_MODEL' and w.orderQuantity>w.pickedQuantity");
		if(wds.size()>0){
			WaveDoc doc=wds.get(0);
			if(doc.getAllocatedQuantity()<doc.getOrderQuantity()){
				List<Long> waveDocIds=new ArrayList<Long>();
				waveDocIds.add(wds.get(0).getId());
				WarehouseHolder.setWarehouse(commonDao.load(Warehouse.class, wId));
				User user=commonDao.load(User.class,worker.getUser().getId());
				UserHolder.setUser(user);
				AllocateManager allocateManager = (AllocateManager) ac.getBean("allocateManager");
				allocateManager.waveAllocate(waveDocIds);
			}
			List<WaveDocDetail> wdds=commonDao.findByQuery("from WaveDocDetail d where d.waveDoc.id="+wds.get(0).getId());
			if(wdds.size()>0){
				List<Task> ts =commonDao.findByQuery("from Task t where t.waveDocDetail.id="+wdds.get(0).getId()+" and t.movedQuantityMU<t.planQuantityMU  and t.planQuantityMU>0");
				if(ts.size()>0){
					JSONObject obj = new JSONObject();
					Task t=ts.get(0);
					QueryAppManager app = (QueryAppManager) ac.getBean("queryAppManager");
					HashMap<String, Object> map=null;//app.getTaskMap(t);
					obj.put("task_id", map.get("task_id"));
					obj.put("src_lp_code", map.get("src_lp"));
					obj.put("src_loc_code",map.get("src_loc"));
					obj.put("ca_coefficient", map.get("ca_coefficient"));
					obj.put("item_name", map.get("item_name"));
					obj.put("prc_info", map.get("prc_info"));
					obj.put("bar_code", map.get("item_code"));
					obj.put("un_info", map.get("un_info"));
					status="1";
					data=obj.toString();
					t.setWorker1(worker);
					commonDao.store(t);
				}
			}
			
		}else{
			msg="无任务单号";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	

}
