package weaver.docs.docs.AddWater;

import com.engine.doc.util.WaterMarkUtilNew;
import weaver.conn.RecordSet;
import weaver.docs.docs.util.ImageMarkUtil;
import weaver.docs.docs.util.PdfWaterMarkUtil;
import weaver.file.ImageFileManager;
import weaver.file.util.FileDeleteUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.wps.officed.OfficedWatermark;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * author：tongh
 * date：2019-2-28 8:51
 * detail：给下载的各种文档附件添加水印的方法
 */
public class DocAddWaterForSecond extends BaseBean{
    public static final String DOCWATER = "docwater";
    public static final String PDFWATER = "pdfwater";
    public static final String IMGWATER = "imgwater";
	
	private static String s = "0123456789ABCDEF";
    /**
     * 给word文档添加水印
     * @param  inputStream 文档流
     * @param user  用户对象
     * @param filename 文件名
     * @return InputStream 加了水印的文件流
     */
    public InputStream docAddWater(InputStream inputStream,User user,String filename){
        return docAddWater(inputStream,user,filename,DOCWATER,-1,"ecology");
    }
    public InputStream docAddWater(InputStream inputStream, User user, String filename, String filetype, int fileid, String fromMould){

        return docAddWater(inputStream,user,filename,filetype,fileid,fromMould,-1,"");
    }
    public InputStream docAddWater(InputStream inputStream, User user, String filename, String filetype, int fileid, String fromMould, int origifileid,String requestid){
        writeLog("DocAddWaterForSecond---docAddWater--start");
        InputStream imagefile=null;
        PdfWaterMarkUtil pdfWaterMarkUtil=null;
        DocAddWaterForSecondNew docAddWaterForSecondNew = new DocAddWaterForSecondNew();
        String ext="";
        String docsourcepath="";
        String doctargetpath="";
        String watercontent="";
        try{
            pdfWaterMarkUtil=new PdfWaterMarkUtil();
            ext=getFileExt(filename);
            watercontent= WaterMarkUtilNew.getSystemWaterContent(user,origifileid>0?origifileid:fileid,fromMould,requestid);
            if(fileid>0&&"".equals(watercontent)){
                Map<String,Object> waterMap  =  WaterMarkUtilNew.getWmSettingByFileid(user,origifileid>0?origifileid:fileid,requestid);
                watercontent = Util.null2String(waterMap.get("wmcontent"));
                watercontent = (watercontent.startsWith("&watermark_txt=") || watercontent.startsWith("?watermark_txt=")) ? watercontent.substring(15) : watercontent;
            }
            Boolean result = false;

            if(WaterMarkUtilNew.getwmTypeByFileid(origifileid>0?origifileid:fileid).equals("text")){
                if(PDFWATER.equals(filetype) || IMGWATER.equals(filetype)){
                    watercontent = watercontent.replaceAll("\\n","\\\r\\\n");
                }
                return docAddWaterForSecondNew.docAddTextWaterForYozo(inputStream,user,filename,filetype,watercontent,origifileid>0?origifileid:fileid,requestid);
            }else{
                return docAddWaterForSecondNew.docAddPicWaterForYozo(inputStream,user,filename,filetype,origifileid>0?origifileid:fileid);
            }
        }catch(Exception e){
            writeLog("docAddWater--------------error="+e);
        }
        writeLog("DocAddWaterForSecond---docAddWater--end");
        return imagefile;
    }
    
