package nc.impl.erm.servlet.bgywy;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.Properties;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.owasp.esapi.ESAPI;

import com.alibaba.fastjson.JSONObject;

import nc.bcmanage.bs.IBusiCenterManageService;
import nc.pubitf.erm.expenseaccount.IinsertLog_RequiresNew;
import nc.bs.arap.api.psapitool.WuYePSApiUtil;
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.itf.uap.print.IPrintEntry;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.net.servlet.IReturnStatus;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.para.SysInitQuery;
import nc.vo.erm.bgyimageconfig.BgyimageconfigVO;
import nc.vo.esb.EsbInfoVO;
import nc.vo.esb.QueryInfoVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.BusinessException;
import nccloud.base.reflect.NCClass;
import nccloud.dto.arap.arappub.PrintDataInfo;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.pubitf.platform.print.AbstractPrintService;
import nccloud.pubitf.platform.print.IPrintInfo;
import nccloud.pubitf.platform.print.vo.PrintInfo;
import nccloud.vo.platform.print.LightPrintTemplateHelper;

/**
 * @Description: 【NCC->影像系统】单据封面回传
 * 
 * @author 熊国文
 * @date 2021-04-28
 * @version with NCC
 */

public class NccToImage implements IHttpServletAdaptor {
	 private static Properties _prop = new Properties();

	@Override
	public void doAction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String rsdata = null;
		ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
		ResultVO result = new ResultVO();
		result.setResult("");
		esb.setResultInfo(result);
		
