package com.kingdee.eas.gyt;

import org.apache.log4j.Logger;
import javax.ejb.*;
import java.rmi.RemoteException;
import com.kingdee.bos.*;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.rule.RuleExecutor;
import com.kingdee.bos.metadata.MetaDataPK;
//import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.framework.ejb.AbstractEntityControllerBean;
import com.kingdee.bos.framework.ejb.AbstractBizControllerBean;
//import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.service.ServiceContext;
import com.kingdee.bos.service.IServiceContext;

import com.kingdee.eas.common.EASBizException;


import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.bsf.service.classloader.MsfClassLoaderFactory;
import com.kingdee.bos.ctrl.bizshare.ConnectException;
import com.kingdee.bos.ctrl.kdf.data.impl.BOSQueryDelegate;
import com.kingdee.bos.ctrl.print.common.provider.DefaultPrintDataProvider;
import com.kingdee.bos.ctrl.report.forapp.kdnote.client.DefaultNoteDataProvider;
import com.kingdee.bos.ctrl.report.forapp.kdnote.client.KDNoteHelper;
import com.kingdee.bos.ctrl.report.forapp.kdnote.webserver.IContextProvider;
import com.kingdee.bos.ctrl.report.forapp.kdnote.webserver.KDNoteWebServerHelper;
import com.kingdee.bos.ctrl.reportone.kdrs.biz.IBizContext;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.dao.query.QueryExecutorFactory;
import com.kingdee.bos.util.EASResource;
import com.kingdee.eas.basedata.assistant.AbstractPrintIntegrationInfo;
import com.kingdee.eas.basedata.assistant.IPrintIntegration;
import com.kingdee.eas.basedata.assistant.PrintIntegrationFactory;
import com.kingdee.eas.basedata.assistant.util.CommonPrintIntegrationDataProvider;
import com.kingdee.eas.basedata.assistant.util.MultiDataSourceDataProviderProxy;
import com.kingdee.eas.basedata.assistant.util.PrintIntegrationManager;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.context.WebContextUtil;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.log.IOperateLogService;
import com.kingdee.shr.base.syssetting.log.OperateLogManager;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.shr.base.syssetting.util.SHRCheck;
import com.kingdee.shr.base.syssetting.web.controller.ReportTemplateController;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.base.syssetting.web.util.UserUtil;
import com.kingdee.shr.component.report.CommonDataProvider;
import com.kingdee.shr.component.report.ICommonDataProvider;
import com.kingdee.shr.recuritment.InterviewPlanCollection;
import com.kingdee.shr.recuritment.InterviewPlanFactory;
import com.kingdee.shr.recuritment.InterviewPlanInfo;
import com.kingdee.shr.recuritment.osf.interviewGo.GetVideoInterviewServiceOSF;
import com.kingdee.util.Uuid;
import org.springframework.ui.ModelMap;
import org.springframework.validation.support.BindingAwareModelMap;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;














public class GetJobFacadeControllerBean extends AbstractGetJobFacadeControllerBean
{
    private static Logger logger =
        Logger.getLogger("com.kingdee.eas.gyt.GetJobFacadeControllerBean");
    public static String RPT_CTX = "shr_rpt_ctx";
    public static String PDF = "PDF";
    public static String NODE_SERVER = "shr_node_Server";
    private static Pattern PATTERN = Pattern.compile("(\r\n|\r|\n|\n\r|>|<|'|\"|;|,|\\(|\\)|\\{|\\})");

    
    
    @Override
    public void getJobRegistration(Context ctx) throws BOSException, EASBizException {
    	super.getJobRegistration(ctx);
    	
    	process1(ctx,new HashMap());
    	
    }
    
    
    
