package cn.myapps.runtime.common.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.myapps.base.web.WebUser;
import cn.myapps.common.OBPMRuntimeException;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.exception.OBPMValidateException;
import cn.myapps.common.model.activity.ActionContent;
import cn.myapps.common.model.activity.Activity;
import cn.myapps.common.model.activity.ActivityResult;
import cn.myapps.common.model.activity.ActivityType;
import cn.myapps.common.model.activity.ValidationWrap;
import cn.myapps.common.model.stylerepository.StyleRepositoryVO;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.SpringApplicationContextUtil;
import cn.myapps.conf.FeignConfig;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.common.feign.service.KmsFeignService;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcess;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcessBean;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.util.StringUtil;
import cn.myapps.common.util.cache.MemoryCacheUtil;
import com.KGitextpdf.text.Image;
import com.lowagie.text.pdf.PdfReader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;


public class ExportToPdf extends ActivityType {

    public ExportToPdf(Activity act) {
        super(act);
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public String getAfterAction() {
        return BASE_ACTION;
    }

    public String getBackAction() {
        return BASE_ACTION;
    }

    public String getBeforeAction() {
        return BASE_ACTION;
    }

    public String getButtonId() {
        return DOCUMENT_BUTTON_ID;
    }

    public String getDefaultClass() {
        return DOCUMENT_BUTTON_CLASS;
    }

    public String getDefaultOnClass() {
        return DOCUMENT_BUTTON_ON_CLASS;
    }

    public String getOnClickFunction() {
        //return "doExportToPDF('" + act.getId() + "')";
        return "Activity.doExecute('" + act.getId() + "'," + act.getType() + ")";
    }

    public ActivityResult doExecute(ActionContent actionContent, Document doc, WebUser user) throws Exception {
        ActivityResult activityResult = new ActivityResult();
        return activityResult;
    }

    public ActivityResult doProcess(ActionContent action, Document doc, WebUser user,String htmlBody) throws Exception {
        ActivityResult activityResult = new ActivityResult();
        ValidationWrap validationWrap = new ValidationWrap();
        String pdfPath = "";
        try {
            HttpServletRequest request = action.getRequest();
            HttpServletResponse response = action.getResponse();
            ParamsTable params = action.getParams();

            String formid = params.getParameterAsString("_formid");
            //兼容restFul 导出pdf 接口调用
            if(StringUtil.isBlank(formid)) formid=(String) request.getAttribute("formId");
//            Form form = FormHelper.get_FormById(formid);

            FormDesignTimeService fp = DesignTimeServiceManager.formDesignTimeService();
            Form form = (Form) fp.doView(formid);

            Collection<Activity> acts = form.getActivities();
            Iterator<Activity> it = acts.iterator();
            String afterActionScript = "";
            String actId = "";
            while (it.hasNext()) {
                Activity act = it.next();
                if (ActivityType.EXPTOPDF == act.getType()) {
                    actId = act.getId();
                    afterActionScript = act.getAfterActionScript();
                }
            }

            String id = params.getParameterAsString("content.id");
            //兼容restFul 导出pdf 接口调用
            if(StringUtil.isBlank(id)) id=(String) request.getAttribute("docId");
            DocumentProcess docProcess = new DocumentProcessBean(form.getApplicationid());
            doc = (Document) MemoryCacheUtil.getFromPrivateSpace(id, user);
            if (doc == null) {
                doc = (Document) docProcess.doView(id);
            }

            IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), form.getApplicationid());
            runner.initBSFManager(doc, params, user, new ArrayList<ValidateMessage>());

            //String agent = request.getHeader("USER-AGENT");
            String fileName="";
            if(!StringUtil.isBlank(form.getDescription())){
                fileName = form.getDescription();
            }else{
                fileName = form.getName();
            }
//            if (null != agent && -1 != agent.indexOf("Firefox")) {
//                response.setContentType("application/pdf; charset=UTF-8");
//                response.setHeader("Content-Disposition", "attachment; filename=" + MimeUtility.encodeText(fileName, "UTF-8", "B") + ".pdf");
//            } else {
//                response.setContentType("application/pdf; charset=UTF-8");
//                response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ".pdf");
//            }

//            new ConvertHTML2Pdf().generatePDF(pdfHtml, response.getOutputStream());
            String folderPath = PropertyUtil.getPath() + File.separator + "uploads"+ File.separator +"exportPdf" + File.separator;
            File folder = new File(folderPath);
            //文件夹不存在则创建
            if(!folder.exists()){
                folder.mkdirs();
            }
            String filePath = folderPath + "temp.html";
            FileOutputStream fos = new FileOutputStream(filePath);

            //拼接获取图片的保存文件夹路径
            File file = new File("obpm-demo");
            String imgpath = file.getAbsolutePath().replace("\\","/");
            //String s = "";
            fos.write("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" >".getBytes());

            fos.write(htmlBody.replaceAll("/obpm/",imgpath).getBytes());

            // 存在签章
            if (!StringUtil.isBlank(doc.getSign())){
                JSONArray signs = cn.myapps.util.json.JsonTmpUtil.fromObject(doc.getSign());
                for (Iterator iterator = signs.iterator();iterator.hasNext();){
                    JSONObject json = (JSONObject) iterator.next();
                    String marginLeft = json.getString("left");
                    String marginTop = json.getString("top");
                    String realPath = PropertyUtil.getPath() + json.getString("img");
                    float left;
                    float top;
                    left = Float.parseFloat(marginLeft);
                    top = Float.parseFloat(marginTop);
                    String imgHtml = "<img src=\"" + realPath + "\" style=\"position:absolute;left:" +
                            left + "px;top:" + top + "px;width:100px\">";
                    fos.write(imgHtml.getBytes());
                }
            }

            fos.write("</html>".getBytes());
            fos.close();
            FeignConfig.ACCESS_TOKEN = user.getACCESS_TOKEN(request);
            String outputPDF = folderPath + fileName + ".pdf";
            pdfPath = File.separator + "uploads"+ File.separator +"exportPdf" + File.separator + fileName + ".pdf";
            //通过feign服务调用kms的html转pdf接口

            KmsFeignService kmsFeignService = SpringApplicationContextUtil.getBean(KmsFeignService.class);
            kmsFeignService.htmlConvertPdf(filePath,outputPDF);

//            File file = new File(outputPDF);
//            //文件下载response设置
//            new ActivityRunTimeServiceImpl().doFileDownload(file,response.getOutputStream());
//            response.flushBuffer();

            //执行运行后脚本
            if (afterActionScript != null && !afterActionScript.equals("")) {
                StringBuffer afterLabel = new StringBuffer();
                afterLabel.append("Activity Action:").append(actId).append(" afterActionScript");
                runner.run(act, afterLabel.toString(), afterActionScript);
            }
        } catch (IOException e) {
            activityResult.setRuntimeException(new OBPMRuntimeException(e.getMessage(), e));
            e.printStackTrace();
        } catch (OBPMValidateException e) {
            validationWrap.addFieldError("1", e.getValidateMessage());
            e.printStackTrace();
        } catch (RuntimeException re){
            activityResult.setRuntimeException(new OBPMRuntimeException(re.getMessage(), re));
            re.printStackTrace();
        }catch (Exception e) {
            activityResult.setRuntimeException(new OBPMRuntimeException(e.getMessage(), e));
            e.printStackTrace();
        }
        activityResult.setResultType(ActivityResult.RESULT_TYPE_NONE);
        activityResult.setValidationWrap(validationWrap);
        activityResult.setResultData(pdfPath);
        return activityResult;
    }

    /**
     * 根据传入的css路径地址获取css文件内容
     *
     * @param url
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    private String getCssContent(String url, HttpServletRequest request, HttpServletResponse response,Document doc) throws Exception {
        StringBuffer content = new StringBuffer();
        content.append("<style>\n");
        String filePath = url;
        content.append(cn.myapps.util.file.FileOperate.getFileContentAsString(filePath));
        String styleContent = "";
        StyleRepositoryVO style = doc.getForm().getStyle();
        if(style != null){
            styleContent = style.getContent();
        }
        if(!StringUtil.isBlank(styleContent)){
            content.append(styleContent);
            content.append("\n");
        }
        content.append("</style>\n");
        return content.toString();
    }

//    @Override
//    public ValueObject doMbExecte(WebUser user, ParamsTable params)
//            throws Exception {
//        return null;
//    }

}