		String appcode = request.getParameter("appcode");//"20080PBM408";
		String Oids = request.getParameter("Oids");//"1001H8100000000DU0K2";
		try {
			// TODO Auto-generated method stub
			// 获取请求参数,
			//URLhttp://127.0.0.1/service/~erm/nc.impl.erm.servlet.bgywy.NccToImage?appcode=20080EBM410&Oids=1001H9100000000A34KT
			initInvocationInfo();
			BgyimageconfigVO imconfig = new BgyimageconfigVO();
			try {
				//通过表erm_bgyimageconfig，查询出打印相关参数
				//参数可以通过跟踪产品打印输出的代码获取，先录日志，再出打印按钮类，例如：nccloud.web.arap.arappub.action.PrintOutPutAction
				imconfig = queryImageConfig(appcode);
			} catch (BusinessException e1) {
				// TODO Auto-generated catch block
				throw new BusinessException(e1.getMessage());
			}
			if(null==imconfig)
					throw new BusinessException("未能根据appcode找到对应的打印模板，请检查erm_bgyimageconfig表");
			//String Nodekey = imconfig.getTranstype(); // 交易类型，"F1-Cxx-W04";// request.getParameter("Nodekey");
			String PrintServiceModule = imconfig.getModule();// 模块名，"arap";// request.getParameter("PrintServiceModule");
			String PrintServiceName = imconfig.getServicename();// 打印服务类全路径"nccloud.pubimpl.arap.arappub.ArapPrintService";															
			String PrintTemplateID = imconfig.getPrinttemplateid();// 打印模板PK
			String BillType = imconfig.getBilltype();// 单扰类型"F1";
			String NodeKey = imconfig.getVdef2();// 打印模板节点号;
			PrintDataInfo ArApPrintinfo = new PrintDataInfo();
			PrintInfo ErmPrintinfo = new PrintInfo();
			PrintInfo PuPrintinfo = new PrintInfo();
			ByteArrayOutputStream print = new ByteArrayOutputStream();
			IPrintEntry printEntry = LightPrintTemplateHelper.getPrintEntry();		
			if (PrintServiceModule.equals("arap")) {
				ArApPrintinfo.setAppcode(appcode);
				ArApPrintinfo.setIds(new String[] { Oids });
				ArApPrintinfo.setNodeKey(NodeKey);
				NCClass printServiceClazz = new NCClass();
				printServiceClazz.setModule(PrintServiceModule);
				printServiceClazz.setName(PrintServiceName);
				ArApPrintinfo.setPrintServiceClazz(printServiceClazz);
				ArApPrintinfo.setPrintTemplateID(PrintTemplateID);
				ArApPrintinfo.setBillType(BillType);
				ArApPrintinfo.setFuncode(appcode);
				printEntry.exportPdf(getPrintService(ArApPrintinfo).getDataSources(ArApPrintinfo), PrintTemplateID, print);
			};
			if (PrintServiceModule.equals("erm")) {
				ErmPrintinfo.setAppcode(appcode);
				ErmPrintinfo.setIds(new String[] { Oids });
				ErmPrintinfo.setNodeKey(NodeKey);
				NCClass printServiceClazz = new NCClass();
				printServiceClazz.setModule(PrintServiceModule);
				printServiceClazz.setName(PrintServiceName);
				ErmPrintinfo.setPrintServiceClazz(printServiceClazz);
				ErmPrintinfo.setPrintTemplateID(PrintTemplateID);
				ErmPrintinfo.setNodeKey(NodeKey);			
				printEntry.exportPdf(getPrintService(ErmPrintinfo).getDataSources(ErmPrintinfo), PrintTemplateID, print);
			};
			if (PrintServiceModule.equals("pu")) {
				   PuPrintinfo.setAppcode(appcode);
				   PuPrintinfo.setIds(new String[] { Oids });
				   PuPrintinfo.setNodeKey(NodeKey);
				   NCClass printServiceClazz = new NCClass();
				   printServiceClazz.setModule(PrintServiceModule);
				   printServiceClazz.setName(PrintServiceName);
				   PuPrintinfo.setPrintServiceClazz(printServiceClazz);
				   PuPrintinfo.setPrintTemplateID(PrintTemplateID);
				   PuPrintinfo.setNodeKey(NodeKey);   
				   printEntry.exportPdf(getPrintService(PuPrintinfo).getDataSources(PuPrintinfo), PrintTemplateID, print);
				  };
			// 下载输出
			
			
			InputStream in = new ByteArrayInputStream(print.toByteArray());
			PrintWriter out = null;
			try {
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/pdf");
				// 输入流，获得文件的字节流
				byte[] bytes = new byte[in.available()];
				in.read(bytes);
				// 将字节流写入response中
				response.getOutputStream().write(bytes);
				in.close();
				response.flushBuffer();
				response.getOutputStream().flush();
			} catch (Exception e) {
				ExceptionUtils.wrapBusinessException(e.getMessage());
			} finally {
				if (out != null) {
					out.close();
				}
			}
			
			result.setCode(IReturnStatus.SUCCEED);// 成功
			result.setMessage("打开成功");
			createResultEsbVO(esb);
			esb.setResultInfo(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
	
			
			try {
				String err = getExceptionDetail(e);
				
				JSONObject errjson = new JSONObject();
				errjson.put("err", err);
				result.setCode(IReturnStatus.ERROR);// 异常
				result.setError(errjson.toString());
				result.setMessage(result.getError());
				createResultEsbVO(esb);// 初始化响应对象
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
				esb.getEsbInfo().setReturnMsg("异常");
				esb.setResultInfo(result);// 设置响应内容
				NCLocator.getInstance().lookup(IinsertLog_RequiresNew.class).insertImageLog_RequiresNew(Oids, appcode, null,  errjson, "IMAGE_NCCFM_VIEW");
			
			} catch (BusinessException e1) {
				// TODO Auto-generated catch block
				JSONObject errjson = new JSONObject();
				errjson.put("err", e1);
				result.setCode(IReturnStatus.ERROR);// 异常
				result.setError(errjson.toString());
				result.setMessage(result.getError());
				createResultEsbVO(esb);// 初始化响应对象
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
				esb.getEsbInfo().setReturnMsg("异常");
				esb.setResultInfo(result);// 设置响应内容
			}
		}finally {
			rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);
			sendResponse(response, rsdata);
		}
	}
	//登陆信息
	private void initInvocationInfo() throws BusinessException {
		try {
			//InvocationInfoProxy.getInstance().setGroupId(SysInitQuery.getParaString("GLOBLE00000000000000", "GROUP"));
			//InvocationInfoProxy.getInstance().setUserId(SysInitQuery.getParaString("GLOBLE00000000000000", "ITFUSER"));
			 InputStream in = NccToImage.class.getResourceAsStream("login_message.properties");
	         BufferedReader bf = new BufferedReader(new InputStreamReader(in));
	         _prop.load(bf);
	         //IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
//	        InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
	        InvocationInfoProxy.getInstance().setUserDataSource( _prop.getProperty("userDataSource") );	
	        InvocationInfoProxy.getInstance().setGroupId(_prop.getProperty("pkGroup"));
			InvocationInfoProxy.getInstance().setUserId(_prop.getProperty("userId"));
			ISecurityTokenCallback tc = NCLocator.getInstance().lookup(ISecurityTokenCallback.class);
			byte[] token = tc.token("__system".getBytes(), "NC".getBytes());
			NetStreamContext.setToken(token);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new BusinessException(e.getMessage());
			
		}
	}

	/**
	 * 获取打印服务    
	 * @param info
	 * @return
	 * @throws BusinessException 
	 */
	private AbstractPrintService getPrintService(IPrintInfo info) throws BusinessException {
		Object instance = null;
		try {
			Class<?> clazz = info.getPrintServiceClazz().load();
			instance = clazz.newInstance();

		} catch (Exception var4) {
			ExceptionUtils.wrapException(var4);
		}
		AbstractPrintService service = null;
		if (instance instanceof AbstractPrintService) {
			service = (AbstractPrintService) instance;

		} else {
			throw new BusinessException("找不到打印服务！");
		}

		return service;
	}

	public static BgyimageconfigVO queryImageConfig(String appcode) throws BusinessException {
		BgyimageconfigVO imageconfig = new BgyimageconfigVO();
		StringBuilder querySQL = new StringBuilder("select ");
		querySQL.append(" * ");
		querySQL.append(" from ");
		querySQL.append(" erm_bgyimageconfig ");
		querySQL.append(" where appcode='");
		querySQL.append(appcode);
		querySQL.append("'");
		imageconfig = (BgyimageconfigVO) new BaseDAO().executeQuery(querySQL.toString(),
				new BeanProcessor(BgyimageconfigVO.class));
		return imageconfig;
	}
	
	
	/**
	 * add by longht 
	 * @param e	异常
	 * return 异常详细信息
	 */
	public static 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();  
    }
	
	
	/**
	 * 生成ESB响应对象
	 * @param esb
	 */
	public static void createResultEsbVO(ResultEsbVO esb){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		EsbInfoVO esbInfo=new EsbInfoVO();
		QueryInfoVO queryInfo=new QueryInfoVO();
		Date date=Calendar.getInstance().getTime();//获取当前时间
		//设置响应时间
		esbInfo.setInstId(UUID.randomUUID().toString());//使用UUID作为流水号
		esbInfo.setRequestTime(dateFormat.format(Calendar.getInstance().getTime()));//设置请求开始时间
		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);
	}
	
	

	/**
	 * 发送响应信息
	 * @param response
	 * @param esb
	 */
	private 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();
			}
		}
	}
}