    public Object process1(Context context, Map<String, Object> param) {
        HashMap<String, Object> result = new HashMap<String, Object>();
//        context= SHRContext.getInstance().getContext();
        try {
//            String recordId = (String)param.get("recordId"); //ÃæÊÔ°²ÅÅid
//            logger.error("GetJobRegistrationPackagerecordId-----------------" + recordId);
//            InterviewPlanCollection interviewPlanCollection = InterviewPlanFactory.getLocalInstance(context).getInterviewPlanCollection("where interview = '" + recordId + "'");
//            if (interviewPlanCollection == null){
//
//            }
//            InterviewPlanInfo interviewPlanInfo = interviewPlanCollection.get(0);
//            String billID = interviewPlanInfo.getInterview().getId().toString();
            logger.error("GetJobRegistrationPackagebillID-----------------");

//            SHRContext instance = SHRContext.getInstance();
//            instance.setContext(context);
//            ServletRequest request = instance.getRequest();
//            ServletResponse response = instance.getResponse();
            BindingAwareModelMap modelMap = new BindingAwareModelMap();

            param.put("dataProvider","com.kingdee.shr.recuritment.util.InterviewResultPrintHelpDataProvider");
            param.put("billID","Tnk32W2mTPibC2qoL3n3iglDARo=");
            param.put("tdQueryPK","");
            param.put("tdTemplateName","/s-HR/Recuritment/InterviewResult");
            param.put("method","report");
            param.put("tdRptTemplate","RecRegisterTem.r1-print");
            param.put("tdTemplatePath","%2Fs-HR%2FRecuritment%2FInterviewResult");
            param.put("uipk","com.kingdee.shr.recuritment.interview");
            param.put("serviceId","X8LdsTb7TCGpfR/aas8MGfI9KRA=");
//            param.put("","");
//            param.put("","");
//            param.put("","");
//            request.setAttribute("dataProvider","com.kingdee.shr.recuritment.util.InterviewResultPrintHelpDataProvider");
//            //request.setAttribute("billID",billID);
//            request.setAttribute("billID","Tnk32W2mTPibC2qoL3n3iglDARo=");
//            request.setAttribute("tdQueryPK","");
//            request.setAttribute("tdTemplateName","/s-HR/Recuritment/InterviewResult");
//            request.setAttribute("method","report");
//            request.setAttribute("tdRptTemplate","RecRegisterTem.r1-print");
//            request.setAttribute("tdTemplatePath","%2Fs-HR%2FRecuritment%2FInterviewResult");
//            request.setAttribute("uipk","com.kingdee.shr.recuritment.interview");
//            request.setAttribute("serviceId","X8LdsTb7TCGpfR/aas8MGfI9KRA=");

            reportPackage(param,modelMap,context);

            result.put("msg", "cs");
            result.put("msgType", "1");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", e.getMessage());
            result.put("msgType", "0");
        }

        return result;
    }
    public String reportPackage(Map<String, Object> param, ModelMap modelMap,Context context) throws SHRWebException, ShrWebBizException {
        String tdTemplatePath = (String) param.get("tdTemplatePath");
        String tdRptTemplate = (String) param.get("tdRptTemplate");

//        String tdTemplatePath = (String)request.getAttribute("tdTemplatePath");
//        String tdRptTemplate = (String)request.getAttribute("tdRptTemplate");
        String templatePath = tdTemplatePath + "/" + tdRptTemplate;
//        Context ctx = SHRContext.getInstance().getContext();
//        IOperateLogService service = null;

//        try {
//            service = OperateLogManager.getIOperateLogService(ctx, OperateLogManager.getPrintLogConfigBean(ctx));
//            if (null != service) {
//                service.preLogHandle(request);
//            }
//        } catch (Exception var12) {
//            var12.printStackTrace();
//        }

        try {
            Object dataProvider = this.getDataProvider(param, modelMap,context);
            exportPackage(param, modelMap, templatePath, dataProvider, "PDF",context);
        } catch (Exception var11) {
            var11.printStackTrace();
            throw new SHRWebException(var11);
        }

//        try {
//            if (null != service) {
//                service.postLogHandle(request);
//            }
//        } catch (Exception var10) {
//            var10.printStackTrace();
//        }

        return null;
    }

