package nc.bs.uapbd.mdg.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.UUID;

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

import com.alibaba.fastjson.JSON;

import nc.bcmanage.bs.IBusiCenterManageService;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.comn.NetStreamContext;
import nc.bs.framework.core.util.ObjectCreator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.net.servlet.IReturnStatus;
import nc.net.servlet.SapToNcEsbJsonServlet;
import nc.pubimpl.sap.tm.SapTmImpl;
import nc.pubitf.para.SysInitQuery;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.BusinessException;
import uap.json.JSONObject;

public class SapTmReceiveBankAccServlet extends SapToNcEsbJsonServlet {

	@Override
	public void execFunction(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonobj = null;
		try {
			initInvocationInfo();
			jsonobj = findPostJsonValue(request);// 获取Post请求的值
			if (jsonobj == null || "".equals(jsonobj)) {// 无Post提交值
				ResultVO result = new ResultVO();
				result.setCode(IReturnStatus.FAILING);// 失败
				result.setMessage("Post所提交请求Json格式错误或者无值!");
				ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
				createResultEsbVO(esb);
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_FAILING);
				esb.getEsbInfo().setReturnMsg("失败");
				esb.setResultInfo(result);
				sendResponse(response, esb);
			} else {
				SapTmImpl sapTmImpl=(SapTmImpl) ObjectCreator.newInstance("nc.pubimpl.sap.tm.SapTmImpl");
				String jsondata =sapTmImpl.receiveBankAccInfo("d9c4ceac-c045-4570-bb48-96f958e2a16c", jsonobj.toString());
				ResultEsbVO<ResultVO> esb =JSON.parseObject(jsondata,ResultEsbVO.class);
				sendResponse(response, esb);
			}
		} catch (Exception e) {
			ResultVO result = new ResultVO();
			result.setCode(IReturnStatus.ERROR);// 异常
			result.setError(getExceptionDetail(e));
			ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();// 创建响应对象
			createResultEsbVO(esb);// 初始化响应对象
			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
			esb.getEsbInfo().setReturnMsg("异常");
			esb.setResultInfo(result);// 设置响应内容
			sendResponse(response, esb);
		}
	}
	
	/**
	 * 获得UUID值
	 */
	public static String getStringUUID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 发送响应信息
	 * 
	 * @param response
	 * @param esb
	 */
	public void sendResponse(final HttpServletResponse response, ResultEsbVO esb) {
//		String jsondata = net.sf.json.JSONObject.fromObject(esb).toString();
		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(jsondata);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 加载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() throws BusinessException {
		IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
		InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
		InvocationInfoProxy.getInstance().setGroupId(SysInitQuery.getParaString("GLOBLE00000000000000", "GROUP"));
		InvocationInfoProxy.getInstance().setUserId(SysInitQuery.getParaString("GLOBLE00000000000000", "ITFUSER"));
		ISecurityTokenCallback tc = NCLocator.getInstance().lookup(
				ISecurityTokenCallback.class);
		byte[] token = tc.token("__system".getBytes(), "NC".getBytes());
		NetStreamContext.setToken(token);
	}
}
