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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
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.LocationType;
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.EditLotInfoType;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.inventory.ItemKeyInventory;
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.inventory.InventoryManager;
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 QueryInvServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected static ApplicationContext ac;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryInvServlet() {
        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");
//		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));//post方式传递读取字符流
//		String jsonStr = null;
//		StringBuilder result = new StringBuilder();
//		try {
//			while ((jsonStr = reader.readLine()) != null) {
//				result.append(jsonStr);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		System.out.println("result:"+result.toString());
//		JSONObject json= JSONObject.fromObject(result.toString());
//		QueryAppManager app = (QueryAppManager) ac.getBean("queryAppManager");
//		String methodType =json.has("methodType")?json.getString("methodType"):""; 
////		Long workerId = app.convertLong(json.has("workerId")?json.getString("workerId"):"0");//App登录用户Id
////		Long wId = app.convertLong(json.has("wId")?json.getString("wId"):"0");//App登录仓库Id
////		String tz_inv_status=app.convertString(request.getHeader("tz_inv_status"));
////		String tz_reason=app.convertString(request.getHeader("tz_reason"));
////		Integer tz_qty=app.convertInteger(request.getHeader("tz_qty"));
////		Long item_id=app.convertLong(request.getHeader("item_id"));
////		Long pick_loc_id=app.convertLong(request.getHeader("pick_loc_id"));
////		Double ca_coefficient=app.convertDouble(request.getHeader("ca_coefficient"));
////		int suggest=app.convertInteger(request.getHeader("suggest"));;
////		int valid_period=app.convertInteger(request.getHeader("valid_period"));;
//		JSONObject resultJson = new JSONObject();
//		if("scanCodeInv".equals(methodType)){
//			String query_type =json.has("query_type")?json.getString("query_type"):""; //1库位查询，2货品查询
//			String code=json.has("code")?json.getString("code"):""; 
////			resultJson=app.scanItemCodeInv(commonDao, code,query_type);
//		}else if("scanDstLoc".equals(methodType)){
//			String dst_loc_code=json.has("dst_loc_code")?json.getString("dst_loc_code"):""; 
////			resultJson=app.scanLocationPick(commonDao, dst_loc_code, wId);
//		}else if("moveLocAll".equals(methodType)){
//			Long src_loc_id=json.getLong("loc_id"); 
//			Long dst_loc_id=json.getLong("dst_loc_id"); 
//			System.out.println(src_loc_id+"======"+dst_loc_id);
////			resultJson=this.moveLocAll(commonDao, src_loc_id,dst_loc_id, wId, workerId);
//		}else if("moveLocPart".equals(methodType)){
//			Long inv_id=json.getLong("inv_id"); 
//			double qty=json.getDouble("move_qty"); 
//			Long dst_loc_id=json.getLong("dst_loc_id"); 
//			System.out.println(inv_id+"======"+dst_loc_id+"===="+qty);
////			resultJson=this.moveLocPart(commonDao,dst_loc_id, inv_id,qty,wId, workerId);
//		}else if("adjustInvLot".equals(methodType)){
//			Long inv_id=json.getLong("inv_id"); 
//			String tz_pc1=json.has("pc1")?json.getString("pc1"):null; 
//			String tz_pd1=json.has("pd1")?json.getString("pd1"):null;
//			String tz_pd2=json.has("pd2")?json.getString("pd2"):null;
//			int tz_qty=json.getInt("move_qty"); 
//			resultJson=this.adjustInvLot(commonDao, inv_id, tz_pc1, tz_pd1, tz_pd2,tz_qty, wId, workerId);
//		}else if("adjustInvStatus".equals(methodType)){
//			Long inv_id=json.getLong("inv_id"); 
//			String tz_reason=json.has("tz_reason")?json.getString("tz_reason"):null; 
//			String tz_inv_status=json.has("status")?json.getString("status"):null; 
////			int tz_qty=json.getInt("move_qty"); 
//			resultJson=this.adjustInvStatus(commonDao, inv_id, tz_inv_status, tz_reason, wId, workerId);
//		}else if("adjustInvQty".equals(methodType)){
//			Long inv_id=json.getLong("inv_id"); 
//			int tz_qty=json.getInt("move_qty"); 
//			String tz_reason=json.has("tz_reason")?json.getString("tz_reason"):null; 
//			resultJson=this.adjustInvQty(commonDao, inv_id, tz_qty, tz_reason, wId, workerId);
//		}
////		else if("adjustItemInfo".equals(methodType)){
////			resultJson=this.adjustItemInfo(commonDao, item_id, ca_coefficient, pick_loc_id, suggest, valid_period);
////		}
//		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 moveLocAll(CommonDao commonDao,Long src_loc_id,Long dst_loc_id,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="移库成功";
		String data="";
		status="1";
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject moveLocPart(CommonDao commonDao,Long dst_loc_id,Long inv_id,double qty,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="移库成功";
		String data="";
		status="1";
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}

	public JSONObject adjustInvLot(CommonDao commonDao,Long inv_id,String tz_pc1,String tz_pd1,String tz_pd2,int tz_qty,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="修改成功";
		String data="";
		Inventory inv=commonDao.get(Inventory.class, inv_id);
		double ky_qty=0;
		Boolean temp=Boolean.FALSE;
		Date propD1=null;
		Date propD2=null;
		Long ik_id=null;
		if(inv==null){
			msg="该记录不存在,重新刷新";
		}else{
			ky_qty=inv.getQuantity()-inv.getQueuedQuantity();
			if(ky_qty<=0){
				msg="可用数量为0，不能修改";
			}else{
				Location loc=commonDao.get(Location.class, inv.getLocation().getId());
				if(loc.getType().equals(LocationType.SHIP)||loc.getType().equals(LocationType.RECEIVE)){
					msg="该库位类型，不能修改";
				}else{temp=Boolean.TRUE;
					ItemKeyInventory iki=commonDao.get(ItemKeyInventory.class,inv.getItemKeyInventory().getId());
					ik_id=iki.getItemKey().getId();
					if(tz_pd1!=null){
						propD1=DateUtil.formatStrToDateYMD(tz_pd1);
						ItemKey ik=commonDao.get(ItemKey.class, ik_id);
						Item item=commonDao.get(Item.class, ik.getItem().getId());
						Calendar cal = new GregorianCalendar();
						cal.setTime(propD1);
						cal.add(Calendar.DATE , item.getValidPeriod());	
						propD2=cal.getTime();
					}
				}
			}
		}
		if(temp){
			//判断是否发生变化，如果有变化则调整，无变化则不调整
			Worker worker=commonDao.load(Worker.class,workerId);
			WarehouseHolder.setWarehouse(commonDao.load(Warehouse.class, wId));
			User user=commonDao.load(User.class,worker.getUser().getId());
			UserHolder.setUser(user);
			InventoryManager inventoryManager = (InventoryManager) ac.getBean("inventoryManager");
			Date storageDate=inv.getStorageDate();
			inventoryManager.storeInventoryItemKey(inv, EditLotInfoType.BYINVENTORY, tz_qty+0d, ky_qty, ik_id, tz_pc1, propD1, propD2, storageDate);
			status="1";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject adjustInvStatus(CommonDao commonDao,Long inv_id,String tz_inv_status,String tz_reason,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="修改成功";
		String data="";
		Inventory inv=commonDao.get(Inventory.class, inv_id);
		double ky_qty=0;
		Boolean temp=Boolean.FALSE;
		if(inv==null){
			msg="该记录不存在,重新刷新";
		}else{
			ky_qty=inv.getQuantity()-inv.getQueuedQuantity();
			if(ky_qty<=0){
				msg="可用数量为0，不能修改";
			}else{
				Location loc=commonDao.get(Location.class, inv.getLocation().getId());
				if(loc.getType().equals(LocationType.SHIP)||loc.getType().equals(LocationType.RECEIVE)){
					msg="该库位类型，不能修改";
				}else{
					temp=Boolean.TRUE;
				}
			}
		}
		if(temp){
			Worker worker=commonDao.load(Worker.class,workerId);
			WarehouseHolder.setWarehouse(commonDao.load(Warehouse.class, wId));
			User user=commonDao.load(User.class,worker.getUser().getId());
			UserHolder.setUser(user);
			InventoryManager inventoryManager = (InventoryManager) ac.getBean("inventoryManager");
			List<Long> invIds=new ArrayList<Long>();
			invIds.add(inv_id);
			inventoryManager.editInventoryStatus(invIds, tz_inv_status);
			status="1";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject adjustInvQty(CommonDao commonDao,Long inv_id,int tz_qty,String tz_reason,Long wId,Long workerId){
		JSONObject resultJson = new JSONObject();
		String status="0";
		String msg="修改成功";
		String data="";
		Inventory inv=commonDao.get(Inventory.class, inv_id);
		double ky_qty=0;
		Boolean temp=Boolean.FALSE;
		if(inv==null){
			msg="该记录不存在,重新刷新";
		}else{
			ky_qty=inv.getQuantity()-inv.getQueuedQuantity();
			if(ky_qty<=0){
				msg="可用数量为0，不能修改";
			}else{
				Location loc=commonDao.get(Location.class, inv.getLocation().getId());
				if(loc.getType().equals(LocationType.SHIP)||loc.getType().equals(LocationType.RECEIVE)){
					msg="该库位类型，不能修改";
				}else{
					temp=Boolean.TRUE;
				}
			}
		}
		if(temp){
			Worker worker=commonDao.load(Worker.class,workerId);
			WarehouseHolder.setWarehouse(commonDao.load(Warehouse.class, wId));
			User user=commonDao.load(User.class,worker.getUser().getId());
			UserHolder.setUser(user);
			InventoryManager inventoryManager = (InventoryManager) ac.getBean("inventoryManager");
			List<Long> invIds=new ArrayList<Long>();
			invIds.add(inv_id);
			inventoryManager.modifyInventory(inv_id, tz_qty+0.0, tz_reason);
			status="1";
		}
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}
	
	public JSONObject adjustItemInfo(CommonDao commonDao,Long item_id,double ca_coefficient,Long pick_loc_id,int suggest,int valid_period){
		JSONObject resultJson = new JSONObject();
		String status="1";
		String msg="修改成功";
		String data="";
		Item item=commonDao.get(Item.class, item_id);
		item.setCAcoefficient(ca_coefficient);
		item.setSuggest(suggest);
		item.setValidPeriod(valid_period);
		Location loc=commonDao.get(Location.class, pick_loc_id);
		if(loc!=null){
			item.setLocation(loc);
		}
		commonDao.store(item);
		resultJson.put("status", status);
		resultJson.put("msg", msg);
		resultJson.put("data", data);
		return resultJson;
	}

}