    public String ConvertHexToRGB(String hex){
        String rgb = "";
        String regex = "^[0-9A-F]{3}|[0-9A-F]{6}$";
        if (hex != null) {
            hex = hex.toUpperCase();
            if (hex.substring(0, 1).equals("#")) {
                hex = hex.substring(1);
            }
            if (Pattern.compile(regex).matcher(hex).matches()) {
                String a, c, d;
                String[] str = new String[3];
                for (int i = 0; i < 3; i++) {
                    a = hex.length() == 6 ? hex.substring(i * 2, i * 2 + 2) : hex.substring(i, i + 1) + hex.substring(i, i + 1);
                    c = a.substring(0, 1);
                    d = a.substring(1, 2);
                    str[i] = String.valueOf(s.indexOf(c) * 16 + s.indexOf(d));
                }
                rgb = str[0] + "," + str[1] + "," + str[2];
            }
        }
        return rgb;

    }
    public InputStream docAddWaterForWps(int fileid, User user, String filename, String fromMould, int originfileid,String requestid){
    	try{
    		
    		String doctype = "";
	        if(filename.toLowerCase().endsWith(".pdf")){
	        	doctype = OfficedWatermark.WATER_TYPE_PDF;
	        }else if(filename.toLowerCase().endsWith(".doc") || filename.toLowerCase().endsWith(".docx")){
	        	doctype = OfficedWatermark.WATER_TYPE_WORD;
	        }
    		 if(WaterMarkUtilNew.getwmTypeByFileid(originfileid>0?originfileid:fileid).equals("text")){
                 String watercontent= WaterMarkUtilNew.getSystemWaterContent(user,originfileid>0?originfileid:fileid,fromMould,requestid);
                 
                 OfficedWatermark warterMark = new OfficedWatermark();
                 Map<String,Object> fontParams = WaterMarkUtilNew.getWmSettingByFileid(user,originfileid>0?originfileid:fileid,requestid);
                 fontParams.put("fromMould",fromMould);
                 Map<String, Object> extraParam = new HashMap<String, Object>();
                 extraParam.put("user", user);
                 extraParam.put("fromMould", fromMould);
                 extraParam.put("originfileid", originfileid);
                 extraParam.put("requestid", requestid);
                 if(weaver.wps.doccenter.utils.Config.isWpsDocCenterOpen()) {
                     Map<String, Object> params = new HashMap<String, Object>();
                     weaver.wps.doccenter.impl.DocWaterMark docWaterMark = new weaver.wps.doccenter.impl.DocWaterMark();

                     return docWaterMark.addWatermarkByText(fileid,filename,doctype,watercontent,fontParams, extraParam);
                 }
                 if(OfficedWatermark.WATER_TYPE_PDF == doctype){
		        	return warterMark.addWaterInputStream(fileid,filename,doctype,watercontent,fontParams,extraParam);
                 }
                 InputStream is = warterMark.addWaterInputStream(fileid,filename,doctype,watercontent,fontParams,extraParam);
                 return is;
    		 }else{
    		     int imageid = Util.getIntValue(WaterMarkUtilNew.getwmImgFileidByFileid(user,originfileid>0?originfileid:fileid));
    		     OfficedWatermark warterMark = new OfficedWatermark();
    		     Map<String,Object> imgParams = WaterMarkUtilNew.getWmSettingByFileid(user,originfileid>0?originfileid:fileid,requestid);
                 Map<String, Object> extraParam = new HashMap<String, Object>();
                 extraParam.put("user", user);
                 extraParam.put("fromMould", fromMould);
                 if(weaver.wps.doccenter.utils.Config.isWpsDocCenterOpen()) {
                     Map<String, Object> params = new HashMap<String, Object>();
                     weaver.wps.doccenter.impl.DocWaterMark docWaterMark = new weaver.wps.doccenter.impl.DocWaterMark();

                     return docWaterMark.addWatermarkByImage(fileid,filename,doctype,imageid,imgParams, extraParam);
                 }
                 imgParams.put("fromMould",fromMould);
                 InputStream is = warterMark.addImgWaterInputStream(fileid,filename,doctype,imageid,imgParams,extraParam);
                 return is;
    		 }
    	}catch(Exception e){
    		 writeLog("docAddWaterForWps--------------error="+e);
    	}
    	return null;
    }
    public InputStream docAddWaterForWps(int fileid, User user, String filename, String fromMould){
        return docAddWaterForWps(fileid,user,filename,fromMould,-1,"");
    }
    /**
     * 给pdf文档添加水印
     * @param
     * @param user  用户对象
     * @param filename 文件名
     * @param fileid 文件id
     * @param fromMould 文件来源 ecology 文档附件/email 邮件附件
     * @return InputStream 加了水印的文件流
     */
    public InputStream pdfAddWater(InputStream inputStream, User user, String filename, int fileid, String fromMould){
        return pdfAddWater(inputStream,user,filename,fileid,fromMould,-1,"");
    }
    public InputStream pdfAddWater(InputStream inputStream, User user, String filename, int fileid, String fromMould, int originfileid,String requestid){
        writeLog("DocAddWaterForSecond---pdfAddWater--start");
        InputStream imagefile=null;
        PdfWaterMarkUtil pdfWaterMarkUtil=null;
        String ext="";
        String docsourcepath="";
        String doctargetpath="";
        String watercontent="";
        try{
            pdfWaterMarkUtil=new PdfWaterMarkUtil();
            ext=getFileExt(filename);
            docsourcepath=pdfWaterMarkUtil.getWaterPdfPath("."+ext);
            doctargetpath=pdfWaterMarkUtil.getWaterPdfPath("."+ext);
            watercontent= WaterMarkUtilNew.getSystemWaterContent(user,originfileid>0?originfileid:fileid,fromMould,requestid);

            if(fileid>0&&"".equals(watercontent)){
                Map<String,Object> waterMap  =  WaterMarkUtilNew.getWmSettingByFileid(user,originfileid>0?originfileid:fileid,requestid);
               
                watercontent = Util.null2String(waterMap.get("wmcontent"));
                watercontent = (watercontent.startsWith("&watermark_txt=") || watercontent.startsWith("?watermark_txt=")) ? watercontent.substring(15) : watercontent;
            }
            pdfWaterMarkUtil.writeToLocal(docsourcepath, inputStream);
            writeLog("pdfAddWater--------------filename="+filename);
            writeLog("pdfAddWater--------------watercontent="+watercontent);
            writeLog("pdfAddWater--------------docsourcepath="+docsourcepath);
            writeLog("pdfAddWater--------------doctargetpath="+doctargetpath);
            try{
//                watercontent = RichTextUtil.getContent(watercontent);
                writeLog("DocAddWaterForSecond-->filename--->"+filename+"WaterMarkUtilNew.getwmTypeByFileid(fileid)101", WaterMarkUtilNew.getwmType());
                if(WaterMarkUtilNew.getwmTypeByFileid(originfileid>0?originfileid:fileid).equals("text")){
                    PdfWaterMarkUtil.addSystemWater(docsourcepath, doctargetpath, watercontent,user,originfileid>0?originfileid:fileid,requestid);
                }else{
                    String imagepath = WaterMarkUtilNew.getFilePath(WaterMarkUtilNew.getwmImgFileidByFileid(user,originfileid>0?originfileid:fileid));
                    writeLog("DocAddWaterForSecond-->filename--->"+filename+"imagepath106",imagepath);
                    pdfWaterMarkUtil.addimgWatermark(docsourcepath, doctargetpath, watercontent,imagepath,user,originfileid>0?originfileid:fileid);
                }

                imagefile = new FileInputStream(new File(doctargetpath));
            }catch(Exception e){
                String error = e.getMessage();
                imagefile = new FileInputStream(new File(docsourcepath));
            }
        }catch(Exception e){
            writeLog("pdfAddWater--------------error="+e);
        }
        writeLog("DocAddWaterForSecond---pdfAddWater--end");
        return imagefile;
    }
    /**
     * 给图片添加水印
     * @param inputStream  文档流
     * @param user  用户对象
     * @param filename 文件名
     * @return InputStream 加了水印的文件流
     */
    public InputStream imgAddWater(InputStream inputStream,User user,String filename,int fileid,String fromMould,String requestid){
        writeLog("DocAddWaterForSecond---imgAddWater--start");
        InputStream imagefile=null;
        PdfWaterMarkUtil pdfWaterMarkUtil=null;
        String ext="";
        String docsourcepath="";
        String doctargetpath="";
        String watercontent="";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try{
            pdfWaterMarkUtil=new PdfWaterMarkUtil();
            ext=getFileExt(filename);
            docsourcepath=pdfWaterMarkUtil.getWaterPdfPath("."+ext);
            doctargetpath=pdfWaterMarkUtil.getWaterPdfPath("."+ext);
            watercontent=WaterMarkUtilNew.getSystemWaterContent(user,fileid,fromMould,requestid);
            if(fileid>0&&"".equals(watercontent)){
                Map<String,Object> waterMap  =  WaterMarkUtilNew.getWmSettingByFileid(user,fileid,requestid);
                watercontent = Util.null2String(waterMap.get("wmcontent"));
                watercontent = (watercontent.startsWith("&watermark_txt=") || watercontent.startsWith("?watermark_txt=")) ? watercontent.substring(15) : watercontent;
            }
            outputStream = ImageMarkUtil.getOutputStream(inputStream);
            InputStream inputStream1 = new ByteArrayInputStream(outputStream.toByteArray());
            InputStream inputStream2 = new ByteArrayInputStream(outputStream.toByteArray());
            pdfWaterMarkUtil.writeToLocal(docsourcepath, inputStream1);
            writeLog("imgAddWater--------------filename="+filename);
            writeLog("imgAddWater--------------watercontent="+watercontent);
//            watercontent = RichTextUtil.getContent(watercontent);
            File image = null;
            try{
                writeLog("DocAddWaterForSecond-->filename--->"+filename+"WaterMarkUtilNew.getwmTypeByFileid(fileid)140",WaterMarkUtilNew.getwmTypeByFileid(fileid));

                if(WaterMarkUtilNew.getwmTypeByFileid(fileid).equals("text")){
                    image =ImageMarkUtil.addSystemWaterForPic(inputStream2, watercontent, "."+ext,user,fileid,requestid);
                }else{
                    String imagepath = WaterMarkUtilNew.getFilePath(WaterMarkUtilNew.getwmImgFileidByFileid(user,fileid));
                    writeLog("DocAddWaterForSecond-->filename--->"+filename+"145",filename);
                    image = ImageMarkUtil.addSystemImgwmForPic(inputStream2,imagepath,"."+ext,user,fileid);
                }
                imagefile = new FileInputStream(image);
            }catch(Exception e){
                String error = e.getMessage();
                imagefile = new FileInputStream(new File(docsourcepath));
            }
        }catch(Exception e){
            writeLog("imgAddWater--------------error="+e);
        }finally {
            try {
                outputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //FileSecurityUtil.deleteFile(docsourcepath);
        new FileDeleteUtil().deleteFile(docsourcepath);

        writeLog("DocAddWaterForSecond---imgAddWater--end");
        return imagefile;
    }


    public int getDocImagefileIdByDocid(String docid){
        int imagefileid=0;
        String zwflag="1";
        RecordSet rs = new RecordSet();
        String sql="select * from docdetail where id="+docid;
        rs.executeSql(sql);
        if(rs.next()){
            zwflag=Util.null2String(rs.getString("doctype"));
            if(zwflag.isEmpty()){
                zwflag="1";
            }
        }
        sql="select * from DocImageFile  where  docfiletype <> '1'  and docid ="+docid;
        if("1".equals(zwflag)){
            sql+=" and isextfile = '1' ";
        }else{
            sql+=" and (isextfile <> '1' or isextfile is null) ";
        }
        sql+=" order by id, versionId desc ";
        rs.executeSql(sql);
        if(rs.next()){
            imagefileid=Util.getIntValue(rs.getString("imagefileid"),0);
        }
        return imagefileid;
    }
    public int saveImageFile(InputStream inputStream,String fileName,String comefrom){
        ByteArrayOutputStream bos = null;
        try{
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            ImageFileManager imageFileManager=new ImageFileManager();
            imageFileManager.resetParameter();
            imageFileManager.setImagFileName(fileName);
            imageFileManager.setComefrom(comefrom);
            imageFileManager.setData(bos.toByteArray());
            return imageFileManager.saveImageFile();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally
        {
            if(inputStream != null)
            {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos != null)
            {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }
    public InputStream getInputStreamByImagefileId(int  imagefileid){
        InputStream inputStream=null;
        if(imagefileid>0){
            ImageFileManager imageFileManager=new ImageFileManager();
            imageFileManager.getImageFileInfoById(imagefileid);
            inputStream = imageFileManager.getInputStream();
        }
        return inputStream;
    }
    /**
     * 得到文档的扩展名
     *
     * @param file 文档全名
     * @return 文档的扩展名
     */
    public String getFileExt(String file) {
        if (file == null || file.trim().equals("")) {
            return "";
        } else {
            int idx = file.lastIndexOf(".");
            if (idx == -1) {
                return "";
            } else {
                if (idx + 1 >= file.length()) {
                    return "";
                } else {
                    return file.substring(idx + 1);
                }
            }
        }
    }
    public boolean isWaterOpenForPreview(int docid){
        boolean flag = false;
        RecordSet rs=new RecordSet();
        try{
            String sql="SELECT iswateropenforpreview FROM docseccategory where id=(select seccategory from docdetail where id="+docid+")";
            rs.execute(sql);
            int	iswateropen=0;
            if(rs.next()){
                iswateropen=Util.getIntValue(rs.getString("iswateropenforpreview"),0);
            }
            if(iswateropen==1){
                flag=true;
            }
        }catch(Exception e){
        }
        return flag;
    }
    public boolean isWaterOpenForPreview(String fileid){
        boolean flag = false;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.executeSql("select d1.seccategory from docdetail d1,docimagefile d2 where d1.id =d2.docid and d2.imagefileid = "+fileid);
        if(rs.next()){
            String seccategory = rs.getString("seccategory");
            rs1.executeSql("select iswateropenforpreview from docseccategory where id ="+seccategory);
            if(rs1.next()){
                String iswateropen = rs1.getString("iswateropenforpreview");
                if("1".equals(iswateropen)){
                    flag = true;
                }
            }
        }
        if(!flag){
            try{
                int  imagefileid = 0;
                rs.executeSql("select imagefileid from pdf_imagefile where pdfimagefileid = "+fileid);
                if(rs.next()){
                    imagefileid = rs.getInt("imagefileid");
                }
                if(imagefileid != 0){
                    return isWaterOpenForPreview(imagefileid+"");
                }
            }catch(Exception e){
            }
        }
        return flag;
    }
    public boolean isWaterOpenForImg(int docid){
        boolean flag = false;
        RecordSet rs=new RecordSet();
        try{
            String sql="SELECT iswateropenforimg FROM docseccategory where id=(select seccategory from docdetail where id="+docid+")";
            rs.execute(sql);
            int	iswateropen=0;
            if(rs.next()){
                iswateropen=Util.getIntValue(rs.getString("iswateropenforimg"),0);
            }
            if(iswateropen==1){
                flag=true;
            }
        }catch(Exception e){
        }
        return flag;
    }
    public boolean isWaterOpenForImg(String fileid){
        boolean flag = false;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.executeSql("select d1.seccategory from docdetail d1,docimagefile d2 where d1.id =d2.docid and d2.imagefileid = "+fileid);
        if(rs.next()){
            String seccategory = rs.getString("seccategory");
            rs1.executeSql("select iswateropenforimg from docseccategory where id ="+seccategory);
            if(rs1.next()){
                String iswateropen = rs1.getString("iswateropenforimg");
                if("1".equals(iswateropen)){
                    flag = true;
                }
            }
        }
        return flag;
    }
    public boolean isWaterOpenForDownload(int docid){
        boolean flag = false;
        RecordSet rs=new RecordSet();
        try{
            String sql="SELECT iswateropenfordownload FROM docseccategory where id=(select seccategory from docdetail where id="+docid+")";
            rs.execute(sql);
            int	iswateropen=0;
            if(rs.next()){
                iswateropen=Util.getIntValue(rs.getString("iswateropenfordownload"),0);
            }
            if(iswateropen==1){
                flag=true;
            }
        }catch(Exception e){
        }
        return flag;
    }
    public boolean isWaterOpenForDownload(String fileid){
        boolean flag = false;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.executeSql("select d1.seccategory from docdetail d1,docimagefile d2 where d1.id =d2.docid and d2.imagefileid = "+fileid);
        if(rs.next()){
            String seccategory = rs.getString("seccategory");
            rs1.executeSql("select iswateropenfordownload from docseccategory where id ="+seccategory);
            if(rs1.next()){
                String iswateropen = rs1.getString("iswateropenfordownload");
                if("1".equals(iswateropen)){
                    flag = true;
                }
            }
        }
        if(!flag){
            try{
                int  imagefileid = 0;
                rs.executeSql("select imagefileid from pdf_imagefile where pdfimagefileid = "+fileid);
                if(rs.next()){
                    imagefileid = rs.getInt("imagefileid");
                }
                if(imagefileid != 0){
                    return isWaterOpenForDownload(imagefileid+"");
                }
            }catch(Exception e){
            }
        }
        return flag;
    }
}