    public Object getDataProvider(Map<String, Object> param, ModelMap modelMap,Context ctx) throws BOSException {
        Object data = null;
        String tdRptTemplate = (String)param.get("tdRptTemplate");
        String tdQueryPK = (String)param.get("tdQueryPK");
        List idList = new ArrayList();
        String isSelectedAllStr = (String)param.get("isSelectedAll");
        String queryUuidStr = (String)param.get("queryUuid");
        String billID = (String)param.get("billID");
        String dataProvider = (String)param.get("dataProvider");
        boolean isSelectedAll = isSelectedAllStr != null && isSelectedAllStr.equalsIgnoreCase("true");
        int i;
        if (isSelectedAll) {
            IQueryExecutor exec = QueryExecutorFactory.getLocalInstance(ctx, MetaDataPK.create(tdQueryPK));
            idList = exec.getBillIDList(Uuid.read(queryUuidStr), "id", 0, 0);
        } else {
            String[] billIDs = billID.split(",");
            String[] var15 = billIDs;
            int var16 = billIDs.length;

            for(i = 0; i < var16; ++i) {
                String s = var15[i];
                ((List)idList).add(s);
            }
        }

//        KDNoteWebServerHelper webServerHelper = (KDNoteWebServerHelper)SHRContext.getSessionContext().get("node_Server");
//        if (webServerHelper == null) {
//            if (logger.isInfoEnabled()) {
//                logger.info("WAF Debug for Dynform framework ,webServerHelper get is null from Session by key node_Server,then ");
//            }
//
//            IBizContext bizContext = getBizContext();
//            if (bizContext != null) {
//                webServerHelper = (KDNoteWebServerHelper)SHRContext.getSessionContext().get("node_Server");
//            } else {
//                JSONUtils.ERROR("bizContext is empty !");
//            }
//        }

        IMetaDataPK tdQuery = null;
        if (tdQueryPK != null) {
            tdQuery = MetaDataPK.create(tdQueryPK);
        }

        if (!com.kingdee.util.StringUtils.isEmpty(dataProvider)) {
            if ("com.kingdee.bos.ctrl.print.common.provider.DefaultPrintDataProvider".equals(dataProvider)) {
                data = new DefaultPrintDataProvider(ctx, (List)idList, tdQuery);
            } else if ("com.kingdee.bos.ctrl.report.forapp.kdnote.client.DefaultNoteDataProvider".equals(dataProvider)) {
                data = new DefaultNoteDataProvider(ctx, (List)idList, tdQuery);
            } else {
                try {
                    Constructor<?>[] ctor = MsfClassLoaderFactory.forName(dataProvider).getDeclaredConstructors();
                    logger.debug("-------start--------dataprovider is " + dataProvider);
                    i = 0;

                    for(int total = ctor.length; i < total; ++i) {
                        Class[] cl = ctor[i].getParameterTypes();
                        if (cl.length == 1) {
                            data = MsfClassLoaderFactory.forName(dataProvider).getConstructor(cl).newInstance(billID);
                        } else if (cl.length == 2) {
                            data = MsfClassLoaderFactory.forName(dataProvider).getConstructor(cl).newInstance(billID, tdQueryPK);
                            break;
                        }
                    }

                    logger.debug("------end---------dataprovider is " + dataProvider);
                } catch (Exception var21) {
                    logger.error(var21.getMessage(), var21);
                }

                if (data == null) {
                    try {
                        data = Class.forName(dataProvider).newInstance();
                    } catch (Exception var20) {
                        var20.printStackTrace();
                    }
                }
            }
        } else {
            data = new DefaultNoteDataProvider(ctx, (List)idList, tdQuery);
        }

        if (null == data) {
            data = new CommonDataProvider((List)idList, tdQuery);
        }

        if (data instanceof ICommonDataProvider) {
            ((ICommonDataProvider)data).setContext(ctx);
        }

        data = this.printTimesControl( data, (List)idList, tdRptTemplate,ctx);
        return data;
    }

