package com.engine.htsc.doc.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.VersionIdUpdate;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.htsc.util.UploadDocUtil;
import weaver.interfaces.htsc.wpscenter.impl.ConvertDocToOfd;

import javax.ws.rs.WebApplicationException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * 生成OFD文件并关联OA文档
 */
public class DocUtil {

    private static RecordSet rs = new RecordSet();
    private static RecordSetTrans rst = new RecordSetTrans();
    private static BaseBean bb = new BaseBean();

    /**
     * 生成ofd文件
     * @param old_docid
     */
    public static Integer generateFile (int old_docid) {
        Integer newdocid = null;
        try {
            Integer old_imagefileid = null;
            String old_imagefilename = "";
            rs.executeQuery("select a.IMAGEFILEID,a.IMAGEFILENAME from IMAGEFILE a ,DOCIMAGEFILE b where\n" +
                    "a.IMAGEFILEID = b.IMAGEFILEID and b.DOCID = ?",old_docid);
            if (rs.next()) {
                old_imagefileid = Util.getIntValue(rs.getString("IMAGEFILEID"));
                old_imagefilename = Util.null2String(rs.getString("IMAGEFILENAME"));
            }

            bb.writeLog("DocUtil docid:"+old_docid+" imagefileid:" +old_imagefileid+ " imagefilename:"+old_imagefilename);

            ConvertDocToOfd convertDocToOfd = new ConvertDocToOfd();
            int imagefileid = convertDocToOfd.convertToOfd(old_imagefileid, old_imagefilename, false);

            if (imagefileid > 0) {
                int maincategory = -1;
                int subcategory = -1;
                int seccategory = -1;
                String docextendname = "ofd" ;
                String imagefilename = "";
                String docfiletype = "";
                String doccreaterid ="";
                String doctype = "";
                String filerealpath = "";
                String iszip = "";

                rs.executeQuery("select imagefilename,imagefiletype,filesize,filerealpath,iszip from ImageFile where imagefileid = ?",imagefileid);
                if(rs.next()){
                    imagefilename = Util.null2String(rs.getString("imagefilename"));
                    filerealpath = Util.null2String(rs.getString("filerealpath"));
                    iszip = Util.null2String(rs.getString("iszip"));

                }

                rs.executeQuery("select maincategory,subcategory,seccategory,doccreaterid,doctype from docdetail " +
                        " where id=?",old_docid);
                if (rs.next()) {
                    maincategory = Util.getIntValue(rs.getString("maincategory"));
                    subcategory = Util.getIntValue(rs.getString("subcategory"));
                    seccategory = Util.getIntValue(rs.getString("seccategory"));
                    doccreaterid = Util.null2String(rs.getString("doccreaterid"));
                    doctype = Util.null2String(rs.getString("doctype"));
                }

                //1.docdetail生成数据
                String content = "";
                String pubtime = TimeUtil.getCurrentDateString();
                String operatetime = TimeUtil.getOnlyCurrentTimeString();
                newdocid = new UploadDocUtil().createDoc(imagefilename,content,
                        Util.getIntValue(doccreaterid),pubtime,maincategory,subcategory,seccategory,
                        Util.getIntValue(doctype),docextendname,"");
                DocImageManager dm = new DocImageManager();
                VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

                int versionid = versionIdUpdate.getVersionNewId();
                String sql = " insert into DocImageFile " +
                        "(id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight," +
                        "isextfile,imagefielsize,docfiletype,versionid,operateuserid,operatedate,operatetime)"+
                        " values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                rst.executeUpdate(sql,new Object[]{dm.getNextDocImageFileId(),newdocid,imagefileid,imagefilename,
                        0,0,0,0,docfiletype,versionid,doccreaterid,pubtime,operatetime});

                //2.更新附件个数
                rst.executeUpdate("update docdetail set accessorycount = (select count(1) from DocImageFile where docid = ?) where id = ?",new  Object[]{newdocid,newdocid});

                rst.commit();
                //3.上传网关
                callbackgateway(imagefileid,imagefilename,filerealpath,iszip);
            }

        }catch (Exception e) {
            bb.writeLog("吞掉异常 不影响原业务");
            rst.rollback();
            e.getMessage();
            e.printStackTrace();
        }
        return newdocid;
    }

    /**
     * 上传网关
     * @param imagefileid
     * @param imagefilename
     * @param realfilepath
     */
    public static void  callbackgateway(int imagefileid,String imagefilename,String realfilepath,String iszip){

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        CloseableHttpResponse clresponse=null;
        InputStream inputStream = null;
        ZipInputStream zipInputStream = null;
        try{
            String upload = QC969424Util.getPV("upload");
            String systemNo = QC969424Util.getPV("systemNo");
            String url = upload+"/"+systemNo;
            QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();
            if (realfilepath != null && !realfilepath.equals(""))
            {
                File file = new File(realfilepath);
                if(!file.exists())
                {
                    throw  new WebApplicationException(404);
                }
                if (iszip.equals("1")) {
                    zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        inputStream = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                }

                clresponse= qc.doUpload(url,imagefilename,inputStream);
                int statusCode = clresponse.getStatusLine().getStatusCode();
                if(statusCode == 200)
                {
                    String res = EntityUtils.toString(clresponse.getEntity());
                    if(!"".equals(res)){
                        String sql = " update imagefile set fileid=? where imagefileid=?";
                        rs.executeUpdate(sql,new Object[]{res,imagefileid});
                    }
                }
                zipInputStream.close();
                inputStream.close();;
                //释放链接
                clresponse.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream !=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(clresponse !=null){
                    clresponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }





}
