package nc.bs.tianwen.wuye;

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.JSONObject;

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.bs.uap.boss.process.BossWriteRecBIllInfo;
import nc.net.servlet.IReturnStatus;
import nc.net.servlet.SapToNcEsbJsonServlet;
import nc.pubitf.para.SysInitQuery;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.BusinessException;

/**
 * @Description: 应收单
 * 
 * @author 周蓝萍【碧桂园物业-天问接口】
 * @date 2019-04-12
 * @version with NC V6.3
 */
@SuppressWarnings("restriction")
public class TWRecBillServelet 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 {
				JSONObject requestInfo = jsonobj.getJSONObject("requestInfo");
				JSONObject head = requestInfo.getJSONObject("Header");
				if (head.containsKey("bossid")) {
					BossWriteRecBIllInfo bosspro=NCLocator.getInstance().lookup(BossWriteRecBIllInfo.class);
					String jsondata =bosspro.writeRecBillInfo(jsonobj);//boss系统分支
					sendResponse(response, jsondata);
					
				} else if (head.containsKey("ztId")) {
					BossWriteRecBIllInfo bosspro=NCLocator.getInstance().lookup(BossWriteRecBIllInfo.class);
					String jsondata =bosspro.writeRecBillInfo2(jsonobj);//中台系统分支
					sendResponse(response, jsondata);
					
				} else {
					String jsondata = WYTwxtUtil.getIWuYeTwxtBusiService().writeRecbillInfo(
							new uap.json.JSONObject(jsonobj.toString()));
					sendResponse(response, jsondata);
				}
			}
		} 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, String jsondata) {
		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 JSONObject.parseObject(sb.toString());
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void initInvocationInfo() throws BusinessException {
		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);
	}

}
