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.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
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.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.pub.sap.constant.SapConstants;
import nc.pubimpl.erm.expenseaccount.InsertLog_RequiresNewImpl;
import nc.pubitf.para.SysInitQuery;
import nc.vo.erm.bgyimageconfig.BgyimageconfigVO;
import nc.vo.erm.image.ImageTMLogVO;
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 appcode = request.getParameter("appcode");//"20080PBM408";
		String Oids = request.getParameter("Oids");//"1001H8100000000DU0K2";
		
		try {
			Thread.sleep(3 * 1000);
		} catch (InterruptedException e2) {
		}
		
		try {
			initInvocationInfo();
			// TODO Auto-generated method stub
			// 获取请求参数,
			//URLhttp://127.0.0.1/service/~erm/nc.impl.erm.servlet.bgywy.NccToImage?appcode=20080EBM410&Oids=1001H9100000000A34KT
			BgyimageconfigVO imconfig = new BgyimageconfigVO();
			try {
				//通过表erm_bgyimageconfig，查询出打印相关参数
				//参数可以通过跟踪产品打印输出的代码获取，先录日志，再出打印按钮类，例如：nccloud.web.arap.arappub.action.PrintOutPutAction
				imconfig = queryImageConfig(appcode);
			} catch (BusinessException e1) {
				// TODO Auto-generated catch block
				ExceptionUtils.wrapBusinessException(e1.getMessage());
			}
			//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();
			PrintInfo IcPrintinfo = 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);
				  };
			if (PrintServiceModule.equals("ic")) {
					IcPrintinfo.setAppcode(appcode);
					IcPrintinfo.setIds(new String[] { Oids });
					IcPrintinfo.setNodeKey("print");
					NCClass printServiceClazz = new NCClass();
					printServiceClazz.setModule(PrintServiceModule);
					printServiceClazz.setName(PrintServiceName);
					IcPrintinfo.setPrintServiceClazz(printServiceClazz);
					IcPrintinfo.setPrintTemplateID(PrintTemplateID);
					//IcPrintinfo.setNodeKey(NodeKey);   
					printEntry.exportPdf(getPrintService(IcPrintinfo).getDataSources(IcPrintinfo), 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();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			try {
				String a   =getExceptionDetail(e);
				JSONObject err = new JSONObject();
				err.put("err", a);
				insertImageLog(Oids, appcode, null,  err, "IMAGE_NCCFM_VIEW");
			} catch (BusinessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	//登陆信息
	private void initInvocationInfo() {
		try {
			IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
			String[] datasources=busiCenterManageService.getAvailableBusiCenterDsNames();
			//由于UAT环境与生产的数据源不一致
			String ds="NCCDATA";//生产环境数据源:NCCDATA
			for (int i = 0; i < datasources.length; i++) {
				if (datasources[i].equals("NCCDATA"))
				{
					ds="NCCDATA";
					break;
				}
					else
						ds="ncclcdata";//连测环境数据源:ncclcdata
			}
			InvocationInfoProxy.getInstance().setUserDataSource(ds);
			//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);
//			InvocationInfoProxy.getInstance().setGroupId(_prop.getProperty("pkGroup"));
//			InvocationInfoProxy.getInstance().setUserId(_prop.getProperty("userId"));
			InvocationInfoProxy.getInstance().setGroupId("0001H810000000000HS2");
			InvocationInfoProxy.getInstance().setUserId("NC_USER0000000000000");
			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
			ExceptionUtils.wrapBusinessException(e.getMessage());
		}
	}

	/**
	 * 获取打印服务    
	 * @param info
	 * @return
	 */
	private AbstractPrintService getPrintService(IPrintInfo info) {
		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 {
			ExceptionUtils.wrapBusinessException("找不到打印服务！");
		}

		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();  
    }
	
	public void insertImageLog(String billid, String billcode, JSONObject send, JSONObject result, String urlcode) throws BusinessException {
		String code = result.getString("code");
		ImageTMLogVO log = new ImageTMLogVO();
		log.setBillid(billid);
		log.setBillno(billcode);
		log.setTm_content(JSONObject.toJSONString(send));
		log.setTm_result(JSONObject.toJSONString(result));
		log.setApicode(urlcode);
		if(!StringUtils.isBlank(code) && "200".equals(code)) {
			log.setTm_status("S");
		} else {
			log.setTm_status("F");
		}
		// 插入日志表
		new BaseDAO().insertVO(log);
	}
}
