package weaver.docs.docs.util;

import com.api.doc.detail.util.ImageConvertUtil;
import com.engine.doc.util.WaterMarkUtil;
import com.engine.doc.util.WaterMarkUtilNew;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import weaver.docs.docs.AddWater.DocAddWaterForSecond;
import weaver.docs.pdf.docpreview.ConvertorPool;
import weaver.docs.pdf.docpreview.ConvertorPool.ConvertorObject;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;


/**
 * author：tongh
 * date：2019-3-11 9:25
 * detail：
 */
public class DocWaterMarkForYZUtil extends BaseBean {

    public boolean addWaterMark(String sourceFileName, String targetFileName, String watercontent, User user) {
        return addWaterMark(sourceFileName, targetFileName, watercontent, user, "", null, -1, -1,"");
    }

    public boolean addWaterMark(String sourceFileName, String targetFileName, String watercontent, User user, String type, Map<String, String> params) {
        return addWaterMark(sourceFileName, targetFileName, watercontent, user, type, params, -1, -1,"");
    }

    public boolean addWaterMark(String sourceFileName, String targetFileName, String watercontent, User user, String type, Map<String, String> params, int picid, int fileid,String requestid) {
//        writeLog("DocWaterMarkForYZUtil-------------addWaterMark-------start");
//        writeLog("DocWaterMarkForYZUtil-------------sourceFileName="+sourceFileName);
//        writeLog("DocWaterMarkForYZUtil-------------targetFileName="+targetFileName);
//        writeLog("DocWaterMarkForYZUtil-------------watercontent="+watercontent);
        String filetype = DocAddWaterForSecond.DOCWATER;
        String extname = "";
        if (params != null) {
            filetype = Util.null2s(params.get("filetype"), DocAddWaterForSecond.DOCWATER);
            extname = Util.null2s(params.get("extname"), "");
        }
        boolean result = false;
        ConvertorPool instance = null;
        ConvertorObject convert = null;
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isconvert", "1");
        resultMap.put("document", "document");
        Map<String, Object> wmSettingMap = WaterMarkUtil.getWmSetting(resultMap, user);
        Map<String, Object> wmSetting = (Map<String, Object>) wmSettingMap.get("wmSetting");
        if (fileid > 0) {
            wmSetting = WaterMarkUtilNew.getWmSettingByFileid(user,fileid,requestid);
        }


        String opacitystr = Util.null2String(wmSetting.get("yozo_transparency"));
        String rotatestr = Util.null2String(wmSetting.get("yozo_rotate"));

        String family = Util.null2String((String) wmSetting.get("yozo_fontname"), "Microsoft YaHei");
        String fontsizestr = Util.null2String(wmSetting.get("yozo_fontsize"));
        String spacestr = Util.null2String(wmSetting.get("yozo_space"));
        String color = Util.null2String(wmSetting.get("yozo_color"));


        float opacity = Util.getFloatValue(opacitystr, 1);
        int rotate = Util.getIntValue(rotatestr, 20);
        int fontsize = Util.getIntValue(fontsizestr, 50);

        try {
            File sourceFile = new File(sourceFileName);
            if (sourceFile.exists() && sourceFile.isFile()) {
                String wordwaterFont = family;
                //设置水印颜色
                String waterColor = "";
                try {
                    waterColor = WaterMarkUtil.stringtoRGB(color);
                    waterColor = new String(waterColor.getBytes("ISO-8859-1"), "UTF-8");
                } catch (Exception e) {
                    waterColor = "128,128,128";
                }
                int r = 128;
                int g = 128;
                int b = 128;
                if (!"".equals(waterColor) && waterColor.indexOf(",") > 0) {
                    String[] colorarray = waterColor.split(",");
                    if (colorarray != null && colorarray.length >= 3) {
                        r = Util.getIntValue(colorarray[0]);
                        g = Util.getIntValue(colorarray[1]);
                        b = Util.getIntValue(colorarray[2]);
                    }
                }

                //水印字体大小
                int wordwaterFontSize = fontsize;
                if (wmSetting.containsKey("yozo_fontsize")) {
                    wordwaterFontSize = Util.getIntValue(Util.null2String(wmSetting.get("yozo_fontsize")));
                }
                //水印间距
                int wordwmSpace = Util.getIntValue(spacestr, 50);
                //水印透明度
                float wmTransparency = (float) opacity / 100F;
                if (wmSetting.containsKey("yozo_transparency")) {
                    wmTransparency = Util.getFloatValue(Util.null2String(wmSetting.get("yozo_transparency")));
                }
                //水印内容显示在上边还是下边，0表示下边，1表示上边
                int wordwaterShowLevel = Util.getIntValue(getPropValue("PdfWaterMarkSet", "wordwaterShowLevel"), 1);
                if (wmSetting.containsKey("yozo_suspend")) {
                    wordwaterShowLevel = Util.getIntValue(Util.null2String(wmSetting.get("yozo_suspend")));
                }

                //水印倾斜度
                int wordwaterGradient = rotate;
                //水印内容是否平铺,1是平铺,0是不平铺(循环展示)
                int wmTileEffect = Util.getIntValue(getPropValue("PdfWaterMarkSet", "wmTileEffect"), 1);
                if (wmSetting.containsKey("yozo_tiled")) {
                    wmTileEffect = Util.getIntValue(Util.null2String(wmSetting.get("yozo_tiled")));
                }

                String docdcsurl = Util.null2String(getPropValue("doc_custom_for_weaver", "convert_client_path"));

                if (!docdcsurl.startsWith("http")) {
                    docdcsurl = "http://" + docdcsurl;
                }
                docdcsurl = ImageConvertUtil.getYozoServer(docdcsurl);
                String convertIp = new ImageConvertUtil().getConvertIp();
                if (!convertIp.startsWith("http")) {
                    convertIp = "http://" + convertIp;
                }
                convertIp = ImageConvertUtil.getYozoServer(convertIp);
                docdcsurl += "/upload";
                String dcsresult = "";
                String dcsUrl = "";
                String wmPicPath = "";
                String imgStream ="";
                JSONObject json = null;
                if (!"".equals(docdcsurl) && docdcsurl != null) {
                    Map<String, String> param = new HashMap<String, String>();
                    if ("docx".equals(extname)) {
                        param.put("imageType", "docx");
                    }
                    switch (filetype) {
                        case DocAddWaterForSecond.DOCWATER:
                            param.put("convertType", "33");
                            param.put("wmWord", "1");
                            break;
                        case DocAddWaterForSecond.PDFWATER:
                            param.put("convertType", "34");
//                                param.put("wmWord","1");
                            break;
                        case DocAddWaterForSecond.IMGWATER:
                            param.put("convertType", "44");
                            break;
                        default:
                            break;
                    }
                    if (!type.equals("img")) {
                        param.put("wmSize", wordwaterFontSize + "");
                        param.put("wmContent", watercontent);
                        param.put("wmFont", wordwaterFont);
                        param.put("wmSpace", wordwmSpace + "");
                        param.put("wmTransparency", wmTransparency + "");
                        param.put("wmSuspend", wordwaterShowLevel + "");
                        param.put("wmRotate", "-" + wordwaterGradient);
                        param.put("wmRgb", "1");
                        param.put("wmColor", "5");
                        param.put("wmRgbRed", r + "");
                        param.put("wmRgbGreen", g + "");
                        param.put("wmRgbBlue", b + "");
                        param.put("wmTileEffect",wmTileEffect +"");
                    } else {
                        param.put("wmSize", "");
                        param.put("wmContent", "");
                        param.put("wmFont", "");
                        param.put("wmSpace", "");
                        param.put("wmTransparency", wmTransparency + "");
                        param.put("wmSuspend", "1");
                        param.put("wmRotate", "");
                        param.put("wmRgb", "1");
                        param.put("wmRgbRed", "");
                        param.put("wmRgbGreen", "");
                        param.put("wmRgbBlue", "");
                        param.put("wmColor", "");
                        param.put("wmTileEffect", "");
                        param.put("wmX", "250");
                        param.put("wmY", "400");
                        ServletOutputStream out = null;
                        FileInputStream ips = null;
                        if (picid <= 0) {
                            picid = Util.getIntValue(Util.null2String(wmSetting.get("imageid")));
                        }
                        String imagepath = WaterMarkUtil.getFilePath(picid + "");
                        try{
                            if(!"".equals(imagepath)){
                                String yozowaterimgpath=uploadFile(ImageConvertUtil.getYozoServer(convertIp)+"/testUpload",imagepath);
                                writeLog("DocWaterMarkForYZUtil--yozowaterimgpath="+yozowaterimgpath+";docdcsurl="+docdcsurl+";docuploaddcsurl="+ImageConvertUtil.getYozoServer(convertIp)+"/testUpload");
                                if(!"".equals(yozowaterimgpath)){
                                    wmPicPath=yozowaterimgpath;
                                }else{
                                    File codepathFile = new File(imagepath);
                                    if(codepathFile.exists() && codepathFile.isFile()){
                                        imgStream=getFileBase64(new FileInputStream(codepathFile));
                                    }
                                }

                            }
                        }catch(Exception e){
                            writeLog("DocWaterMarkForYZUtil--get---wmImage---error="+e);
                        }
                        param.put("wmImage", imgStream);
                        param.put("wmPicPath", wmPicPath);

                    }

                    writeLog("DocWaterMarkForYZUtil--param=" + param);

                    dcsUrl = submitToDCS(docdcsurl, sourceFileName, param, type, params);

                    writeLog("DocWaterMarkForYZUtil--dcsUrl=" + dcsUrl);
                    json = convertV4ToV3Json(new JSONObject(dcsUrl));
                    dcsresult = json.getString("result");
                    JSONArray data = json.getJSONArray("data");
                    dcsUrl = data.get(0).toString();
                    InputStream inputStream = getInputStreamFromDcs(dcsUrl);
                    writeToLocal(targetFileName, inputStream);
                    if ("0".equals(dcsresult)) {
                        result = true;
                    }
                } else {
                    instance = ConvertorPool.getInstance();
                    convert = instance.getConvertor();
                    String rootpath = GCONST.getRootPath();
                    String convertTempPath = rootpath + "filesystem" + File.separatorChar + "docWaterMarkTemp";
                    File tempFile = new File(convertTempPath);
                    if (!tempFile.exists()) {
                        tempFile.mkdir();
                    }
                    convert.convertor.setWordEditable(true);
                    convert.convertor.setWarterMarkForWord(true);
                    convert.convertor.setAutoDeleteTempFiles(true);
                    convert.convertor.insertTextWaterMark(watercontent, wordwaterFont, wordwaterFontSize, new Color(r, g, b), true, true, true, false, false, 150, 0.5f, -45);//后5个参数依次是是否平铺，是否在文字上方，水印间距， 透明度和角度
                    result = convert.convertor.convertMStoOOX(sourceFileName, targetFileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != instance) {
                    instance.returnConvertor(convert);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public boolean addWaterMarkByWmMap(String sourceFileName, String targetFileName, String watercontent, User user, String type, Map<String, String> params, int picid, int fileid,String requestid) {
        String filetype = DocAddWaterForSecond.DOCWATER;
        String extname = "";
        if (params != null) {
            filetype = Util.null2s(params.get("filetype"), DocAddWaterForSecond.DOCWATER);
            extname = Util.null2s(params.get("extname"), "");
        }
        boolean result = false;
        ConvertorPool instance = null;
        ConvertorObject convert = null;
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isconvert", "1");
        resultMap.put("document", "document");
        Map<String, Object> wmSettingMap = WaterMarkUtil.getWmSetting(resultMap, user);
        Map<String, Object> wmSetting = (Map<String, Object>) wmSettingMap.get("wmSetting");
        if (fileid > 0) {
            wmSetting = WaterMarkUtilNew.getWmSettingByFileid(user, fileid,requestid);
        }


        String opacitystr = Util.null2String(wmSetting.get("yozo_transparency"));
        String rotatestr = Util.null2String(wmSetting.get("yozo_rotate"));

        String family = Util.null2String((String) wmSetting.get("yozo_fontname"), "Microsoft YaHei");
        String fontsizestr = Util.null2String(wmSetting.get("yozo_fontsize"));
        String spacestr = Util.null2String(wmSetting.get("yozo_space"));
        String color = Util.null2String(wmSetting.get("yozo_color"));


        float opacity = Util.getFloatValue(opacitystr, 1);
        int rotate = Util.getIntValue(rotatestr, 20);
        int fontsize = Util.getIntValue(fontsizestr, 50);

        try {
            File sourceFile = new File(sourceFileName);
            if (sourceFile.exists() && sourceFile.isFile()) {
                String wordwaterFont = family;
                //设置水印颜色
                String waterColor = "";
                try {
                    waterColor = WaterMarkUtil.stringtoRGB(color);
                    waterColor = new String(waterColor.getBytes("ISO-8859-1"), "UTF-8");
                } catch (Exception e) {
                    waterColor = "128,128,128";
                }
                int r = 128;
                int g = 128;
                int b = 128;
                if (!"".equals(waterColor) && waterColor.indexOf(",") > 0) {
                    String[] colorarray = waterColor.split(",");
                    if (colorarray != null && colorarray.length >= 3) {
                        r = Util.getIntValue(colorarray[0]);
                        g = Util.getIntValue(colorarray[1]);
                        b = Util.getIntValue(colorarray[2]);
                    }
                }

                //水印字体大小
                int wordwaterFontSize = fontsize;
                if (wmSetting.containsKey("yozo_fontsize")) {
                    wordwaterFontSize = Util.getIntValue(Util.null2String(wmSetting.get("yozo_fontsize")));
                }
                //水印间距
                int wordwmSpace = Util.getIntValue(spacestr, 50);
                //水印透明度
                float wmTransparency = (float) opacity / 100F;
                if (wmSetting.containsKey("yozo_transparency")) {
                    wmTransparency = Util.getFloatValue(Util.null2String(wmSetting.get("yozo_transparency")));
                }
                //水印内容显示在上边还是下边，0表示下边，1表示上边
                int wordwaterShowLevel = Util.getIntValue(getPropValue("PdfWaterMarkSet", "wordwaterShowLevel"), 1);
                if (wmSetting.containsKey("yozo_suspend")) {
                    wordwaterShowLevel = Util.getIntValue(Util.null2String(wmSetting.get("yozo_suspend")));
                }

                //水印倾斜度
                int wordwaterGradient = rotate;
                //水印内容是否平铺,1是平铺,0是不平铺(循环展示)
                int wmTileEffect = Util.getIntValue(getPropValue("PdfWaterMarkSet", "wmTileEffect"), 1);
                if (wmSetting.containsKey("yozo_tiled")) {
                    wmTileEffect = Util.getIntValue(Util.null2String(wmSetting.get("yozo_tiled")));
                }

                String docdcsurl = Util.null2String(getPropValue("doc_custom_for_weaver", "convert_client_path"));

                if (!docdcsurl.startsWith("http")) {
                    docdcsurl = "http://" + docdcsurl;
                }
                docdcsurl = ImageConvertUtil.getYozoServer(docdcsurl);

                docdcsurl += "/upload";
                String dcsresult = "";
                String dcsUrl = "";
                String wmPicPath = "";
                String convertIp = new ImageConvertUtil().getConvertIp();
                if (!convertIp.startsWith("http")) {
                    convertIp = "http://" + convertIp;
                }
                convertIp = ImageConvertUtil.getYozoServer(convertIp);
                String imgStream ="";
                JSONObject json = null;
                if (!"".equals(docdcsurl) && docdcsurl != null) {
                    writeLog("DocWaterMarkForYZUtil--docdcsurl=" + docdcsurl);
                    Map<String, String> param = new HashMap<String, String>();
                    if ("docx".equals(extname)) {
                        param.put("imageType", "docx");
                    }
                    switch (filetype) {
                        case DocAddWaterForSecond.DOCWATER:
                            param.put("convertType", "33");
                            param.put("wmWord", "1");
                            break;
                        case DocAddWaterForSecond.PDFWATER:
                            param.put("convertType", "34");
                            break;
                        case DocAddWaterForSecond.IMGWATER:
                            param.put("convertType", "44");
                            break;
                        default:
                            break;
                    }
                    if (!type.equals("img")) {
                        param.put("wmSize", wordwaterFontSize + "");
                        param.put("wmContent", watercontent);
                        param.put("wmFont", wordwaterFont);
                        param.put("wmSpace", wordwmSpace + "");
                        param.put("wmTransparency", wmTransparency + "");
                        param.put("wmSuspend", wordwaterShowLevel + "");
                        param.put("wmRotate", "-" + wordwaterGradient);
                        param.put("wmRgb", "1");
                        param.put("wmRgbRed", r + "");
                        param.put("wmRgbGreen", g + "");
                        param.put("wmRgbBlue", b + "");
                        param.put("wmTileEffect", wmTileEffect + "");
                    } else {
                        param.put("wmSize", "");
                        param.put("wmContent", "");
                        param.put("wmFont", "");
                        param.put("wmSpace", "");
                        param.put("wmTransparency", wmTransparency + "");
                        param.put("wmSuspend", "1");
                        param.put("wmRotate", "");
                        param.put("wmRgb", "1");
                        param.put("wmRgbRed", "");
                        param.put("wmRgbGreen", "");
                        param.put("wmRgbBlue", "");
                        param.put("wmColor", "");
                        param.put("wmTileEffect", "");
                        param.put("wmX", "250");
                        param.put("wmY", "400");
                        ServletOutputStream out = null;
                        FileInputStream ips = null;
                        if (picid <= 0) {
                            picid = Util.getIntValue(Util.null2String(wmSetting.get("imageid")));
                        }
                        String imagepath = WaterMarkUtil.getFilePath(picid + "");
                        try{
                            if(!"".equals(imagepath)){
                                String yozowaterimgpath=uploadFile(ImageConvertUtil.getYozoServer(convertIp)+"/testUpload",imagepath);
                                writeLog("DocWaterMarkForYZUtil--yozowaterimgpath="+yozowaterimgpath+";docdcsurl="+docdcsurl+";docuploaddcsurl="+ImageConvertUtil.getYozoServer(convertIp)+"/testUpload");
                                if(!"".equals(yozowaterimgpath)){
                                    wmPicPath=yozowaterimgpath;
                                }else{
                                    File codepathFile = new File(imagepath);
                                    if(codepathFile.exists() && codepathFile.isFile()){
                                        imgStream=getFileBase64(new FileInputStream(codepathFile));
                                    }
                                }

                            }
                        }catch(Exception e){
                            writeLog("DocWaterMarkForYZUtil--get---wmImage---error="+e);
                        }
                        param.put("wmImage", imgStream);
                        param.put("wmPicPath", wmPicPath);

                    }

                    writeLog("DocWaterMarkForYZUtil--param=" + param);

                    dcsUrl = submitToDCS(docdcsurl, sourceFileName, param, type, params);

                    writeLog("DocWaterMarkForYZUtil--dcsUrl=" + dcsUrl);
                    json =  convertV4ToV3Json(new JSONObject(dcsUrl));
                    dcsresult = json.getString("result");
                    JSONArray data = json.getJSONArray("data");
                    dcsUrl = data.get(0).toString();
                    InputStream inputStream = getInputStreamFromDcs(dcsUrl);
                    writeToLocal(targetFileName, inputStream);
                    if ("0".equals(dcsresult)) {
                        result = true;
                    }
                } else {
                    instance = ConvertorPool.getInstance();
                    convert = instance.getConvertor();
                    String rootpath = GCONST.getRootPath();
                    String convertTempPath = rootpath + "filesystem" + File.separatorChar + "docWaterMarkTemp";
                    File tempFile = new File(convertTempPath);
                    if (!tempFile.exists()) {
                        tempFile.mkdir();
                    }
                    convert.convertor.setWordEditable(true);
                    convert.convertor.setWarterMarkForWord(true);
                    convert.convertor.setAutoDeleteTempFiles(true);
                    convert.convertor.insertTextWaterMark(watercontent, wordwaterFont, wordwaterFontSize, new Color(r, g, b), true, true, true, false, false, 150, 0.5f, -45);//后5个参数依次是是否平铺，是否在文字上方，水印间距， 透明度和角度
                    result = convert.convertor.convertMStoOOX(sourceFileName, targetFileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != instance) {
                    instance.returnConvertor(convert);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取不可编辑的office流
     *
     * @param inputsteam
     * @param filename
     * @return
     */
    public InputStream getDocNotEditInputStream(InputStream inputsteam, String filename) {
        InputStream imagefile = null;
        String sourcepath = "";
        String targetpath = "";
        String ext = "";
        try {
            if (!"".equals(filename)) {
                ext = getFileExt(filename);
                sourcepath = getFileTempPath("." + ext);
                targetpath = getFileTempPath("." + ext);
                writeLog("getDocNotEditInputStream------sourcepath===" + sourcepath);
                writeLog("getDocNotEditInputStream------targetpath===" + targetpath);
                writeToLocal(sourcepath, inputsteam);
                boolean flag = setDocNotEdit(sourcepath, targetpath);
                writeLog("getDocNotEditInputStream------flag===" + flag);
                if (!flag) {
                    targetpath = sourcepath;
                }
                if (!"".equals(targetpath)) {
                    imagefile = new FileInputStream(new File(targetpath));
                }
            }
        } catch (IOException e) {
            targetpath = sourcepath;
            try {
                imagefile = new FileInputStream(new File(targetpath));
            } catch (FileNotFoundException e1) {
            }
            e.printStackTrace();
            writeLog("getDocNotEditInputStream------e===" + e);
        }
        return imagefile;
    }

    public boolean setDocNotEdit(String sourceFileName, String targetFileName) {
        boolean result = false;
        ConvertorPool instance = null;
        ConvertorObject convert = null;
        try {
            File sourceFile = new File(sourceFileName);
            if (sourceFile.exists() && sourceFile.isFile()) {
                instance = ConvertorPool.getInstance();
                convert = instance.getConvertor();
                String rootpath = GCONST.getRootPath();
                String convertTempPath = rootpath + "filesystem" + File.separatorChar + "docWaterMarkTemp";
                File tempFile = new File(convertTempPath);
                if (!tempFile.exists()) {
                    tempFile.mkdir();
                }
                convert.convertor.setTempPath(convertTempPath);
                convert.convertor.setWordEditable(false);
                result = convert.convertor.convertMStoOOX(sourceFileName, targetFileName);
                convert.convertor.deleteTempFiles();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != instance) {
                    instance.returnConvertor(convert);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public void writeToLocal(String destination, InputStream input) throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    public String getFileTempPath(String ext) {
        String pdfdirPath = GCONST.getRootPath() + "filesystem" + File.separatorChar + "docWaterMarkTemp";
        File waterimagefile = new File(pdfdirPath);
        if (!waterimagefile.exists()) {
            waterimagefile.mkdir();
        }
        String pdfPath = pdfdirPath + File.separatorChar + UUID.randomUUID().toString() + ext;
        return pdfPath;
    }

    /**
     * 得到文档的扩展名
     *
     * @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 static String submitToDCS(String url, String filepath, Map<String, String> param, String type) {
        return submitToDCS(url, filepath, param, type, null);
    }

    public static String submitToDCS(String url, String filepath, Map<String, String> param, String type, Map<String, String> params) {
        String filetype = DocAddWaterForSecond.DOCWATER;
        String extname = "";
        if (params != null) {
            filetype = Util.null2s(params.get("filetype"), DocAddWaterForSecond.DOCWATER);
            extname = Util.null2s(params.get("extname"), "");
        }
        String requestJson = "";
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost(url);
            FileBody file = new FileBody(new File(filepath));
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
            reqEntity.addPart("file", file);
            reqEntity.addPart("targetUrl", new StringBody("1", Charset.forName("UTF-8")));
            reqEntity.addPart("convertType", new StringBody(param.get("convertType"), Charset.forName("UTF-8")));
            if (DocAddWaterForSecond.DOCWATER.equals(filetype) || "".equals(filetype)) {
                reqEntity.addPart("wmWord", new StringBody(param.get("wmWord"), Charset.forName("UTF-8")));
            }
            reqEntity.addPart("wmSize", new StringBody(Util.null2String(param.get("wmSize")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmContent", new StringBody(Util.null2String(param.get("wmContent")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmFont", new StringBody(Util.null2String(param.get("wmFont")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmSpace", new StringBody(Util.null2String(param.get("wmSpace")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmTransparency", new StringBody(Util.null2String(param.get("wmTransparency")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmSuspend", new StringBody(Util.null2String(param.get("wmSuspend")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmRotate", new StringBody(Util.null2String(param.get("wmRotate")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmRgb", new StringBody("1", Charset.forName("UTF-8")));
            reqEntity.addPart("wmTileEffect", new StringBody(Util.null2String(param.get("wmTileEffect")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmRgbRed", new StringBody(Util.null2String(param.get("wmRgbRed")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmRgbGreen", new StringBody(Util.null2String(param.get("wmRgbGreen")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmRgbBlue", new StringBody(Util.null2String(param.get("wmRgbBlue")), Charset.forName("UTF-8")));
            reqEntity.addPart("wmColor", new StringBody("5", Charset.forName("UTF-8")));
            if ("img".equals(type)) {
                reqEntity.addPart("wmX", new StringBody(param.get("wmX"), Charset.forName("UTF-8")));
                reqEntity.addPart("wmY", new StringBody(param.get("wmY"), Charset.forName("UTF-8")));
                if(!"".equals(Util.null2String(param.get("wmPicPath")))){
                    reqEntity.addPart("wmPicPath",new StringBody(param.get("wmPicPath"), Charset.forName("UTF-8")));
                }else if(!"".equals(Util.null2String(param.get("wmImage")))){
                    reqEntity.addPart("wmImage",new StringBody(param.get("wmImage"), Charset.forName("UTF-8")));
                }
            }
            if ("docx".equals(extname)) {
                reqEntity.addPart("imageType", new StringBody(param.get("imageType"), Charset.forName("UTF-8")));
            }
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                byte[] json = EntityUtils.toByteArray(resEntity);
                requestJson = new String(json, "UTF-8");
                //requestJson = EntityUtils.toString(resEntity);
                EntityUtils.consume(resEntity);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
            }
        }
        return requestJson;
    }
    /**
     *
     * @param url 配置永中DCS的上传接口的地址：比如：http://192.168.42.197:8088/ecology_dvs/testUpload
     * @param filepath 源文件路径
     * @return
     */
    public  String uploadFile(String url, String filepath) {
        writeLog("DocWaterMarkForYZUtil----------uploadFile--------start");
        writeLog("DocWaterMarkForYZUtil----------uploadFile--------url="+url);
        writeLog("DocWaterMarkForYZUtil----------uploadFile--------filepath="+filepath);
        String requestJson = "";
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost(url);
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------httppost="+httppost);
            FileBody file = new FileBody(new File(filepath));
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,Charset.forName("UTF-8"));
            reqEntity.addPart("file", file); // file为请求后台的File upload;属性
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------response="+response);
            int statusCode = response.getStatusLine().getStatusCode();
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------statusCode="+statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                byte [] josn = EntityUtils.toByteArray(resEntity);
                requestJson = new String(josn,"UTF-8");
                EntityUtils.consume(resEntity);
            }
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------requestJson1="+requestJson);
            if(!"".equals(requestJson)){
                JSONObject json = convertV4ToV3Json(new JSONObject(requestJson));
                writeLog("DocWaterMarkForYZUtil----------uploadFile--------json="+json);
                if(json!=null){
                    requestJson=json.getString("data");
                    writeLog("DocWaterMarkForYZUtil----------uploadFile--------requestJson2="+requestJson);
                }
            }
        } catch (ParseException e) {
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------ParseException="+e);
            e.printStackTrace();
        } catch (IOException e) {
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------IOException="+e);
            e.printStackTrace();
        } catch (JSONException e) {
            writeLog("DocWaterMarkForYZUtil----------uploadFile--------JSONException="+e);
            e.printStackTrace();
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
                writeLog("DocWaterMarkForYZUtil----------uploadFile--------Exception--ignore="+ignore);
            }
        }
        writeLog("DocWaterMarkForYZUtil----------uploadFile--------requestJson="+requestJson);
        writeLog("DocWaterMarkForYZUtil----------uploadFile--------end");
        return requestJson;
    }
    private InputStream getInputStreamFromDcs(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        return inputStream;
    }

    public static JSONObject convertV4ToV3Json(JSONObject obj){
        try {
          if("v4".equals(ImageConvertUtil.getYozoVersion())) {
            int result = (Integer) obj.get("errorcode");
            String convertPath = "";
            JSONObject data = null;
            try {
                data = obj.getJSONObject("data");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (result == 0 && data != null) {
                convertPath = (String) data.get("viewUrl");
            }
            obj.put("result", result);
            if (!"".equals(convertPath)) {
                obj.remove("data");
                java.util.List convertPathList = new  java.util.ArrayList();
                convertPathList.add(convertPath);
                obj.put("data", convertPathList);
            }
          }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static String getFileBase64(InputStream is) {
        byte[] buffer = null;
        ByteArrayOutputStream bos = null;
        try {

            if (is == null) {
                return "";
            }
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = is.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (IOException e) {

        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }

        if (buffer != null) {
            return new String(Base64.encodeBase64(buffer));
        }
        return "";
    }

}