package weaver.interfaces.htsc.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424Util;

import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.*;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.gwlc.WrokflowToOAUtil;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

/***
 *
 */
public class UploadDocUtil {

    /***
     *
     * @param docid
     * @param filepath
     * @param realpath
     * @return
     */
    public  Map<String,String> uploadFile(String docid,String filepath,String realpath)
    {
        Map<String,String> map=new HashMap<>();

        BaseBean bb = new BaseBean();
        bb.writeLog("uploadFile");
        RecordSet rs = new RecordSet();
        String pubtime = TimeUtil.getCurrentDateString();

        int subcategoryid = -1;
        int maincategoryid = -1;
        PropBean pb = new PropBean();
        int seccategoryid = -1;
        String secid = pb.getPropName("htsc_yyfhj");
        if(!"".equals(secid)){
            seccategoryid = Util.getIntValue(secid);
        }
        bb.writeLog("seccategoryid:"+seccategoryid);



        String docextendname = "" ;
        String imagefilename = "";
        String docfiletype = "";
        String imagefiletype = "";
        String realfilepath = "" ;
        String doccreaterid ="";
        String doctype = "";
        int filesize = 0;

        String sql =" select t.maincategory,t.subcategory,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize,\n" +
                    " l.docfiletype,p.imagefiletype,t.doccreaterid \n" +
                    " from docdetail t\n" +
                    " inner join docimagefile l on l.docid = t.id\n" +
                    " inner join imagefile p on p.imagefileid = l.imagefileid\n" +
                    " where docid="+docid+" and versionid IN(select max(versionid) from DocImageFile where docid="+docid+" ) ";

        rs.execute(sql);
        if(rs.next()){
//            seccategoryid = Util.getIntValue(rs.getString("seccategory"));
//            maincategoryid = Util.getIntValue(rs.getString("maincategory"));
//            subcategoryid = Util.getIntValue(rs.getString("subcategory"));
//            if(!"".equals(subid)){
//                subcategoryid = Util.getIntValue(subid);
//            }else{
//                subcategoryid = Util.getIntValue(rs.getString("subcategory"));
//            }

            docextendname = Util.null2String(rs.getString("docextendname"));
            imagefilename = Util.null2String(rs.getString("imagefilename"));
            docfiletype = Util.null2String(rs.getString("docfiletype"));

            imagefiletype = Util.null2String(rs.getString("imagefiletype"));
            doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            doctype = Util.null2String(rs.getString("doctype"));
            filesize = Util.getIntValue(rs.getString("filesize"));
        }

        int newdocid = 0;
        int imagefileid=0;

        try {
            bb.writeLog("imagefilename:"+imagefilename);
            bb.writeLog("doccreaterid:"+doccreaterid);
            bb.writeLog("secCategoryid:"+seccategoryid);
            bb.writeLog("docextendname:"+docextendname);
            bb.writeLog("doccreaterid:"+doccreaterid);
            String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
            bb.writeLog("filetype:"+filetype);
            bb.writeLog("realpath:"+realpath);
            bb.writeLog("filepath:"+filepath);
            imagefilename = "正文_用印件"+"."+filetype;
            boolean istrue = true;
            try {
                realfilepath = copyFileUsingChannel(filepath,realpath,docid+"."+filetype);
                bb.writeLog("realfilepath:"+realfilepath);

                File realfile = new File(realfilepath);
                if(!realfile.exists())
                {
                    istrue = false;
                }
            }catch (Exception e){
                bb.writeLog(e);
                istrue = false;
            }
            if(istrue)
            {
                try{
                    String content = "";
                    newdocid = createDoc(imagefilename,content,Util.getIntValue(doccreaterid),pubtime,maincategoryid,subcategoryid,seccategoryid,Util.getIntValue(doctype),docextendname,"");
                    bb.writeLog("newdocid:"+newdocid);

                    ImageFileIdUpdate im = new ImageFileIdUpdate();
                    imagefileid = im.getImageFileNewId();
                    bb.writeLog("imagefileid:"+imagefileid);

                    sql= " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                         " values("+imagefileid+",'"+imagefilename+"','"+imagefiletype+"',1,'"+realfilepath+"',0,0,'"+filesize+"')";
                    rs.execute(sql);

                    DocImageManager dm = new DocImageManager();
                    VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                    int versionid = versionIdUpdate.getVersionNewId();
                    sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid)"+
                          " values("+dm.getNextDocImageFileId()+","+newdocid+","+imagefileid+",'"+imagefilename+"','0','0','0','0','"+docfiletype+"',"+versionid+")";
                    rs.execute(sql);

                    sql = " select count(1) as cou from DocImageFile where docid="+newdocid;
                    rs.execute(sql);
                    rs.next();
                    int count = Util.getIntValue(Util.null2String(rs.getString("cou")));

                    sql = " update docdetail set accessorycount="+count+" where id="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);
                }catch (Exception e){
                    bb.writeLog("e1:"+e);
                }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        map.put("newdocid",String.valueOf(newdocid));
        map.put("newimagefileid",String.valueOf(imagefileid));
        map.put("imagefilename",imagefilename);
        map.put("realfilepath",realfilepath);
        return map;
    }

