package nc.net.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.comn.NetStreamContext;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.itf.pu.invoke.IMatrialFp;
import nc.itf.ws.esb.IEsbDAO;
import nc.pub.sap.constant.SapConstants;
import nc.vo.esb.EsbInfoVO;
import nc.vo.esb.EsbVO;
import nc.vo.esb.QueryInfoVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.ws.esb.CertificateVO;
import nc.vo.ws.esb.EsbinfoVO;
import uap.json.JSONObject;

/**
 *      物料分配功能
 * @author 邝鹏飞 2021-05-12
 *
 */
public class WlfpServlet implements IHttpServletAdaptor {
	
	/**
	 * 交互时间精确到毫秒
	 */
	public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	
	private static IEsbDAO service;
	
	
	private String beginDateStr;
	
	@Override
	public void doAction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		beginDateStr=dateFormat.format(Calendar.getInstance().getTime());//请求处理开始时间
		initInvocationInfo();
		execFunction(request,response);		
	}
	
		
	/**
	 * 发送响应信息
	 * @param response
	 * @param esb
	 */
	public void sendResponse(final HttpServletResponse response,String esb){
		//String jsondata=com.alibaba.fastjson.JSONObject.toJSONString(esb);
		PrintWriter out=null;
		try {
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
	        out.write(esb);
	        out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
	
	/**
	 * ESB 逻辑处理接口
	 * @return
	 */
	private static IEsbDAO getService(){
    	if(service==null)
    		service=NCLocator.getInstance().lookup(IEsbDAO.class);
    	return service;
	}
	
	/**
	 * 创建ESB交互对象
	 * @param newi
	 * @param esb 交互VO
	 * @return newi=0(请求对象)
	 */
	public void createEsbVO(final EsbVO esb){
		EsbInfoVO esbInfo=new EsbInfoVO();
		QueryInfoVO queryInfo=new QueryInfoVO();
		Date date=Calendar.getInstance().getTime();//获取当前时间
		//设置请求时间
		esbInfo.setRequestTime(dateFormat.format(date));
		esbInfo.setInstId(getStringUUID());//使用UUID作为流水号
		esb.setEsbInfo(esbInfo);
		esb.setQueryInfo(queryInfo);
	}
	/**
	 * 生成ESB响应对象
	 * @param esb
	 */
	public void createResultEsbVO(final ResultEsbVO esb){
		EsbInfoVO esbInfo=new EsbInfoVO();
		QueryInfoVO queryInfo=new QueryInfoVO();
		Date date=Calendar.getInstance().getTime();//获取当前时间
		//设置响应时间
		esbInfo.setInstId(getStringUUID());//使用UUID作为流水号
		esbInfo.setRequestTime(getBeginDateStr());//设置请求开始时间
		esbInfo.setResponseTime(dateFormat.format(date));//设置响应时间
		esbInfo.setReturnStatus(IReturnStatus.ESB_SUCCEED);//默认响应成功
		esbInfo.setReturnCode(IReturnStatus.ESB_SUCCEED_CODE);//默认成功code
		esbInfo.setReturnMsg("成功");//默认响应成功提示
		esb.setEsbInfo(esbInfo);
		esb.setQueryInfo(queryInfo);
	}
	
	/**
	 * 获得UUID值
	 */
	public static String getStringUUID(){
		return UUID.randomUUID().toString();
	}
	
	/**
	 * @param e	异常
	 * return 异常详细信息
	 */
	public String getExceptionDetail(Exception e) {  
		if(e==null)
			return null;
        StringBuffer stringBuffer = new StringBuffer(e.toString() + "\n");  
        if(e.getStackTrace()==null || e.getStackTrace().length==0)
        	return stringBuffer.toString();  
        StackTraceElement[] messages = e.getStackTrace();  
        int length = messages.length;  
        for (int i = 0; i < length; i++) {
            stringBuffer.append("\t"+messages[i].toString()+"\n");  
        }  
        return stringBuffer.toString();  
    }
	
	/**
	 * 请求处理开始时间
	 * @return
	 */
	public String getBeginDateStr(){
		return beginDateStr;
	}
	
	
	/**
	 * 业务逻辑执行函数
	 * @param request
	 * @param response
	 */
	public  void execFunction(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObj = null;
		try {
			jsonObj = findPostJsonValue(request);
			String materials = (String)jsonObj.get("materials");
			String targetId = (String)jsonObj.get("targetId");
			
			//String[] materialsArr = materials.split(",");
			String[] targetIdArr = targetId.split(",");
			
			String[] materialsArr = new String[1];
			materialsArr[0] = materials;
			
			IMatrialFp bgyToService = NCLocator.getInstance().lookup(IMatrialFp.class);
			bgyToService.invokeassignMaterialByPks(materialsArr, targetIdArr);
			
			sendResponse(response, "{\"result\":\"分配成功\"}");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			String msg = "分配失败："+e.getMessage();
			sendResponse(response, "{\"result\":"+msg+"}");
		}
	}

	/**
	 * 加载Post提交上来的Json参数
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	private JSONObject findPostJsonValue(final HttpServletRequest request) throws Exception{
		BufferedReader br=null;
		try {
			br= new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String temp=null;
			while ((temp = br.readLine())!= null) {
				sb.append(temp);
			}
			return new JSONObject(sb.toString());
		} catch (Exception e) {
			throw e;
		}finally{
			try {
				if(br!=null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private void initInvocationInfo() {
		InvocationInfoProxy.getInstance().setUserDataSource("design");
		InvocationInfoProxy.getInstance().setGroupId(SapConstants.GROUPID);
		InvocationInfoProxy.getInstance().setUserId(
				SapConstants.NCADMIN_CUSERID);
		ISecurityTokenCallback tc = NCLocator.getInstance().lookup(
				ISecurityTokenCallback.class);
		byte[] token = tc.token("__system".getBytes(), "NC".getBytes());
		NetStreamContext.setToken(token);
	}
}
