package com.engine.htxc.commonutil.fileutil;

import com.engine.htxc.commonutil.db.DbTools;
import com.engine.integration.util.StringUtils;
import com.engine.odoc.util.DocUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.VersionIdUpdate;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424SyncauthRequestUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.general.TimeUtil;
import weaver.general.Util;


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

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName GatewayUtil.java
 * @createTime 2022年06月23日 11:22:00
 * @Reamrk 存储网管相对应的
 */
public class GatewayUtil {

    private static DbTools dbtools=new DbTools();

    public static  String  sendGateway(int imagefileid,String imagefilename){
        String value="";
        if( imagefileid<=0){
            return "";
        }
        Map<String,Object> retmap= getImageFile(Util.null2String(imagefileid));
        String realfilepath= Util.null2String(retmap.get("filerealpath"));
        String iszip= Util.null2String(retmap.get("iszip"));
        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 && !"".equals(realfilepath))
            {
                File file = new File(realfilepath);
                if(!file.exists())
                {
                    throw  new WebApplicationException(404);
                }
                if ("1".equals(iszip)) {
                    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});
                        value=res;
                    }
                }
                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();
            }
        }
    return value;

    }

    public static Map<String,Object> getImageFile(String imagefileid){
     String sql="select * from imagefile where imagefileid=?";
        if(StringUtils.isBlank(imagefileid)){
            return null;
        }
        return new DbTools().getsqltomap(sql,imagefileid);

    }

    public static String getWayToDocId(String fileid,String filename,int olddocid){
        if(StringUtils.isBlank(fileid) || StringUtils.isBlank(filename) || olddocid<0){
            return "";
        }
        int imagefileid=getWayToImageFileId(fileid,filename);
        int newdocid=DocUtil.createDocFromAnother(olddocid);
        if(imagefileid<0 || newdocid<0){
            return "";
        }
       String docextendname="pdf";
        if(filename.split(".").length>0){
            docextendname=filename.split(".")[filename.split(".").length-1];
        }
        VersionIdUpdate versionIdUpdate = new VersionIdUpdate();
        int versionid = versionIdUpdate.getVersionNewId();
        Map<String,Object> docimagefilemap=new HashMap<>(5);
        docimagefilemap.put("docid",newdocid);
        docimagefilemap.put("imagefileid",imagefileid);
        docimagefilemap.put("imagefilename",filename);
        docimagefilemap.put("docextendname",docextendname);
        docimagefilemap.put("versionid",versionid);
        String operatedate = TimeUtil.getCurrentDateString();
        String operatetime =TimeUtil.getOnlyCurrentTimeString();
        docimagefilemap.put("operatedate",operatedate);
        docimagefilemap.put("operatetime",operatetime);
        docimagefilemap.put("uploaddate",operatedate+" "+operatetime);
        FileUtil.createdocimagefile(docimagefilemap);
        //关联操作
        docLinkImageFile(newdocid,imagefileid,filename,fileid);
        return Util.null2String(newdocid);
    }

    public static int getWayToImageFileId(String fileid,String filename){
        int value=-1;
        if(StringUtils.isBlank(fileid) || StringUtils.isBlank(filename)){
            return value;
        }
        String token ="";
        InputStream is=null;
        boolean bool = QC969424Util.openQc969424();
        if (bool) {
           try {
               QC969424RequestBaseUtil qC969424RequestBaseUtil = new QC969424RequestBaseUtil();
               token = QC969424Util.getToken();
               if (token == null || "".equals(token)) {
                   token= qC969424RequestBaseUtil.getToken();
               }
               QC969424SyncauthRequestUtil qC969424SyncauthRequestUtil = new QC969424SyncauthRequestUtil();
               is = qC969424SyncauthRequestUtil.download(fileid);
               if(is!=null){
                   value = DocUtil.saveImageFile(is, filename, "");
                   is.close();
               }

           }catch (Exception e){

           }
        }
        return value;

    }

    private static void docLinkImageFile(int newdocid,int imagefileid,String imagefilename,String fileid){
        if(newdocid<0 || imagefileid<=0 || StringUtils.isBlank(imagefilename) || StringUtils.isBlank(fileid)){
            return ;
        }
        Map<String,String> docset=new HashMap<>(2);
        docset.put("imagefileid",Util.null2String(imagefileid));
        docset.put("imagefilename",imagefilename);
        Map<String,String> docwhere=new HashMap<>(1);
        docwhere.put("docid",Util.null2String(newdocid));
        dbtools.updateSql("docimagefile",docset,docwhere);
        //跟新imagefile
        Map<String,String> imagefileset=new HashMap<>(1);
        imagefileset.put("fileid",fileid);
        Map<String,String> imagefilewhere=new HashMap<>(1);
        imagefilewhere.put("imagefileid",Util.null2String(imagefileid));
        dbtools.updateSql("imagefile",imagefileset,imagefilewhere);
        //跟新docdetail
        Map<String,String> docdetailset=new HashMap<>(1);
        docdetailset.put("doctype","1");
        Map<String,String> docdetailwhere=new HashMap<>(1);
        docdetailwhere.put("id",Util.null2String(newdocid));
        dbtools.updateSql("docdetail",docdetailset,docdetailwhere);
    }

}