    public void  Callbackgateway(int imagefileid,String imagefilename,String realfilepath){

                BaseBean bb = new BaseBean();
                bb.writeLog("uploadFile");
                RecordSet rs = new RecordSet();
        InputStream inputStream = null;
        CloseableHttpResponse clresponse=null;
                try{
                    String upload = QC969424Util.getPV("upload");
                    String systemNo = QC969424Util.getPV("systemNo");
                    String url = upload+"/"+systemNo;
                    bb.writeLog("url:"+url);
                    bb.writeLog("imagefilename:"+imagefilename);
                    bb.writeLog("realfilepath:"+realfilepath);
                    QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();
                    File file = new File(realfilepath);
                    inputStream = new FileInputStream(file);
                    clresponse= qc.doUpload(url,imagefilename,inputStream);
                    bb.writeLog("clresponse:"+clresponse);

                    int statusCode = clresponse.getStatusLine().getStatusCode();
                    bb.writeLog("statusCode:"+statusCode);
                    if(statusCode == 200)
                    {
                        String res = EntityUtils.toString(clresponse.getEntity());
                        bb.writeLog("res:"+res);
                        if(!"".equals(res)){
                            String sql = " update imagefile set fileid=? where imagefileid=?";
                            bb.writeLog(" sql:"+sql+" imagefileid:"+imagefileid);
                            rs.executeUpdate(sql,new Object[]{res,imagefileid});
                        }
                    }

                    inputStream.close();;
                    //释放链接
                    clresponse.close();
                }catch (Exception ex){
                    ex.printStackTrace();
                    bb.writeLog("ex:"+ex);
                }finally {
                    try {
                        if(inputStream !=null){
                            inputStream.close();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if(clresponse !=null){
                            clresponse.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }





    }

    public  Map<String,String> ManualSignuploadFile(String docid,String filepath,String realpath)
    {
        Map<String,String> map=new HashMap<>();

        BaseBean bb = new BaseBean();
        bb.writeLog("uploadFile");
        RecordSet rs = new RecordSet();
        String pubtime = TimeUtil.getCurrentDateString();

        int seccategoryid = 0;
        int maincategoryid = 0;
        int subcategoryid = 0;
        String docextendname = "" ;
        String imagefilename = "";
        String realfilepath = "" ;
        String docfiletype = "";
        String imagefiletype = "";
        String doccreaterid ="";
        String doctype = "";
        int filesize = 0;

        PropBean pb = new PropBean();
        String secid = pb.getPropName("htsc_yyfhj");
        if(!"".equals(secid)){
            seccategoryid = Util.getIntValue(secid);
        }
        bb.writeLog("seccategoryid:"+seccategoryid);

        String sql =" select t.maincategory,t.subcategory,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize,\n" +
                " l.docfiletype,p.imagefiletype,t.doccreaterid \n" +
                " from docdetail t\n" +
                " inner join docimagefile l on l.docid = t.id\n" +
                " inner join imagefile p on p.imagefileid = l.imagefileid\n" +
                " where docid="+docid+" and versionid IN(select max(versionid) from DocImageFile where docid="+docid+" ) ";

        rs.execute(sql);
        if(rs.next()){
//            seccategoryid = Util.getIntValue(rs.getString("seccategory"));
            maincategoryid = Util.getIntValue(rs.getString("maincategory"));
            subcategoryid = Util.getIntValue(rs.getString("subcategory"));

            docextendname = Util.null2String(rs.getString("docextendname"));
            imagefilename = Util.null2String(rs.getString("imagefilename"));
            docfiletype = Util.null2String(rs.getString("docfiletype"));

            imagefiletype = Util.null2String(rs.getString("imagefiletype"));
            doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            doctype = Util.null2String(rs.getString("doctype"));
            doctype="12"; //因为生成的pdf没有docid，所有用之前上传的文件保存关联。那么doctype改成12 为pdf
            filesize = Util.getIntValue(rs.getString("filesize"));
        }

        int newdocid = 0;
        int imagefileid=0;
        try {
            bb.writeLog("imagefilename:"+imagefilename);
            bb.writeLog("doccreaterid:"+doccreaterid);
            bb.writeLog("secCategoryid:"+seccategoryid);
            bb.writeLog("docextendname:"+docextendname);
            bb.writeLog("doccreaterid:"+doccreaterid);



            //   String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
            String filetype =".pdf";
            int  filepathlength=  filepath.split("\\.").length;
            if(filepathlength>0){
                //获取附件的后缀名
                filetype= "."+filepath.split("\\.")[filepathlength-1];
            }
            bb.writeLog("filetype:"+filetype);
            bb.writeLog("realpath:"+realpath);
            bb.writeLog("filepath:"+filepath);

            imagefilename = imagefilename.substring(0,imagefilename.lastIndexOf("."))+filetype;
            bb.writeLog("imagefilename:"+imagefilename);
            boolean istrue = true;

            try {
                realfilepath = copyFileUsingChannel(filepath,realpath,docid+filetype);
                bb.writeLog("realfilepath:"+realfilepath);

                File realfile = new File(realfilepath);
                if(!realfile.exists())
                {
                    istrue = false;
                }
            }catch (Exception e){
                bb.writeLog(e);
                istrue = false;
            }
            if(istrue)
            {
                try{
                    String content = "";
                    newdocid = createDoc(imagefilename,content,Util.getIntValue(doccreaterid),pubtime,maincategoryid,subcategoryid,seccategoryid,Util.getIntValue(doctype),docextendname,"");
                    bb.writeLog("newdocid:"+newdocid);

                    ImageFileIdUpdate im = new ImageFileIdUpdate();
                    imagefileid = im.getImageFileNewId();
                    bb.writeLog("imagefileid:"+imagefileid);

                    sql= " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                            " values("+imagefileid+",'"+imagefilename+"','"+imagefiletype+"',1,'"+realfilepath+"',0,0,'"+filesize+"')";
                    rs.execute(sql);

                    DocImageManager dm = new DocImageManager();
                    VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                    int versionid = versionIdUpdate.getVersionNewId();
                    String operatedate = com.weaver.general.TimeUtil.getCurrentDateString();
                    String operatetime = com.weaver.general.TimeUtil.getOnlyCurrentTimeString();
                    sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid,operatedate,operatetime)"+
                            " values("+dm.getNextDocImageFileId()+","+newdocid+","+imagefileid+",'"+imagefilename+"','0','0','1','0','"+docfiletype+"',"+versionid+",'"+operatedate+"','"+operatetime+"')";
                    rs.execute(sql);

                    sql = " select count(1) as cou from DocImageFile where docid="+newdocid;
                    rs.execute(sql);
                    rs.next();
                    int count = Util.getIntValue(Util.null2String(rs.getString("cou")));

                    sql = " update docdetail set accessorycount="+count+" where id="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                    WrokflowToOAUtil wrokflowToOAUtil = new WrokflowToOAUtil();
                    wrokflowToOAUtil.uploadFile2SG(String.valueOf(imagefileid),imagefilename,realfilepath,"0");

                }catch (Exception e){
                    bb.writeLog("e1:"+e);
                }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        map.put("newdocid",String.valueOf(newdocid));
        map.put("newimagefileid",String.valueOf(imagefileid));
        map.put("imagefilename",imagefilename);
        map.put("realfilepath",realfilepath);
        return map;
    }


    public  Map<String,String> zwpdftofupload(String docid,String wh)
    {
        Map<String,String> map=new HashMap<>();

        BaseBean bb = new BaseBean();
        bb.writeLog("uploadFile");
        RecordSet rs = new RecordSet();
        String pubtime = TimeUtil.getCurrentDateString();

        int seccategoryid = 0;
        int maincategoryid = 0;
        int subcategoryid = 0;
        String docextendname = "" ;
        String imagefilename = "";
        String realfilepath = "" ;
        String docfiletype = "";
        String imagefiletype = "";
        String doccreaterid ="";
        String doctype = "";
        String filerealpath="";
        int filesize = 0;
        String oldimagefileid="";

        String sql =" select t.maincategory,t.subcategory,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize,\n" +
                " l.docfiletype,p.imagefiletype,p.imagefileid,p.filerealpath,t.doccreaterid \n" +
                " from docdetail t\n" +
                " inner join docimagefile l on l.docid = t.id\n" +
                " inner join imagefile p on p.imagefileid = l.imagefileid\n" +
                " where docid="+docid+" and versionid IN(select max(versionid) from DocImageFile where docid="+docid+" ) ";

        rs.execute(sql);
        if(rs.next()){
            seccategoryid = Util.getIntValue(rs.getString("seccategory"));
            maincategoryid = Util.getIntValue(rs.getString("maincategory"));
            subcategoryid = Util.getIntValue(rs.getString("subcategory"));
            docextendname = Util.null2String(rs.getString("docextendname"));
            imagefilename = Util.null2String(rs.getString("imagefilename"));
            docfiletype = Util.null2String(rs.getString("docfiletype"));
            filerealpath= Util.null2String(rs.getString("filerealpath"));
            imagefiletype = Util.null2String(rs.getString("imagefiletype"));
            doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            doctype = Util.null2String(rs.getString("doctype"));

            oldimagefileid=Util.null2String(rs.getString("imagefileid"));

            doctype="12"; //因为生成的pdf没有docid，所有用之前上传的文件保存关联。那么doctype改成12 为pdf
            filesize = Util.getIntValue(rs.getString("filesize"));
        }

        int newdocid = 0;
        int imagefileid=0;
        try {
            bb.writeLog("imagefilename:"+imagefilename);
            bb.writeLog("doccreaterid:"+doccreaterid);
            bb.writeLog("secCategoryid:"+seccategoryid);
            bb.writeLog("docextendname:"+docextendname);
            bb.writeLog("doccreaterid:"+doccreaterid);



         //   String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
            String filetype =".pdf";

         /*   int  filepathlength=  filerealpath.split("\\.").length;
            if(filepathlength>0){
                //获取附件的后缀名
                filetype= "."+filerealpath.split("\\.")[filepathlength-1];
            }*/
            String[] valuesplit=  filerealpath.split("/");
          String filerealpathvalue=  filerealpath.replace(valuesplit[valuesplit.length-1],"");
            String realpath=filerealpathvalue+ JAVATools.getuuid();


             bb.writeLog("filetype:"+filetype);
            bb.writeLog("realpath:"+realpath);
            bb.writeLog("filepath:"+filerealpath);

            imagefilename = "正文"+filetype;
            if(!"".equals(wh)){
                imagefilename=wh+"-"+imagefilename;
            }

                    //imagefilename.split("\\.")[0].toString()+"_电子用印件"+filetype;
            bb.writeLog("imagefilename:"+imagefilename);
            boolean istrue = true;

            try {
                realfilepath = zwpdfimagefiletorealfile(oldimagefileid,realpath,docid+filetype);
                bb.writeLog("realfilepath:"+realfilepath);
               // InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                if("".equals(realfilepath)){
                    istrue = false;
                }
                              /*  File realfile = new File(realfilepath);
                if(!realfile.exists())
                {
                    istrue = false;
                }*/
            }catch (Exception e){
                JAVATools.SetCmdwritelog("附件转正文失败:");
                bb.writeLog(e);
                istrue = false;
            }
            if(istrue)
            {
                try{
                    String content = "";
                    newdocid = createDoc(imagefilename,content,Util.getIntValue(doccreaterid),pubtime,maincategoryid,subcategoryid,seccategoryid,Util.getIntValue(doctype),docextendname,"");
                    bb.writeLog("newdocid:"+newdocid);

                    ImageFileIdUpdate im = new ImageFileIdUpdate();
                    imagefileid = im.getImageFileNewId();
                    bb.writeLog("imagefileid:"+imagefileid);

                    sql= " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                            " values("+imagefileid+",'"+imagefilename+"','"+imagefiletype+"',1,'"+realfilepath+"',0,0,'"+filesize+"')";
                    rs.execute(sql);

                    DocImageManager dm = new DocImageManager();
                    VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                    int versionid = versionIdUpdate.getVersionNewId();
                    sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid)"+
                            " values("+dm.getNextDocImageFileId()+","+newdocid+","+imagefileid+",'"+imagefilename+"','0','0','1','0','"+docfiletype+"',"+versionid+")";
                    rs.execute(sql);

                    sql = " select count(1) as cou from DocImageFile where docid="+newdocid;
                    rs.execute(sql);
                    rs.next();
                    int count = Util.getIntValue(Util.null2String(rs.getString("cou")));

                    sql = " update docdetail set accessorycount="+count+" where id="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                }catch (Exception e){
                    bb.writeLog("e1:"+e);
                }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        map.put("newdocid",String.valueOf(newdocid));
        map.put("newimagefileid",String.valueOf(imagefileid));
        map.put("imagefilename",imagefilename);
        map.put("realfilepath",realfilepath);
        return map;
    }

    /*重载附件名称*/
    public  Map<String,String> pdftofupload(String docid)
    {
        Map<String,String> map=new HashMap<>();

        BaseBean bb = new BaseBean();
        bb.writeLog("uploadFile");
        RecordSet rs = new RecordSet();
        String pubtime = TimeUtil.getCurrentDateString();

        int seccategoryid = 0;
        int maincategoryid = 0;
        int subcategoryid = 0;
        String docextendname = "" ;
        String imagefilename = "";
        String realfilepath = "" ;
        String docfiletype = "";
        String imagefiletype = "";
        String doccreaterid ="";
        String doctype = "";
        String filerealpath="";
        int filesize = 0;
        String oldimagefileid="";

        String sql =" select t.maincategory,t.subcategory,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize,\n" +
                " l.docfiletype,p.imagefiletype,p.imagefileid,p.filerealpath,t.doccreaterid \n" +
                " from docdetail t\n" +
                " inner join docimagefile l on l.docid = t.id\n" +
                " inner join imagefile p on p.imagefileid = l.imagefileid\n" +
                " where docid="+docid+" and versionid IN(select max(versionid) from DocImageFile where docid="+docid+" ) ";

        rs.execute(sql);
        if(rs.next()){
            seccategoryid = Util.getIntValue(rs.getString("seccategory"));
            maincategoryid = Util.getIntValue(rs.getString("maincategory"));
            subcategoryid = Util.getIntValue(rs.getString("subcategory"));
            docextendname = Util.null2String(rs.getString("docextendname"));
            imagefilename = Util.null2String(rs.getString("imagefilename"));
            docfiletype = Util.null2String(rs.getString("docfiletype"));
            filerealpath= Util.null2String(rs.getString("filerealpath"));
            imagefiletype = Util.null2String(rs.getString("imagefiletype"));
            doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            doctype = Util.null2String(rs.getString("doctype"));

            oldimagefileid=Util.null2String(rs.getString("imagefileid"));

            doctype="12"; //因为生成的pdf没有docid，所有用之前上传的文件保存关联。那么doctype改成12 为pdf
            filesize = Util.getIntValue(rs.getString("filesize"));
        }

        int newdocid = 0;
        int imagefileid=0;
        try {
            bb.writeLog("imagefilename:"+imagefilename);
            bb.writeLog("doccreaterid:"+doccreaterid);
            bb.writeLog("secCategoryid:"+seccategoryid);
            bb.writeLog("docextendname:"+docextendname);
            bb.writeLog("doccreaterid:"+doccreaterid);



            //   String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
            String filetype =".pdf";

         /*   int  filepathlength=  filerealpath.split("\\.").length;
            if(filepathlength>0){
                //获取附件的后缀名
                filetype= "."+filerealpath.split("\\.")[filepathlength-1];
            }*/
            String[] valuesplit=  filerealpath.split("/");
            String filerealpathvalue=  filerealpath.replace(valuesplit[valuesplit.length-1],"");
            String realpath=filerealpathvalue+ JAVATools.getuuid();


            bb.writeLog("filetype:"+filetype);
            bb.writeLog("realpath:"+realpath);
            bb.writeLog("filepath:"+filerealpath);
            if(imagefilename.indexOf(".")>0){
                imagefilename = imagefilename.substring(0,imagefilename.lastIndexOf("."))+filetype;
            }



            //imagefilename.split("\\.")[0].toString()+"_电子用印件"+filetype;
            bb.writeLog("imagefilename:"+imagefilename);
            boolean istrue = true;

            try {
                realfilepath = zwpdfimagefiletorealfile(oldimagefileid,realpath,docid+filetype);
                bb.writeLog("realfilepath:"+realfilepath);
                // InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                if("".equals(realfilepath)){
                    istrue = false;
                }
                              /*  File realfile = new File(realfilepath);
                if(!realfile.exists())
                {
                    istrue = false;
                }*/
            }catch (Exception e){
                JAVATools.SetCmdwritelog("附件转正文失败:");
                bb.writeLog(e);
                istrue = false;
            }
            if(istrue)
            {
                try{
                    String content = "";
                    newdocid = createDoc(imagefilename,content,Util.getIntValue(doccreaterid),pubtime,maincategoryid,subcategoryid,seccategoryid,Util.getIntValue(doctype),docextendname,"");
                    bb.writeLog("newdocid:"+newdocid);

                    ImageFileIdUpdate im = new ImageFileIdUpdate();
                    imagefileid = im.getImageFileNewId();
                    bb.writeLog("imagefileid:"+imagefileid);

                    sql= " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                            " values("+imagefileid+",'"+imagefilename+"','"+imagefiletype+"',1,'"+realfilepath+"',0,0,'"+filesize+"')";
                    rs.execute(sql);

                    DocImageManager dm = new DocImageManager();
                    VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                    int versionid = versionIdUpdate.getVersionNewId();
                    sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid)"+
                            " values("+dm.getNextDocImageFileId()+","+newdocid+","+imagefileid+",'"+imagefilename+"','0','0','1','0','"+docfiletype+"',"+versionid+")";
                    rs.execute(sql);

                    sql = " select count(1) as cou from DocImageFile where docid="+newdocid;
                    rs.execute(sql);
                    rs.next();
                    int count = Util.getIntValue(Util.null2String(rs.getString("cou")));

                    sql = " update docdetail set accessorycount="+count+" where id="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                }catch (Exception e){
                    bb.writeLog("e1:"+e);
                }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        map.put("newdocid",String.valueOf(newdocid));
        map.put("newimagefileid",String.valueOf(imagefileid));
        map.put("imagefilename",imagefilename);
        map.put("realfilepath",realfilepath);
        return map;
    }

    public String zwpdfimagefiletorealfile(String imagefileid,String topath,String filename)
    {
        System.out.println("正文转附件落地开始");
        System.out.println("imagefileid：" + imagefileid + "topath:" + topath + "filename:" + filename);
        BaseBean bb = new BaseBean();

        String filerepathpath = "";
        bb.writeLog("fileCopy");
        if("".equals(imagefileid) || "".equals(topath) || "".equals(filename)){
            return filerepathpath;
        }

        InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            bb.writeLog("topath:"+topath);
            File saveDir = new File(topath);
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            Runtime.getRuntime().exec("chmod -R 777 " + topath);


            String path = topath+"/"+filename;//创建文件
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            Runtime.getRuntime().exec("chmod -R 777 " + path);

            int index;
            byte[] bytes = new byte[1024];

            FileOutputStream uploadFile = new FileOutputStream(file);
            while ((index = inputstream.read(bytes)) != -1) {
                uploadFile.write(bytes, 0, index);
                uploadFile.flush();
            }
            inputstream.close();
            uploadFile.close();
            Runtime.getRuntime().exec("chmod -R 777 " + topath);
            filerepathpath = path;
            bb.writeLog("path:"+path);
            System.out.println("正文转附件落地结束");

        }catch (IOException e){
            bb.writeLog("e222:"+e);
        }finally{
            try{
                if(sourceChannel !=null){
                    sourceChannel.close();
                }
            }catch (IOException e){
                bb.writeLog("e33:"+e);
            }

            try{
                if(destChannel !=null){
                    destChannel.close();
                }
            }catch (IOException e){
                bb.writeLog("e33:"+e);
            }
        }
        return filerepathpath;
    }

    /***
     *
     * @param docid
     * @param filepath
     * @param realpath
     * @return
     */
    public int uploadFileByPath(String docid,String filepath,String realpath,String filename)
    {
        BaseBean bb = new BaseBean();
        bb.writeLog("uploadFileByPath");
        bb.writeLog("filepath:"+filepath);
        bb.writeLog("filename:"+filename);
        RecordSet rs = new RecordSet();
        String pubtime = TimeUtil.getCurrentDateString();

        int seccategoryid = 0;
        int maincategoryid = 0;
        int subcategoryid = 0;
        String imagefiletype = "";
        String doccreaterid ="";
        int filesize = 0;
        String doctype = "";

        String sql =" select t.maincategory,t.subcategory,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize,\n" +
                " l.docfiletype,p.imagefiletype,t.doccreaterid \n" +
                " from docdetail t\n" +
                " inner join docimagefile l on l.docid = t.id\n" +
                " inner join imagefile p on p.imagefileid = l.imagefileid\n" +
                " where docid="+docid+" and versionid IN(select max(versionid) from DocImageFile where docid="+docid+" ) ";

        rs.execute(sql);
        if(rs.next()){
            seccategoryid = Util.getIntValue(rs.getString("seccategory"));
            maincategoryid = Util.getIntValue(rs.getString("maincategory"));
            subcategoryid = Util.getIntValue(rs.getString("subcategory"));

            imagefiletype = Util.null2String(rs.getString("imagefiletype"));
            doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            filesize = Util.getIntValue(rs.getString("filesize"));

            doctype = Util.null2String(rs.getString("doctype"));
        }

        int newdocid = 0;
        try {
            bb.writeLog("doccreaterid:"+doccreaterid);
            bb.writeLog("secCategoryid:"+seccategoryid);
            bb.writeLog("doccreaterid:"+doccreaterid);

            if("".equals(filepath)){
                return -1;
            }

            String filename_path = filepath.substring(filepath.lastIndexOf("/")+1);
            bb.writeLog("filename_path:"+filename_path);
            String docextendname = filename_path.substring(filename_path.lastIndexOf(".")+1);

            String docfiletype = "" ;
            if (docextendname.equalsIgnoreCase("doc")) {
                docfiletype = "3";
            } else if (docextendname.equalsIgnoreCase("xls")) {
                docfiletype = "4";
            } else if (docextendname.equalsIgnoreCase("ppt")) {
                docfiletype = "5";
            } else if (docextendname.equalsIgnoreCase("wps")) {
                docfiletype = "6";
            } else if (docextendname.equalsIgnoreCase("docx")) {
                docfiletype = "7";
            } else if (docextendname.equalsIgnoreCase("xlsx")) {
                docfiletype = "8";
            } else if (docextendname.equalsIgnoreCase("pptx")) {
                docfiletype = "9";
            } else {
                docfiletype ="2";
            }

            bb.writeLog("docextendname:"+docextendname);
            bb.writeLog("realpath:"+realpath);
            bb.writeLog("filepath:"+filepath);

            boolean istrue = true;
            String realfilepath = "" ;
            try {
                bb.writeLog(docid+"."+docextendname);
                realfilepath = copyFileByFileStreams(filepath,realpath,docid+"."+docextendname);
                bb.writeLog("realfilepath:"+realfilepath);

                File realfile = new File(realfilepath);
                if(!realfile.exists())
                {
                    istrue = false;
                }
            }catch (Exception e){
                bb.writeLog(e);
                istrue = false;
            }
            if(istrue)
            {
                filename = filename.substring(0,filename.lastIndexOf("."))+"_rms."+docextendname;
                bb.writeLog("filename2:"+filename);
                try{
                    String content = "";
                    newdocid = createDoc(filename,content,Util.getIntValue(doccreaterid),pubtime,maincategoryid,subcategoryid,seccategoryid,Util.getIntValue(doctype),docextendname,"");
                    bb.writeLog("newdocid:"+newdocid);

                    ImageFileIdUpdate im = new ImageFileIdUpdate();
                    int imagefileid = im.getImageFileNewId();
                    bb.writeLog("imagefileid:"+imagefileid);

                    sql=    " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                            " values("+imagefileid+",'"+filename+"','"+imagefiletype+"',1,'"+realfilepath+"',0,0,'"+filesize+"')";
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                    DocImageManager dm = new DocImageManager();
                    VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                    int versionid = versionIdUpdate.getVersionNewId();
                    sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid)"+
                          " values("+dm.getNextDocImageFileId()+","+newdocid+","+imagefileid+",'"+filename+"','0','0','0','0','"+docfiletype+"',"+versionid+")";
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                    sql = " select count(1) as cou from DocImageFile where docid="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);
                    rs.next();
                    int count = Util.getIntValue(Util.null2String(rs.getString("cou")));
                    bb.writeLog("count:"+count);

                    sql = " update docdetail set accessorycount="+count+" where id="+newdocid;
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);

                    bb.writeLog("netpad---------");
                    try{
                        String upload = QC969424Util.getPV("upload");
                        String systemNo = QC969424Util.getPV("systemNo");
                        String url = upload+"/"+systemNo;
                        bb.writeLog("url:"+url);
                        bb.writeLog("imagefilename:"+filename);
                        bb.writeLog("realfilepath:"+realfilepath);
                        QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();
                        File file = new File(realfilepath);
                        InputStream inputStream = new FileInputStream(file);
                        CloseableHttpResponse clresponse= qc.doUpload(url,filename,inputStream);
                        bb.writeLog("clresponse:"+clresponse);

                        int statusCode = clresponse.getStatusLine().getStatusCode();
                        bb.writeLog("statusCode:"+statusCode);
                        if(statusCode == 200)
                        {
                            String res = EntityUtils.toString(clresponse.getEntity());
                            bb.writeLog("res:"+res);
                            if(!"".equals(res)){
                                sql = " update imagefile set fileid=? where imagefileid=?";
                                bb.writeLog(" sql:"+sql+" imagefileid:"+imagefileid);
                                rs.executeUpdate(sql,new Object[]{res,imagefileid});
                            }
                        }
                    }catch (Exception ex){
                        ex.printStackTrace();
                        bb.writeLog("ex:"+ex);
                    }

//                    String var4 = QC969424Util.getPV("upload");
//                    String var5 = QC969424Util.getPV("systemNo");
//                    String url="/syncauth/upload/jtxt_oa";
//                    QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();
//                    File file = new File("D:\\123.docx");
//                    InputStream inputStream = new FileInputStream(file);
//                    CloseableHttpResponse classname= qc.doUpload(url,filename,inputStream);
//                    System.out.println(classname);

                }catch (Exception e){
                    bb.writeLog("e1:"+e);
                }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }
        return newdocid;
    }

    /***
     *
     * @param title
     * @param body
     * @param creater
     * @param rq
     * @param maincategory
     * @param subcategory
     * @param seccategory
     * @param doctype
     * @param docextendname
     * @param tempcomids
     * @return
     * @throws Exception
     */
    public int createDoc(String title,String body,int creater,String rq,int maincategory,int subcategory,int seccategory,int doctype,String docextendname,String tempcomids){
        RecordSet rs = new RecordSet();
        BaseBean bs = new BaseBean();
        try{
            int docLanguage = 7 ;
            int sec = seccategory;
            ResourceComInfo r = new ResourceComInfo();
            int departmentid = Integer.parseInt(r.getDepartmentID(creater+""));
            bs.writeLog("departmentid:"+departmentid);
            SecCategoryComInfo secCategoryComInfo=new SecCategoryComInfo();

            DocComInfo docComInfo=new DocComInfo();
            DocManager docManager=new DocManager();
            DocViewer docViewer=new DocViewer();

            String nowTime= TimeUtil.getOnlyCurrentTimeString();

            String pubishdate = rq;
            String publishtime = nowTime;

            RecordSet recordSet = new RecordSet();
            int newDocId = docManager.getNextDocId(recordSet);

            docManager.setId(newDocId);
            docManager.setDocsubject(title);
            docManager.setMaincategory(maincategory);
            docManager.setSubcategory(subcategory);
            docManager.setSeccategory(sec);
            docManager.setLanguageid(docLanguage);
            docManager.setDocstatus("1");

            docManager.setDoccreaterid(creater);
            docManager.setDocdepartmentid(departmentid);
            docManager.setDocCreaterType("1");
            docManager.setUsertype("1");
            docManager.setOwnerid(creater);
            docManager.setOwnerType("1");
            docManager.setDoclastmoduserid(creater);
            docManager.setDocLastModUserType("1");

            docManager.setDoccreatedate(pubishdate);
            docManager.setDoclastmoddate(pubishdate);
            docManager.setDoccreatetime(publishtime);
            docManager.setDoclastmodtime(publishtime);

            docManager.setDoclangurage(docLanguage);

            docManager.setKeyword(title);
            docManager.setIsapprover("0");
            docManager.setIsreply("");
            docManager.setDocreplyable("1");
            docManager.setAccessorycount(1);
            docManager.setParentids(newDocId+"");
            docManager.setOrderable(secCategoryComInfo.getSecOrderable(seccategory)+"");
            docManager.setUserid(1);

//            DocCoder localDocCoder = new DocCoder();
            docManager.setDocCode("");

            docManager.setDocEditionId(docManager.getNextEditionId(recordSet));
            docManager.setDocEdition(1);

            docManager.setDoccontent(body);
            docManager.setDocType(doctype);

            docManager.setDocextendname(docextendname);
            docManager.AddDocInfo();

            docComInfo.addDocInfoCache("" + newDocId);
            docViewer.setDocShareByDoc("" + newDocId);
            docManager.AddShareInfo();

//            rs.execute("select subcompanyid1 from HrmResource where id="+creater);
//            rs.next();
//            String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
//
//            rs.execute("update docshare set userid="+creater+"  where docid="+newDocId+"  and sharetype in (80,84)");
//
//            String sharesql="insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
//                    " values('"+newDocId+"',1,1,0,1,80,"+creater+",0,1,255)";
//            rs.execute(sharesql);

//            if(!"".equals(subcompanyid1)){
//                sharesql="insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
//                        " values('"+newDocId+"',2,"+subcompanyid1+",0,1,2,"+subcompanyid1+",0,1,255)";
//                rs.execute(sharesql);
//            }
//            if(!"".equals(tempcomids))
//            {
//                String[] tempcomidArray = tempcomids.split(",");
//                for(int i=0;i<tempcomidArray.length;i++)
//                {
//                    int tempcomid = Util.getIntValue(tempcomidArray[i]);
//                    if(tempcomid!=0)
//                    {
//                        sharesql="insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
//                                " values('"+newDocId+"',1,"+tempcomid+",1,1,2,"+tempcomid+",0,0,255)";
//
//
//                        //bs.writeLog("sharesql:"+sharesql);
//                        rs.execute(sharesql);
//                    }else
//                    {
//                        sharesql="insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
//                                " values('"+newDocId+"',5,1,1,1,1,1,0,0,255)";
//                        // bs.writeLog("sharesql:"+sharesql);
//                        rs.execute(sharesql);
//                    }
//                }
//            }
            return newDocId;
        } catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    /***
     *
     * @param frompath
     * @param topath
     * @param filename
     * @return
     * @throws IOException
     */
    public String copyFileUsingChannel(String frompath,String topath,String filename)
    {
        BaseBean bb = new BaseBean();

        String filerepathpath = "";
        bb.writeLog("fileCopy");
        if("".equals(frompath) || "".equals(topath) || "".equals(filename)){
            return filerepathpath;
        }

        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            bb.writeLog("topath:"+topath);
            File saveDir = new File(topath);
            if(!saveDir.exists()){
                saveDir.mkdir();
            }

            bb.writeLog("frompath:"+frompath);
            bb.writeLog("dest:"+topath+"/"+filename);

            File source = new File(frompath);
            File dest = new File(topath+"/"+filename);


            sourceChannel = new FileInputStream(source).getChannel();
            destChannel = new FileOutputStream(dest).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());

            filerepathpath = topath+"/"+filename;
            bb.writeLog("filerepathpath:"+filerepathpath);

            sourceChannel.close();
            destChannel.close();

        }catch (IOException e){
            bb.writeLog("e222:"+e);
        }finally{
            try{
                if(sourceChannel !=null){
                    sourceChannel.close();
                }
            }catch (IOException e){
                bb.writeLog("e33:"+e);
            }

            try{
                if(destChannel !=null){
                    destChannel.close();
                }
            }catch (IOException e){
                bb.writeLog("e33:"+e);
            }
        }
        return filerepathpath;
    }

    /***
     *
     * @param frompath
     * @param topath
     * @param filename
     * @throws IOException
     */
    public String copyFileByFileStreams(String frompath,String topath,String filename){

        BaseBean bb = new BaseBean();
        String filerepathpath = "";
        bb.writeLog("copyFileByFileStreams");
        if("".equals(frompath) || "".equals(topath) || "".equals(filename)){
            return filerepathpath;
        }

        String destpath = "";
        InputStream input = null;
        OutputStream output = null;
        try {
            File saveDir = new File(topath);
            if(!saveDir.exists()){
                saveDir.mkdir();
            }
            bb.writeLog("frompath:"+frompath);
            bb.writeLog("dest:"+topath+"/"+filename);

            File source = new File(frompath);
            destpath = topath+"/"+filename;
            File dest = new File(destpath);
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[8192];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }

            input.close();
            output.close();

        }catch (IOException e){
                bb.writeLog("e:"+e);
        }finally {
            if(input !=null){
                try{
                    input.close();
                }catch (IOException e){
                    bb.writeLog("e2:"+e);
                }
            }

            if(output !=null){
                try{
                    output.close();
                }catch (IOException e){
                    bb.writeLog("e3:"+e);
                }
            }
        }
        return destpath;
    }

}
