package com.engine.htsc.payment.biz;


import com.engine.common.util.ServiceUtil;
import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.entity.freeNode.FreeNodeEntity;
import com.engine.workflow.service.HtmlToPdfService;
import com.engine.workflow.service.impl.HtmlToPdfServiceImpl;
import weaver.conn.RecordSet;
import weaver.docs.share.DocShareUtil;
import weaver.file.FileSecurityUtil;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.system.SystemComInfo;
import weaver.workflow.exceldesign.HtmlLayoutOperate;
import weaver.workflow.workflow.WorkflowConfigComInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WfToDocBiz extends BaseBean {

    //底部签字意见列表显示数量
    private int pageSize =100;
    //是否用wk转换
    private String useWk="";
    private int keepsign;
    private User user;
    private String docfiles;
    Map<String,Object> pathMap;
    private LinkedHashMap<String,String> fileids;

    private boolean isOpenWaterMark; //是否生成水印
    private String useModeid ;
    /* ---这些参数给到workflowtodoc获取 避免查多次数据库 -- start*/
    private String wfdocpathtype ="1";
    private String wfdocpath = "";
    private String wfdocpathfieldid = "";
    private String wfdocpathfieldvalue ="";
    private String isAccordToSubCom = "";
    /* --- end  ----*/

    String OnlineHtmlMethod; //生成在线文档

    private Map<String,Object> otherParamsMap;

    public Map<String, Object> getOtherParamsMap() {
        return otherParamsMap;
    }

    public void setOtherParamsMap(Map<String, Object> otherParamsMap) {
        this.otherParamsMap = otherParamsMap;
    }

    public void setOnlineHtmlMethod(String onlineHtmlMethod) {
        OnlineHtmlMethod = onlineHtmlMethod;
    }

    public Map<String, Object> getPathMap() {
        return pathMap;
    }

    public void setPathMap(Map<String, Object> pathMap) {
        this.pathMap = pathMap;
    }

    public String getWfdocpathtype() {
        return wfdocpathtype;
    }

    public void setWfdocpathtype(String wfdocpathtype) {
        this.wfdocpathtype = wfdocpathtype;
    }

    public String getWfdocpath() {
        return wfdocpath;
    }

    public void setWfdocpath(String wfdocpath) {
        this.wfdocpath = wfdocpath;
    }

    public String getWfdocpathfieldid() {
        return wfdocpathfieldid;
    }

    public void setWfdocpathfieldid(String wfdocpathfieldid) {
        this.wfdocpathfieldid = wfdocpathfieldid;
    }

    public String getWfdocpathfieldvalue() {
        return wfdocpathfieldvalue;
    }

    public void setWfdocpathfieldvalue(String wfdocpathfieldvalue) {
        this.wfdocpathfieldvalue = wfdocpathfieldvalue;
    }

    public String getIsAccordToSubCom() {
        return isAccordToSubCom;
    }

    public void setIsAccordToSubCom(String isAccordToSubCom) {
        this.isAccordToSubCom = isAccordToSubCom;
    }



    public WfToDocBiz(User user, int pageSize, int keepsign, String docfiles){
        this.pageSize = pageSize;
        this.keepsign = keepsign;
        this.user = user;
        this.docfiles = docfiles;
        this.fileids = new LinkedHashMap<>();
    }

    public WfToDocBiz(User user, int pageSize, int keepsign, String docfiles, String useModeid){
        this.pageSize = pageSize;
        this.keepsign = keepsign;
        this.user = user;
        this.docfiles = docfiles;
        this.fileids = new LinkedHashMap<>();
        this.useModeid=useModeid;
    }

    public WfToDocBiz(User user, int pageSize, int keepsign, String docfiles, String useModeid, boolean isOpenWaterMark){
        this.pageSize = pageSize;
        this.keepsign = keepsign;
        this.user = user;
        this.docfiles = docfiles;
        this.fileids = new LinkedHashMap<>();
        this.useModeid=useModeid;
        this.isOpenWaterMark = isOpenWaterMark;
    }


    public WfToDocBiz(){
    }


    /*
     * 生成html和pdf
     */
    public void generatepdfandhtml(String requestid, String filename,String temppath,String src){
        int onlyHtml =0;
        if (docfiles.contains("2")&&!docfiles.contains("3")){  //只选了生成离线html 没选pdf
            onlyHtml =1;
        }else if (docfiles.contains("3")&&docfiles.contains("2")){  //选了pdf和html
            onlyHtml =2;
        }else if (docfiles.contains("3")&&!docfiles.contains("2")){  //只选了pdf
            onlyHtml =0;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("requestid",requestid);
        params.put("onlyHtml", onlyHtml);
        params.put("pageSize", pageSize);
        params.put("path", temppath);
        params.put("filename", filename);
        params.put("keepsign", keepsign);
        params.put("limitauth", "0");
        params.put("src",src);
        params.put("modeid",useModeid);
        //是否使用wk,在config表中读配置
        WorkflowConfigComInfo configComInfo = new WorkflowConfigComInfo();
        useWk = Util.null2String(configComInfo.getValue("htmltopdf_usewk"));
        new BaseBean().writeLog("jymjym……useWk ="+useWk);
        //是否使用Itext7
        String useItext7  = Util.null2String(configComInfo.getValue("workflowtodoc_useitext7"));
        params.put("useItext7", useItext7);
        if (!"".equals(useWk)){
            params.put("useWk", useWk);
        }
        params.put("isOpenWaterMark",isOpenWaterMark);

        params.put("onlinehtml",OnlineHtmlMethod.equals("1")&&docfiles.contains("1"));  //在线htmlE9

        if (this.otherParamsMap!=null)
            params.putAll(this.otherParamsMap);

        HtmlToPdfService htmlToPdfService = (HtmlToPdfService) ServiceUtil.getService(HtmlToPdfServiceImpl.class,user);
        pathMap = (htmlToPdfService != null) ? htmlToPdfService.getFormDatas(params) : new HashMap<>();
    }

    public LinkedHashMap<String,String> getfileids(String requestname, String filename,String temppath){
        int onlyHtml =0;
        if (docfiles.contains("2")&&!docfiles.contains("3")){  //只选了生成离线html 没选pdf
            onlyHtml =1;
        }else if (docfiles.contains("3")&&docfiles.contains("2")){  //选了pdf和html
            onlyHtml =2;
        }else if (docfiles.contains("3")&&!docfiles.contains("2")){  //只选了pdf
            onlyHtml =0;
        }
        String htmlname="";
        String truefilename ="";

        if (OnlineHtmlMethod.equals("1")&&docfiles.contains("1")){  //在线html
            htmlname = temppath + Util.null2String(pathMap.get("onlinehtmlfilename"));
            truefilename = requestname +"_online.html";
            String fileid = saveAsFile(htmlname,truefilename);
            if (!"".equals(fileid)){
                fileids.put("online_html",fileid);
            }
        }

        if (docfiles.contains("2")){  //选了生成离线html
            if(onlyHtml ==1){ //只选了生成离线html 没选pdf
                htmlname = temppath + Util.null2String(pathMap.get("filename"));
            }else if(onlyHtml ==2){
                htmlname = temppath + Util.null2String(pathMap.get("htmlfilename"));
            }
            truefilename = requestname +"_offline_html.zip";
            String fileid = saveAsFile(htmlname,truefilename);
            if (!"".equals(fileid)){
                fileids.put("offline_html",fileid+"");
            }

        }
        if (docfiles.contains("3")){  //只要选了pdf
            if(onlyHtml ==0){  //只选了pdf
                htmlname = temppath + Util.null2String(pathMap.get("filename"));
            }else if(onlyHtml ==2){
                htmlname = temppath + Util.null2String(pathMap.get("pdffilename"));
            }
            truefilename =  requestname + "_offline_pdf.pdf";
            String fileid = saveAsFile(htmlname,truefilename);
            if (!"".equals(fileid)){
                fileids.put("offline_pdf",fileid);
            }
        }


        return fileids;
    }

    //保存为附件
    public String saveAsFile(String htmlname,String truefilename){
        truefilename = Util.formatMultiLang(truefilename,user.getLanguage()+"");
        InputStream in = null;
        byte[] buffer = null;
        File file = new File(htmlname);
        if (file.exists()){
            try {
                in = new FileInputStream(file);
                buffer = new byte[(int) file.length()];
                in.read(buffer);
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        ImageFileManager imageFileManager = new ImageFileManager();
        imageFileManager.setComefrom("WorkflowToDoc");
        imageFileManager.setData(buffer);
        imageFileManager.setImagFileName(truefilename);

        int fileid = imageFileManager.saveImageFile();
        if (fileid <= 0) {
            writeLog("保存离线HTML/PDF文件失败");
            return "";
        }
        FileSecurityUtil.deleteFile(file);
        return fileid+"";
    }

    /**
     * 获得文件保存目录
     *
     * @return
     */
    public String getFileSavePath() {
        SystemComInfo syscominfo = new SystemComInfo();
        String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());
        return createdir;
    }


    //获取存文档的路径
    public String getWfDocPath(String workflowid,String requestid){
        String doccategory = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from workflow_base where id = ?",workflowid);

        if (rs.next()){
            this.wfdocpathtype  = Util.null2String(rs.getString("wfdocpathtype"));
            this.wfdocpath = Util.null2String(rs.getString("wfdocpath"));
            this.wfdocpathfieldid = Util.null2String(rs.getString("wfdocpathfieldid"));

            int isbill = Util.getIntValue(rs.getString("isbill"), 0);
            int formid = Util.getIntValue(rs.getString("formid"), 0);
            if (wfdocpathtype.equals("1")||wfdocpathtype.equals("")){  //历史数据为空则默认用固定目录
                doccategory =  wfdocpath;
            }else if (wfdocpathtype.equals("2")){  //选择框字段值对应路径
                //先获取表单字段值
                String fieldvalue = "";   //表单字段值
                String tablename = " workflow_form ";
                String fieldname = "";
                String sql = "";
                if(isbill == 1){
                    sql = "select tablename from workflow_bill where id="+formid;
                    rs.executeQuery(sql);
                    if(rs.next()){
                        tablename = Util.null2String(rs.getString(1));
                    }
                    sql = "select fieldname from workflow_billfield where billid="+formid+" and id="+wfdocpathfieldid;
                }else{
                    sql = "select fieldname from workflow_formdictdetail where id="+wfdocpathfieldid;
                }
                rs.executeQuery(sql);
                if(rs.next()){
                    fieldname = Util.null2String(rs.getString(1));
                    if(!"".equals(tablename) && !"".equals(fieldname)){
                        sql = "select "+fieldname+" from "+tablename+" where requestid="+requestid;
                        rs.executeQuery(sql);
                        if(rs.next()){
                            fieldvalue = Util.null2String(rs.getString(1));
                        }
                    }
                }
                this.wfdocpathfieldvalue = fieldvalue;
                if (!fieldvalue.equals("")){
                    rs.executeQuery("select doccategory,isAccordToSubCom from workflow_selectitem t where fieldid="
                            + wfdocpathfieldid + " and selectvalue=" + fieldvalue);
                    if (rs.next()) {
                        doccategory = rs.getString("doccategory");
                        isAccordToSubCom = Util.null2String(rs.getString("isAccordToSubCom"));
                    }
                    if (isAccordToSubCom.equals("1")) {
                        int creater = 0;
                        rs.executeQuery("select creater from workflow_requestbase where requestId=" + requestid);
                        if (rs.next()) {
                            creater = Util.getIntValue(rs.getString("creater"), 0);
                        }

                        int subCompanyId = 0;
                        try {
                            ResourceComInfo resourceComInfo = new ResourceComInfo();
                            subCompanyId = Util.getIntValue(resourceComInfo.getSubCompanyID("" + creater), 0);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        rs.executeQuery("SELECT docCategory FROM Workflow_SelectitemObj where fieldid="
                                + wfdocpathfieldid + " and selectvalue=" + fieldvalue + " and  isBill=" + isbill
                                + " and objType='1' and objId= " + subCompanyId);
                        if (rs.next()) {
                            doccategory = Util.null2String(rs.getString("docCategory"));
                        }
                    }
                }
            }
        }
        return  doccategory;
    }

    /*
     *获取模板id
     */
    public String getModeid(int workflowid,int requestid,int nodeid){
        RecordSet rs = new RecordSet();
        int modeid = -1;
        FreeNodeEntity nodeEntity = FreeNodeBiz.getCurrentFreeNodeEntity(requestid,nodeid);
        if(nodeEntity != null) {  //如果为自由节点
            nodeid = nodeEntity.getExtendnodeid();
        }
        String wfdocsource ="";
        rs.executeQuery("select * from workflow_base where id = ?",workflowid);
        if (rs.next()){
            wfdocsource = Util.null2String(rs.getString("wfdocsource"));   //附件来源 1：显示模板 2：打印模板
        }
        HtmlLayoutOperate htmlLayoutOperate = new HtmlLayoutOperate();
        if (wfdocsource.equals("2")) {  //打印模板 获取开启的第一个打印模板 如果没有开启的打印模板，则取显示模板，如果没有打印模板  则取显示模板
            rs.executeQuery("select * from workflow_printset where nodeid = ? and type =1 and printenable =1 order by orderid",nodeid);
            if (rs.next()){
                modeid = Util.getIntValue(rs.getString("modeid"),-1);
            }else {
                modeid = htmlLayoutOperate.getActiveHtmlLayout(workflowid, nodeid, 0);   //获取当前显示模板的活动模板
            }
        }else {  //否则就取当前显示模板
            rs.executeQuery("select ismode from workflow_flownode  where workflowid=? and nodeid=?",workflowid,nodeid);
            if (rs.next()){
                String ismode = Util.null2String(rs.getString("ismode"));
                if (ismode.equals("2")){   //如果不是
                    modeid = htmlLayoutOperate.getActiveHtmlLayout(workflowid, nodeid, 0);   //获取当前显示模板的活动模板
                }else{
                    modeid = -1;
                }
            }

        }
        return modeid+"";
    }

    /*
     * 文档赋权
     * docid 赋权的文档id
     * requestid 请求id
     * docowner 文档所有者
     * 给流程所有操作者赋权
     */
    public static void docShare(String docids,String requestid,int docowner){
        RecordSet rs = new RecordSet();
        //选择流程的所有操作人
        String sql = "select distinct userid,usertype,isremark,agentorbyagentid,agenttype from workflow_currentoperator where requestid ="+requestid;
        rs.executeQuery(sql);
        String userids = "";
        String usertypes = "";
        String agentids = "";
        String agenttypes = "";
        while (rs.next()){
            int opertor = rs.getInt("userid");
            int beagentorid=rs.getInt("agentorbyagentid");
            int usertype = rs.getInt("usertype");
            int isremark=Util.getIntValue(rs.getString("isremark"),-1);
            int agenttype=Util.getIntValue(rs.getString("agenttype"),-1);
            //用户相关客户一次性共享
            userids += "," + opertor;
            usertypes += "," + usertype;

            if (beagentorid > 0) {
                agentids += "," + beagentorid;
                agenttypes += ",0";
            }
        }
        //修正数据
        if (userids.length() > 0) {
            userids = userids.substring(1);
            usertypes = usertypes.substring(1);
        }
        if (agentids.length() > 0) {
            agentids = agentids.substring(1);
            agenttypes = agenttypes.substring(1);
        }
        new BaseBean().writeLog("docShare------userids="+userids+"-------agentids="+agentids+"-----docid="+docids);
        User user = new User(docowner);
        //文档共享
        DocShareUtil dsu = new DocShareUtil();
        //共享
        dsu.addDocShare(user, docids, usertypes, userids, 1);

        if (agentids.length() > 0) {
            //共享
            dsu.addDocShare(user, docids, agenttypes, agentids, 1);
        }
    }


}
