package nc.pubitf.payablebill.yx;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import nc.bs.dao.BaseDAO;
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.wy.baseapp.log.ImageLogger;
import nc.wy.baseapp.utils.PropertiesUtil;

public class PubJHAPIServlet implements IHttpServletAdaptor {

	private static String returnStatus;

	private static String returnCode;

	private static String returnMsg;

	private BaseDAO dao = null;

	public BaseDAO getDao() {
		if (dao == null) {
			dao = new BaseDAO();
		}
		return dao;
	}

	public void doAction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		if ("GET".equalsIgnoreCase(request.getMethod())) {
			// 初始化环境变量
			initNCInvocationInfo();
			processGet(request, response);
		} else {
			// 初始化环境变量
			initNCInvocationInfo();
			// 获取参数
			JSONObject jsonParam = getParam(request, response);
			// 执行业务逻辑
			if (jsonParam != null) {
				JSONObject statusJson = process(jsonParam);
				sendResponse(response, statusJson);
			}
		}

	}

	private JSONObject process(JSONObject json) {
		// TODO Auto-generated method stub
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String requestTime = dateFormat.format(date);

		try {
			String billCode = json.getString("billCode");
			String auditStatus = json.getString("auditStatus");
			String auditRemark = json.getString("auditRemark");
			isTrue(StringUtils.isBlank(billCode), "E0001", "请求参数billCode不能为空！");
			isTrue(StringUtils.isBlank(auditStatus), "E0002", "请求参数auditStatus不能为空！");
			String sql = "update ap_payablebill set def74 = '" + auditStatus + "' , def75 = '" + requestTime
					+ "' where def1 = '" + billCode + "' or pk_payablebill ='" + billCode + "'" ;
			int count = getDao().executeUpdate(sql);  //应付单
			sql = "update ap_paybill set def74 = '" + auditStatus + "' , def75 = '" + requestTime
					+ "' where def1 = '" + billCode + "' or pk_paybill ='" + billCode + "'";
			int count2 = getDao().executeUpdate(sql); //付款单
			sql = "update er_bxzb set zyx71 = '" + auditStatus + "' ,zyx72 ='" + requestTime 
					+ "' where pk_jkbx = '" + billCode + "'";
			int count3 = getDao().executeUpdate(sql); //报销单
			sql = "update er_jkzb set zyx71 = '" + auditStatus + "' ,zyx72 ='" + requestTime 
					+ "' where pk_jkbx = '" + billCode + "'";
			int count5 = getDao().executeUpdate(sql); //借款单
			sql = "update er_mtapp_bill set defitem36 = ' " + auditStatus + "' ,defitem37 ='" + requestTime 
					+ "' where pk_mtapp_bill = '" + billCode + "'";
			int count4 = getDao().executeUpdate(sql); //申请单
			isTrue(count <= 0 && count2 <=0 && count3 <=0 && count4 <=0 && count5 <=0,"E0003","找不到对应单据");
				
		} catch (Exception e) {
			ImageLogger.log("PubJHAPIServlet", "接口", e, returnMsg);
			JSONObject statusJson = new JSONObject();
			statusJson.put("requestTime", requestTime);
			statusJson.put("returnStatus", returnStatus);
			statusJson.put("returnCode", returnCode);
			statusJson.put("returnMsg", returnMsg);
			statusJson.put("msg", returnMsg);
			return statusJson;
		}
		JSONObject statusJson = new JSONObject();
		statusJson.put("requestTime", requestTime);
		statusJson.put("returnStatus", "S");
		statusJson.put("returnCode", "200");
		statusJson.put("returnMsg", "成功");
		statusJson.put("msg", "成功");
		return statusJson;
	}

	private JSONObject getParam(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		StringBuilder content = new StringBuilder();
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		String requestTime = dateFormat.format(date);
		try {
			ServletInputStream ris = request.getInputStream();
			byte[] b = new byte[1024];
			int lens = -1;
			while ((lens = ris.read(b)) > 0) {
				content.append(new String(b, 0, lens, "UTF-8"));
			}
			if (StringUtils.isBlank(content.toString())) {
				throw new Exception("请求参数不能为空！");
			}
			return JSONObject.parseObject(content.toString());
		} catch (Exception e) {
			ImageLogger.log("PubJHAPIServlet", "接口", e, "请求参数：" + content.toString());
			JSONObject statusJson = new JSONObject();
			statusJson.put("requestTime", requestTime);
			statusJson.put("returnStatus", "S");
			statusJson.put("returnCode", "200");
			statusJson.put("returnMsg", e.getMessage());
			statusJson.put("msg", ImageLogger.getStackTrace(e));
			sendResponse(response, statusJson);

		} finally {
		}
		return null;
	}

	private void processGet(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
	}

	private void sendResponse(HttpServletResponse response, JSONObject statusJson) {
		String requestTime = statusJson.getString("requestTime");
		String returnStatus = statusJson.getString("returnStatus");
		String returnCode = statusJson.getString("returnCode");
		String returnMsg = statusJson.getString("returnMsg");
		String msg = statusJson.getString("msg");

		Date date = new Date();
		String instId = date.getTime() + "";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		String responseTime = dateFormat.format(date);
		com.alibaba.fastjson.JSONObject esbInfo = new com.alibaba.fastjson.JSONObject();

		esbInfo.put("code", returnCode);
		esbInfo.put("message", returnMsg);

		com.alibaba.fastjson.JSONObject resultInfo = new com.alibaba.fastjson.JSONObject();
		resultInfo.put("instId", "PubJHAPIServlet-" + instId);
		resultInfo.put("requestTime", requestTime);
		resultInfo.put("returnStatus", returnStatus);
		resultInfo.put("responseTime", responseTime);
		esbInfo.put("data", resultInfo);

		this.sendResponse(response, esbInfo.toString());
	}

	private void sendResponse(HttpServletResponse response, String statusJson) {
		PrintWriter out = null;
		try {
			// 跨域请求，*代表允许全部类型
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
			out.write(statusJson);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	private void initNCInvocationInfo() {
		InvocationInfoProxy.getInstance().setGroupId("0001H810000000000HS2");//集团pk
		InvocationInfoProxy.getInstance().setUserId("1001H8100000022DN5C0");//管理员pk
		ISecurityTokenCallback tc = NCLocator.getInstance().lookup(ISecurityTokenCallback.class);
		byte[] token = tc.token("__system".getBytes(), "NC".getBytes());
		NetStreamContext.setToken(token);
	}
	/**
	 * 判断返回值是否为true
	 * 
	 * @param flag
	 * @param msg
	 * @throws Exception
	 */
	public static void isTrue(boolean flag, String code, String msg) throws Exception {
		// 如果为True，则抛出异常
		if (flag) {
			returnStatus = "E";
			returnCode = code;
			returnMsg = msg;
			throw new Exception(msg);
		}
	}

}
