package nc.pubimpl.baseapp.invoice;

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 org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bcmanage.bs.IBusiCenterManageService;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
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.pubitf.baseapp.image.ImageTMLogVO;
import nc.vo.pub.BusinessException;
import nc.wy.baseapp.log.ImageLogger;
/**
 * 发票状态更新接口
 * @author xuyong
 * @date 2021-07-14
 * 
 * */
public class InvoiceStatusModifyServlet 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 {
			if(!"1".equals(json.getString("code"))) {
				isTrue(true,"E0003", "接口调用失败:"+json.getString("message"));
//				throw new Exception("接口调用失败:"+json.getString("message"));
			}
			String invoiceNo =null;
//			String InvoiceType=null;
//			String InvoiceCode=null;
			String authStatus = null;
			JSONObject result = json.getJSONObject("result");
			invoiceNo = result.getString("invoiceNo");
//			InvoiceType=json.getString("InvoiceType");
//			InvoiceCode=json.getString("InvoiceCode");
			authStatus = result.getString("authStatus");
			isTrue(StringUtils.isBlank(invoiceNo), "E0001", "请求参数invoiceNo不能为空！");
			isTrue(StringUtils.isBlank(authStatus), "E0002", "请求参数authStatus不能为空！");
//			isTrue(StringUtils.isBlank(InvoiceCode), "E0003", "请求参数InvoiceCode不能为空！");
			String sql = "update er_erminvoice set defitem8 = '" + authStatus +
					"' where fphm = '"+ invoiceNo + "'";//pk_payablebill def1
			int count = getDao().executeUpdate(sql);
			isTrue(count <= 0,"E0005","找不到"+invoiceNo+"发票");
				
			
		} catch (Exception e) {
			ImageLogger.log("InvoiceStatusModifyServlet", "接口", 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);
			this.insertlog(json,statusJson);
			return statusJson;
		}
		JSONObject statusJson = new JSONObject();
		statusJson.put("requestTime", requestTime);
		statusJson.put("returnStatus", "S");
		statusJson.put("returnCode", "200");
		statusJson.put("returnMsg", "成功");
		statusJson.put("msg", "成功");
		this.insertlog(json,statusJson);
		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);
		JSONObject requestjson=null;
		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("请求参数不能为空！");
			}
			requestjson=JSONObject.parseObject(content.toString());
			return requestjson;
		} catch (Exception e) {
			ImageLogger.log("InvoiceStatusModifyServlet", "接口", e, "请求参数：" + content.toString());
			JSONObject statusJson = new JSONObject();
			statusJson.put("requestTime", requestTime);
			statusJson.put("returnStatus", "S");
			statusJson.put("returnCode", "E0006");
			statusJson.put("returnMsg", e.getMessage());
			statusJson.put("msg", ImageLogger.getStackTrace(e));
			this.insertlog(requestjson,statusJson);
			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", "InvoiceStatusModifyServlet-" + 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 insertlog(JSONObject requestjson,JSONObject responsejson) {
		String code = responsejson.getString("returnCode");
		ImageTMLogVO log = new ImageTMLogVO();
		log.setTm_content(JSONObject.toJSONString(requestjson));
		log.setTm_result(JSONObject.toJSONString(responsejson));
		log.setApicode("InvoiceStatusModifyServlet");
		if(!StringUtils.isBlank(code) && "200".equals(code)) {
			log.setTm_status("S");
		} else {
			log.setTm_status("F");
		}
		// 插入日志表
		try {
			getDao().insertVO(log);
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	private void initNCInvocationInfo() {
		IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
		try {
			InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		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);
		}
	}

}