    public static void exportPackage(Map<String, Object> param, ModelMap modelMap, String templatePath, Object dataProvider, String type,Context context) throws IOException, SHRWebException {
        if (templatePath != null) {
            try {
                templatePath = URLDecoder.decode(templatePath, "UTF-8");
            } catch (UnsupportedEncodingException var15) {
                logger.error("decode url error when export. the url is :" + SHRCheck.vaildLog(templatePath));
            }

            logger.info("Note output PDF start..." + SHRCheck.vaildLog(templatePath));
            KDNoteWebServerHelper webServerHelper = new KDNoteWebServerHelper();
//            KDNoteWebServerHelper webServerHelper = (KDNoteWebServerHelper)SHRContext.getSessionContext().get(NODE_SERVER);
//            if (webServerHelper == null) {
//                if (logger.isInfoEnabled()) {
//                    logger.info("WAF Debug for Dynform framework ,webServerHelper get is null from Session by key shr_node_Server,then ");
//                }
//                IBizContext bizContext = getBizContext();
//                if (bizContext != null) {
//                    webServerHelper = (KDNoteWebServerHelper)SHRContext.getSessionContext().get(NODE_SERVER);
//                } else {
//                    JSONUtils.ERROR(MessageFormat.format(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "is_empty"), "bizContext"));
//                }
//            }
//
//            if (webServerHelper == null) {
//                JSONUtils.ERROR("cann't find context server!");
//            }

            String fname = templatePath.toString();
            fname = fname.substring(fname.lastIndexOf("/") + 1) + ".pdf";
//            response.setHeader("Content-Disposition", SHRCheck.checkFileNameForSetResponseHeader("inline; filename=\"" + URLEncoder.encode(fname, "UTF-8") + "\""));
//            if (PDF.equals(type)) {
//                response.setContentType("application/pdf");
//            }

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            try {
                //out = response.getOutputStream();
                if (webServerHelper != null) {
                    webServerHelper.setContextProvider(new IContextProvider() {
                        @Override
                        public IBizContext getBizContext(Context context1) {
                            try {
                                IBizContext ctx =  KDNoteHelper.makeContext(context);
                                return ctx;
                            } catch (ConnectException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    webServerHelper.setBosContext(context);
                    webServerHelper.exportPDF(templatePath, dataProvider, out);
                }
                //wKiDDCaiZyrsBbDblnsoeEtIrOcDCDXNad6mzSYvjFQZLSjJ7DNG-IiT3NrjmhFm  RecRegisterPersonBaseQuery

                String tempFilePath = "E:\\kdshr90\\eas\\server\\deploy\\easweb.ear\\shr_web.war\\tmp/wKiDDCaiZyrsBbDblnsoeEtIrOcDCDXNad6mzSYvjFQZLSjJ7DNG-IiT3NrjmhFm";
//                HttpSession session = request.getSession();
//                String tempFilePath = UserUtil.getUserTempDirAbsolutePath(session); //´æ·Å
                File tempFile = new File(tempFilePath);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                logger.error("GetJobRegistrationPackagetempFilePath-----------------" + tempFilePath);
                File outFile = new File(tempFilePath + "/outA.pdf");
                FileOutputStream fos = new FileOutputStream(outFile);
                out.writeTo(fos);
                fos.close();
            } catch (Exception var14) {
                logger.error("export pdf error:", var14);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }

            }

        }
    }


    public static IBizContext getBizContext(Context context) throws ConnectException {
        IBizContext biaContext =  KDNoteHelper.makeContext(context);
        //IBizContext biaContext = (IBizContext)SHRContext.getSessionContext().get(RPT_CTX);
        if (biaContext != null) {
            return biaContext;
        } else {
            try {
                KDNoteWebServerHelper nodeWeb = new KDNoteWebServerHelper();
                nodeWeb.setContextProvider(new IContextProvider() {
                    public IBizContext getBizContext(Context bosCtx) {
                        IBizContext ctx = (IBizContext)SHRContext.getSessionContext().get(ReportTemplateController.RPT_CTX);
                        if (ctx != null) {
                            return ctx;
                        } else {
                            try {
                                ctx = KDNoteHelper.makeContext(SHRContext.getInstance().getContext());
                                SHRContext.getSessionContext().put(ReportTemplateController.RPT_CTX, ctx);
                                return ctx;
                            } catch (ConnectException var4) {
                                //ReportTemplateController.logger.error("get page data error!", var4);
                                return null;
                            }
                        }
                    }
                });
                SHRContext.getSessionContext().put(NODE_SERVER, nodeWeb);
                return nodeWeb.getThisBizContext();
            } catch (Exception var2) {
                logger.error("get page data error!", var2);
                return null;
            }
        }
    }

    private Object printTimesControl( Object data, List idList, String rptTemplate,Context context) throws BOSException {
        MultiDataSourceDataProviderProxy multiDataProvider = new MultiDataSourceDataProviderProxy();
        StringBuffer failToPrintMsg = new StringBuffer();

        try {
            HashMap printAttributes = null;
            IBizContext bizContext = getBizContext(context);
            if (bizContext != null && bizContext.getBizContent() != null) {
                printAttributes = bizContext.getBizContent().getAttributes("/EAS_Note.kdrs/s-HR/AffairBiz/EmpEnroll/EmpEnrollBiz.r1-print", new String[]{"isselected", "prttimes"});
            }

            if (printAttributes != null && printAttributes.get("isselected") == null) {
                return data;
            } else {
                int curNum = 1;
                if (printAttributes != null) {
                    boolean isTimesCtrl = Integer.parseInt(String.valueOf(printAttributes.get("isselected"))) == 1;
                    if (!isTimesCtrl) {
                        return data;
                    }
                }

                ObjectUuidPK pk = new ObjectUuidPK(idList.get(0).toString());
                String bosType = pk.getObjectType().toString();
                IPrintIntegration pinfo = PrintIntegrationFactory.getRemoteInstance();
                List infoList = pinfo.getBillsPrintInfoByList(idList, bosType);
                if (rptTemplate != null && rptTemplate.trim().length() > 0) {
                    for(int i = 0; i < infoList.size(); ++i) {
                        logger.info("start the print control!");
                        int maxNum = 0;
                        if (printAttributes != null && printAttributes.get("prttimes") != null) {
                            maxNum = Integer.parseInt(String.valueOf(printAttributes.get("prttimes")));
                        }

                        int pnum = ((AbstractPrintIntegrationInfo)infoList.get(i)).getPrintedNumber();
                        String billID1 = ((AbstractPrintIntegrationInfo)infoList.get(i)).getPrintBillID();
                        logger.info("Max print number:>>" + maxNum);
                        logger.info("Alreadey print number:>>" + pnum);
                        logger.info("current print number:>>" + curNum);
                        String billNumber;
                        String msgInfo;
                        Object[] objs;
                        if (pnum >= maxNum) {
                            idList.remove(billID1);
                            billNumber = pinfo.getBillNumberByBosType(bosType, billID1);
                            msgInfo = EASResource.getString("com.kingdee.eas.basedata.assistant.PrintIntegrationResource", "pi.controlinfo1");
                            objs = new Object[]{billNumber, String.valueOf(curNum), String.valueOf(pnum), String.valueOf(maxNum)};
                            failToPrintMsg.append(MessageFormat.format(msgInfo, objs) + "\n");
                            HTML(failToPrintMsg.toString());
                        } else if (curNum + pnum > maxNum) {
                            idList.remove(billID1);
                            billNumber = pinfo.getBillNumberByBosType(bosType, billID1);
                            msgInfo = EASResource.getString("com.kingdee.eas.basedata.assistant.PrintIntegrationResource", "pi.controlinfo2");
                            objs = new Object[]{billNumber, String.valueOf(curNum), String.valueOf(pnum), String.valueOf(maxNum)};
                            failToPrintMsg.append(MessageFormat.format(msgInfo, objs) + "\n");
                            HTML(failToPrintMsg.toString());
                        }
                    }

                }

                multiDataProvider.put("MainQuery", (BOSQueryDelegate)data);
                CommonPrintIntegrationDataProvider printQueryData = new CommonPrintIntegrationDataProvider(bosType.toString(), PrintIntegrationManager.getPrintQueryPK());
                multiDataProvider.put("PrintQuery", printQueryData);
                PrintIntegrationManager.initPrint((KDNoteWebServerHelper)SHRContext.getSessionContext().get(NODE_SERVER), pk.getObjectType(), idList, rptTemplate, "com.kingdee.eas.scm.common.SCMResource", true);
                return multiDataProvider;
            }
        } catch (Exception var21) {
            var21.printStackTrace();
            return data;
        }
    }
    public static void HTML(String message) throws ShrWebBizException {
        ServletResponse response = SHRContext.getInstance().getResponse();

        PrintWriter pw;
        try {
            pw = response.getWriter();
        } catch (IOException var4) {
            throw new ShrWebBizException("can't open the output stream!");
        }

        pw.write(message);
        pw.flush();
        pw.close();
    }
    
}