package weaver.interfaces.htsc.wpscenter.utils;

import com.api.doc.mobile.systemDoc.util.SystemDocUtil;
import com.engine.core.exception.ECException;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocComInfo;
import weaver.docs.docs.VersionIdUpdate;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.file.multipart.DefaultFileRenamePolicy;
import weaver.file.multipart.MultipartRequest;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.system.SystemComInfo;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class FileInfoUtil {

    private Logger log = LoggerFactory.getLogger(FileInfoUtil.class);
    
    public Logger getLog() {
        return log;
    }

    public FileInfoUtil setLog(Logger log) {
        this.log = log;
        return this;
    }

    /**
     *
     * @param fileid 文件ID
     * @param user  用户对象
     * @param fromMould 模块
     * @return
     *     ext: 文件后缀,不带点
     *     fileName: 文件名
     *     filesize： 文件大小
     */
    public Map<String,String> getFileInfo(String fileid, User user, String fromMould){
        Map<String, String> fileInfo = new HashMap<String, String>();

        fromMould = Tools.getFromMould(fromMould);

        String filename = "";
        String ext = "";
        String filesize = "";
        // 如果是邮件模块
        if("email".equals(fromMould)){
            weaver.email.service.MailFilePreviewService mfps = new weaver.email.service.MailFilePreviewService();
            Map<String, String> fileInfoMap = mfps.getFileInfoMap(user.getUID(), fileid);
            filesize = fileInfoMap.get("filesize");
            filename = fileInfoMap.get("filename");
            ext = filename.contains(".") ? filename.substring(filename.lastIndexOf(".")+1) : "";
        } else if("editMould".equals(fromMould) || "showMould".equals(fromMould)) {
            String tableName = "";
            String mouldtype = "";
            String mouldPath = "";

            if ("showMould".equals(fromMould)) {
                tableName = "docMould";
            } else {
                tableName = "DocMouldFile";
            }

            RecordSet rs = new RecordSet();
            rs.executeQuery("select mouldName,mouldPath,mouldtype from " + tableName + " where id=?", fileid);
            if (rs.next()) {
                filename = rs.getString("mouldName");
                mouldtype = rs.getString("mouldtype");
                mouldPath = rs.getString("mouldPath");
            }

            if ("2".equals(mouldtype)) {
                filename += ".doc";
                ext = "doc";
            } else if ("3".equals(mouldtype)) {
                filename += ".xls";
                ext = "xls";
            } else if ("4".equals(mouldtype)) {
                filename += ".wps";
                ext = "wps";
            }
            ext = ext.isEmpty() ? (filename.contains(".") ? filename.substring(filename.lastIndexOf(".")) : "") : ext;
            filesize = getMouldFilesize(mouldPath, tableName, fileid);
        }else{
            ImageFileManager ifm = new ImageFileManager();
            ifm.resetParameter();
            ifm.getImageFileInfoById(Util.getIntValue(fileid));
            filename = Util.null2String(ifm.getImageFileName());
            ext = filename.contains(".") ? filename.substring(filename.lastIndexOf(".")+1) : "";
            filesize = ifm.getFilesize();
        }

        ext = ext.toLowerCase();
        filename = Tools.getFileNameWithLowerCaseSuffix(filename);
        // 记录当前文件的名称和类型
        fileInfo.put("ext", ext);
        fileInfo.put("filename", filename);
        fileInfo.put("filesize", filesize);
        String download = Tools.getDownloadUrl(Util.getIntValue(fileid),fromMould);
        fileInfo.put("download", download);

        return fileInfo;
    }

    /**
     *
     * @param fileid
     * @param user
     * @param fromMould
     * @return
     */
    public JSONObject getFileInfoJson(String fileid, User user, String fromMould, Map<String, String> otherParams){
        JSONObject fileInfoJson = new JSONObject();

        fromMould = Tools.getFromMould(fromMould);

        boolean newdoc = "true".equals(otherParams.get("newdoc"));
        String sence = otherParams.get("sence");
        String wpsfileid = otherParams.get("wpsfileid");
        int iscollaborativedoc = Util.getIntValue(otherParams.get("iscollaborativedoc"));

        Map<String, String> fileInfo = getFileInfo(fileid, user, fromMould);
        String filename = fileInfo.get("filename");

        String ext = fileInfo.get("ext");
        String filesize = fileInfo.get("filesize");

        long createTime = 2;

        int fileidInt = Util.getIntValue(fileid);

        // id 默认使用回传的id
        String id = otherParams.get("fileid");

        int versionid = fileidInt;
        if(TokenUtil.SCOPE_FILE_EDIT.equals(sence)) {
            JSONObject wpsFileInfo = getWpsFileInfoWithoutNew(wpsfileid, fileidInt, fromMould, newdoc, ext, filename, user.getUID(), iscollaborativedoc);
            if(null != wpsFileInfo && !wpsFileInfo.isEmpty() && wpsFileInfo.containsKey("wpsfileid")) {
                id = wpsFileInfo.getString("wpsfileid");            // wps文件id
                versionid = wpsFileInfo.getInt("versionid");        // 版本id，取记录中的
                fileidInt = wpsFileInfo.getInt("ecfileid");         // 获取文件的id，更新为新的id
                fromMould = wpsFileInfo.getString("mould");         // 文件模块，更新为新的
                createTime = wpsFileInfo.getLong("createtime");     // 创建时间，取文件记录中的
            } else {
                id = "";
            }
        }

        if(Tools.isEmptyOrNull(id)) {
            if(Tools.isEmptyOrNull(fileid)) {
                return fileInfoJson;
            }
            id = wpsfileid;
            Map<String, String> mapFileInfo = getFileInfo(fileid, user, fromMould);
            RecordSet rs = new RecordSet();
            rs.executeQuery("select * from docimagefile where imagefileid = ?", fileid);
            if(rs.next()){
                if(1 == iscollaborativedoc) {
                    String docid = Util.null2String(rs.getString("docid"));
                    try{
                        DocComInfo dci = new DocComInfo();
                        String doccreatetime = dci.getDocCreateTime(docid);
                        String doclastmodtime = dci.getDocLastModDateTime(docid);
                        if((doccreatetime).equals(doclastmodtime)){
                            versionid = rs.getInt("versionid");
                            createTime = Tools.getTimeSeconds(rs.getString("createdate"), rs.getString("createtime"));
                        } else {
                            throw new ECException("数据查询异常");
                            // return fileInfoJson;
                        }
                    }catch (Exception e) {
                        // 读取缓存类如果报错了就使用sql查询
                        RecordSet rsDoc = new RecordSet();
                        rsDoc.executeQuery("select * from docdetail where id = ?", docid);
                        if(!rsDoc.next()){
                            throw new ECException("数据查询异常");
                            // return fileInfoJson;
                        } else {
                            String doccreatedate = Util.null2String(rsDoc.getString("doccreatedate"));
                            String doccreatetime = Util.null2String(rsDoc.getString("doccreatetime"));
                            String doclastmoddate = Util.null2String(rsDoc.getString("doclastmoddate"));
                            String doclastmodtime = Util.null2String(rsDoc.getString("doclastmodtime"));
                            if((doclastmoddate + doclastmodtime).equals(doccreatedate + doccreatetime)){
                                versionid = rs.getInt("versionid");
                                createTime = Tools.getTimeSeconds(rs.getString("createdate"), rs.getString("createtime"));
                            } else {
                                throw new ECException("数据查询异常");
                                // return fileInfoJson;
                            }
                        }
                    }
                } else {
                    versionid = rs.getInt("versionid");
                    createTime = Tools.getTimeSeconds(rs.getString("createdate"), rs.getString("createtime"));
                }
            } else {
                versionid = 1;
                createTime = 1;
            }
            fileidInt = Util.getIntValue(fileid);
        }

        String downloadUrl = Tools.getDownloadUrl(fileidInt,fromMould);

        String userid = user.getUID()+"";

        fileInfoJson.put("id", id);
        fileInfoJson.put("name", filename);
        // fileInfoJson.put("version", versionid);  // TODO 先用文件ID作为版本ID
        fileInfoJson.put("version", versionid);
        fileInfoJson.put("size", Util.getIntValue(filesize));
        fileInfoJson.put("creator", userid);
        fileInfoJson.put("create_time", createTime);
        fileInfoJson.put("modifier", userid);
        fileInfoJson.put("modify_time", createTime);
        fileInfoJson.put("download_url", downloadUrl);
        //fileInfoJson.put("preview_pages", Integer.MAX_VALUE);

        return fileInfoJson;
    }

    public String getMouldFilesize(String mouldPath, String tableName, String fileid){
        // 如果又模板路径，直接查询模板的大小
        if(null != mouldPath && !mouldPath.trim().isEmpty()) {
            File modFile= new File(mouldPath);
            if(modFile.exists() && modFile.isFile()) {
                return String.valueOf(modFile.length());
            } else {
                return "0";
            }
        }

        // 如果没有模板路径尝试获取模板的物理文件
        RecordSet rs = new RecordSet();
        rs.executeQuery("select imagefileid from " + tableName + " where id=?", fileid);
        if(!rs.next()) {
            return "0";
        }

        ImageFileManager ifm = new ImageFileManager();
        ifm.resetParameter();
        ifm.getImageFileInfoById(rs.getInt("imagefileid"));
        return ifm.getFilesize();
    }

    public String getFixedFileName(String filename, int imagefileid, String fromMould) {
        if (null == filename || filename.isEmpty()) {
            return filename;
        }

        fromMould = Tools.getFromMould(fromMould);

        filename = filename.replace(":", "").replace("：", "");

        boolean isZip = filename.toLowerCase().endsWith(".zip") || filename.toLowerCase().endsWith(".rar");

        if (isZip && filename.length() > 20) {
            filename = filename.substring(0, 15) + filename.substring(filename.lastIndexOf("."));
        }

        if (!isZip) {
            String sendName = imagefileid + "_" + fromMould;
            if (filename != null && filename.contains(".")) {
                sendName = sendName + filename.substring(filename.lastIndexOf("."));
            }
            filename = sendName;
        }

        return filename;
    }

    /**
     * table name table wps_doccenter_fileinfo
     *    id int,                      -- 主键id
     *    wpsfileid String,               -- 创建的wpsid，目前直接复用imagefileid生成新的即可
     *    ecfileid int,                --  保存的文件id
     *    mould varchar(50),           -- 文件当前保存的模块表
     *    versionid int,               -- 文件版本id，目前直接复用versionid生成新的即可
     *    fromecfileid varchar(50),    -- 源文件来源的文件id
     *    frommould varchar(50),       -- 原文件来源的模块表
     *    iscollaborativedoc int,      -- 是否是协作文档
     *    createdate varchar(10),      -- 创建日期
     *    createtime varchar(8)        -- 创建时间
     * @param fileidInt
     * @param fromMould
     * @param isnewdoc
     * @return wpsfileid, versionid, ecfileid, mould, createtime
     */
    @Deprecated
    public JSONObject getWpsFileInfo(String wpsfileid, int fileidInt, String fromMould, boolean isnewdoc, String ext,
                                            String filename, int userid, int iscollaborativedoc){
        JSONObject fileInfoJson = new JSONObject();

        // 来源模块优化，防止空值
        fromMould = Tools.getFromMould(fromMould);

        int versionid = 0;
        int ecfileid = 0;
        int createuserid = 0;
        String mould = "";
        String createdate = "";
        String createtime = "";


        // wps_doccenter_fileinfo
        RecordSet rs = new RecordSet();
        // 如果时协同文档，则查询原有的数据
        if(1 == iscollaborativedoc) {
            String sql = "select * from wps_doccenter_fileinfo where iscollaborativedoc =? and frommould = ? and fromecfileid = ? order by versionid desc";
            rs.executeQuery(sql, iscollaborativedoc, fromMould, fileidInt);
            log.info(new StringBuilder("executeQuery from wps_doccenter_fileinfo:")
                    .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                    .append(" [fromMould]:").append(fromMould)
                    .append(" [fileidInt]:").append(fileidInt)
                    .toString());
            if(rs.next()) {
                wpsfileid = rs.getString("wpsfileid");
                versionid = rs.getInt("versionid");
                ecfileid = rs.getInt("ecfileid");
                createuserid = rs.getInt("createuserid");
                mould = rs.getString("mould");
                createdate = rs.getString("createdate");
                createtime = rs.getString("createtime");

                fileInfoJson.put("wpsfileid", wpsfileid);
                fileInfoJson.put("versionid", versionid);
                fileInfoJson.put("mould", mould);
                fileInfoJson.put("ecfileid", ecfileid);
                fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
                fileInfoJson.put("filename", rs.getString("filename"));
                fileInfoJson.put("createuserid", createuserid);
                return fileInfoJson;
            } else {
                log.warn(new StringBuilder("executeQuery from wps_doccenter_fileinfo failed:")
                        .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                        .append(" [fromMould]:").append(fromMould)
                        .append(" [fileidInt]:").append(fileidInt)
                        .toString());
            }
        } else if(!Tools.isEmptyOrNull(wpsfileid)){
            String sql = "select * from wps_doccenter_fileinfo where wpsfileid = ? order by versionid desc";
            rs.executeQuery(sql, wpsfileid);
            if(rs.next()) {
                // wpsfileid = rs.getString("wpsfileid");
                versionid = rs.getInt("versionid");
                ecfileid = rs.getInt("ecfileid");
                createuserid = rs.getInt("createuserid");
                mould = rs.getString("mould");
                createdate = rs.getString("createdate");
                createtime = rs.getString("createtime");

                fileInfoJson.put("wpsfileid", wpsfileid);
                fileInfoJson.put("versionid", versionid);
                fileInfoJson.put("mould", mould);
                fileInfoJson.put("ecfileid", ecfileid);
                fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
                fileInfoJson.put("filename", rs.getString("filename"));
                fileInfoJson.put("createuserid", createuserid);
                return fileInfoJson;
            }
        }

        if(fileidInt <= 0 && isnewdoc) {
            // 创建一个空白的文档
            ecfileid = copyEmptyFileToNewImagefile(filename, ext);
            mould = "ecology";
        } else {
            ecfileid = fileidInt;
            mould = fromMould;
        }

        wpsfileid = Tools.getNewWpsFileid();
        if(1 == iscollaborativedoc) { // 协同文档，如果已经有versionid，直接用
            String sql = "select * from docimagefile where imagefileid =? order by versionid desc";
            rs.executeQuery(sql, fileidInt);
            if(rs.next()) {
                versionid = rs.getInt("versionid");
            } else {
                versionid = new VersionIdUpdate().getVersionNewId();
            }
        } else {
            versionid = new VersionIdUpdate().getVersionNewId();
        }

        createdate = TimeUtil.getCurrentDateString();
        createtime = TimeUtil.getOnlyCurrentTimeString();

        log.info(new StringBuilder("getWpsFileInfo fileinfo query failed. saveWpsFileInfo:")
                .append(" [wpsfileid]:").append(wpsfileid)
                .append(" [ecfileid]:").append(ecfileid)
                .append(" [mould]:").append(mould)
                .append(" [versionid]:").append(versionid)
                .append(" [ecfileid]:").append(ecfileid)
                .append(" [fromMould]:").append(fromMould)
                .append(" [filename]:").append(filename)
                .append(" [userid]:").append(userid)
                .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                .append(" [createdate]:").append(createdate)
                .append(" [createtime]:").append(createtime)
                .toString());

        // 数据保存到数据库
        saveWpsFileInfo(wpsfileid, ecfileid, mould, versionid, ecfileid, fromMould, filename, userid, iscollaborativedoc, createdate, createtime);

        fileInfoJson.put("wpsfileid", wpsfileid);
        fileInfoJson.put("versionid", versionid);
        fileInfoJson.put("mould", mould);
        fileInfoJson.put("ecfileid", ecfileid);
        fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
        fileInfoJson.put("filename", filename);
        fileInfoJson.put("createuserid", createuserid);

        return fileInfoJson;
    }

    public JSONObject getWpsFileInfoWithoutNew(String wpsfileid, int fileidInt, String fromMould, boolean isnewdoc, String ext,
                                     String filename, int userid, int iscollaborativedoc){
        JSONObject fileInfoJson = new JSONObject();

        // 来源模块优化，防止空值
        fromMould = Tools.getFromMould(fromMould);

        int versionid = 0;
        int ecfileid = 0;
        int createuserid = 0;
        String mould = "";
        String createdate = "";
        String createtime = "";

        if(Config.isLogInfo()) {
            log.info(new StringBuilder("getWpsFileInfo fileinfo query failed. saveWpsFileInfo:")
                    .append(" [wpsfileid]:").append(wpsfileid)
                    .append(" [fileidInt]:").append(fileidInt)
                    .append(" [fromMould]:").append(fromMould)
                    .append(" [isnewdoc]:").append(isnewdoc)
                    .append(" [ext]:").append(ext)
                    .append(" [filename]:").append(filename)
                    .append(" [filename]:").append(filename)
                    .append(" [userid]:").append(userid)
                    .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                    .toString());
        }

        // wps_doccenter_fileinfo
        RecordSet rs = new RecordSet();
        // 如果时协同文档，则查询原有的数据
        if(1 == iscollaborativedoc) {
            String sql = "select * from wps_doccenter_fileinfo where iscollaborativedoc =? and frommould = ? and fromecfileid = ? order by versionid desc";
            rs.executeQuery(sql, iscollaborativedoc, fromMould, fileidInt);
            if(rs.next()) {
                wpsfileid = rs.getString("wpsfileid");
                versionid = rs.getInt("versionid");
                ecfileid = rs.getInt("ecfileid");
                createuserid = rs.getInt("createuserid");
                mould = rs.getString("mould");
                createdate = rs.getString("createdate");
                createtime = rs.getString("createtime");

                fileInfoJson.put("wpsfileid", wpsfileid);
                fileInfoJson.put("versionid", versionid);
                fileInfoJson.put("mould", mould);
                fileInfoJson.put("ecfileid", ecfileid);
                fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
                fileInfoJson.put("filename", rs.getString("filename"));
                fileInfoJson.put("createuserid", createuserid);
            } else if(!isnewdoc){
                log.warn(new StringBuilder("executeQuery from wps_doccenter_fileinfo failed:")
                        .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                        .append(" [fromMould]:").append(fromMould)
                        .append(" [fileidInt]:").append(fileidInt)
                        .toString());
            }
        } else if(!Tools.isEmptyOrNull(wpsfileid)){
            String sql = "select * from wps_doccenter_fileinfo where wpsfileid = ? order by versionid desc";
            rs.executeQuery(sql, wpsfileid);
            if(rs.next()) {
                // wpsfileid = rs.getString("wpsfileid");
                versionid = rs.getInt("versionid");
                ecfileid = rs.getInt("ecfileid");
                createuserid = rs.getInt("createuserid");
                mould = rs.getString("mould");
                createdate = rs.getString("createdate");
                createtime = rs.getString("createtime");

                fileInfoJson.put("wpsfileid", wpsfileid);
                fileInfoJson.put("versionid", versionid);
                fileInfoJson.put("mould", mould);
                fileInfoJson.put("ecfileid", ecfileid);
                fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
                fileInfoJson.put("filename", rs.getString("filename"));
                fileInfoJson.put("createuserid", createuserid);
            }
        }

        return fileInfoJson;
    }

    public JSONObject getWpsFileInfoByVersion(int versionid){
        JSONObject fileInfoJson = new JSONObject();

        // wps_doccenter_fileinfo
        RecordSet rs = new RecordSet();
        // 不管是不是同一个文件的数据，versionid一定不重复，直接作为查询条件即可
        String sql = "select * from wps_doccenter_fileinfo where versionid = ? order by versionid desc";
        rs.executeQuery(sql, versionid);
        if(!rs.next()) {
            fileInfoJson.put("wpsfileid", "wps_0");
            return fileInfoJson;
        }

        String wpsfileid = rs.getString("wpsfileid");
        int ecfileid = rs.getInt("ecfileid");
        int fromecfileid = rs.getInt("fromecfileid");
        int createuserid = rs.getInt("createuserid");
        String mould = rs.getString("mould");
        String frommould = rs.getString("frommould");
        String createdate = rs.getString("createdate");
        String createtime = rs.getString("createtime");
        String filename = rs.getString("filename");

        fileInfoJson.put("wpsfileid", wpsfileid);
        fileInfoJson.put("versionid", versionid);
        fileInfoJson.put("mould", mould);
        fileInfoJson.put("frommould", frommould);
        fileInfoJson.put("ecfileid", ecfileid);
        fileInfoJson.put("fromecfileid", fromecfileid);
        fileInfoJson.put("createtime", Tools.getTimeSeconds(createdate, createtime));
        fileInfoJson.put("filename", filename);
        fileInfoJson.put("createuserid", createuserid);

        return fileInfoJson;
    }

    public int copyFileToNewImagefile(String filename, String filerealpath){
        File emptyFile = new File(filerealpath);
        filename = null == filename || filename.isEmpty() || !filename.contains(".") ? emptyFile.getName() : filename;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(emptyFile);
            byte[] emptyFileBytes = Tools.toByteArray(fileInputStream);
            ImageFileManager imageFileManager = new ImageFileManager();
            imageFileManager.resetParameter();
            imageFileManager.setData(emptyFileBytes);
            imageFileManager.setComefrom("wps_doccenter");       // 设置来源，便于确认
            imageFileManager.setImagFileName(filename);
            return imageFileManager.saveImageFile();
        } catch (IOException e) {
            log.error(e);
            return 0;
        } finally {
            Tools.cloze(fileInputStream);
        }
    }

    public int copyEmptyFileToNewImagefile(String filename, String ext){
        File emptyFile = getEmptFile(ext);
        filename = null == filename || filename.isEmpty() ? emptyFile.getName() : filename;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(emptyFile);
            byte[] emptyFileBytes = Tools.toByteArray(fileInputStream);
            ImageFileManager imageFileManager = new ImageFileManager();
            imageFileManager.resetParameter();
            imageFileManager.setData(emptyFileBytes);
            imageFileManager.setComefrom("wps_doccenter");       // 设置来源，便于确认
            imageFileManager.setImagFileName(filename);
            return imageFileManager.saveImageFile();
        } catch (IOException e) {
            log.error(e);
            return 0;
        } finally {
            Tools.cloze(fileInputStream);
        }
    }

    public File getEmptFile(String ext){
        File emptyFile = new File(getEmptFilePath(ext));
        return emptyFile;
    }

    public String getEmptFilePath(String ext){
        String filepath = GCONST.getRootPath() + "spa" + File.separatorChar + "document" + File.separatorChar;
        filepath = filepath + getEmptFileName(ext);
        return filepath;
    }

    public String getEmptFileName(String ext){
        String filename = "";
        if(ext.equals("xls") || ext.equals("xlsx")){
            filename = "excel.xlsx";
        }else if(ext.equals("doc") || ext.equals("docx")){
            filename = "word.docx";
        }else if(ext.equals("ppt") || ext.equals("pptx")){
            filename = "powerpoint.pptx";
        }else if(ext.equals("wps")){
            filename = "wps.wps";
        }else if(ext.equals("et")){
            filename = "et.et";
        }
        return filename;
    }

    public Boolean saveWpsFileInfo(String wpsfileid, int ecfileid, String mould, int versionid,
                  int fromecfileid, String frommould, String filename, int userid, int iscollaborativedoc, String createdate, String createtime){

        if(ecfileid <= 0 || versionid <= 0 || fromecfileid <= 0 || Tools.isEmptyOrNull(filename) || userid <= 0) {
            log.info(new StringBuilder("saveWpsFileInfo failed. The parameters:")
                    .append(" [wpsfileid]:").append(wpsfileid)
                    .append(" [ecfileid]:").append(ecfileid)
                    .append(" [mould]:").append(mould)
                    .append(" [versionid]:").append(versionid)
                    .append(" [ecfileid]:").append(ecfileid)
                    .append(" [fromMould]:").append(frommould)
                    .append(" [filename]:").append(filename)
                    .append(" [userid]:").append(userid)
                    .append(" [iscollaborativedoc]:").append(iscollaborativedoc)
                    .append(" [createdate]:").append(createdate)
                    .append(" [createtime]:").append(createtime)
                    .toString());
            throw new ECException("arguments invaild");
        }

        // 来源模块优化，防止空值
        mould = Tools.getFromMould(mould);
        frommould = Tools.getFromMould(frommould);

        RecordSet rs = new RecordSet();
        String sql = "insert into wps_doccenter_fileinfo (wpsfileid, ecfileid, mould, versionid, fromecfileid, frommould, filename, createuserid, iscollaborativedoc, createdate, createtime) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        return rs.executeUpdate(sql, wpsfileid, ecfileid, mould, versionid, fromecfileid, frommould, filename, userid, iscollaborativedoc, createdate, createtime);
    }

    public int saveFileToEcology(HttpServletRequest request) {
        FileUpload fu = new FileUpload(request);
        int imagefileid = Util.getIntValue(fu.uploadFiles("file"));
        return imagefileid;
    }

    public int saveFileToEcologyFromRequest(HttpServletRequest request) {
        try{
            FileUpload fu = new FileUpload(request);
            DefaultFileRenamePolicy defpolicy = new DefaultFileRenamePolicy();
            SystemComInfo syscominfo = new SystemComInfo();
            String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());
            String isaesencrypt = syscominfo.getIsaesencrypt();
            String aescode = Util.getRandomString(13);
            boolean needzip = false;
            if ((syscominfo.getNeedzip()).equals("1")) needzip = true;
            boolean needzipencrypt = false;
            //       if( (syscominfo.getNeedzipencrypt()).equals("1") ) needzipencrypt = true ;
            int contentLength = request.getContentLength();
            if(contentLength <= -1 && null != request.getInputStream()) {
                contentLength = Integer.MAX_VALUE;
            }
            MultipartRequest mr = new MultipartRequest(request, createdir, contentLength, defpolicy, needzip, needzipencrypt, "", isaesencrypt, aescode);

            Method method =  FileUpload.class.getMethod("saveFile", new Class[]{String.class, MultipartRequest.class});
            method.setAccessible(true);
            method.invoke(fu,new Object[]{"file", mr});
            method.setAccessible(false);
            int imagefileid = Util.getIntValue(fu.uploadFiles("file"));
            return imagefileid;
        }catch (Exception e) {
            log.error(e);
            return -1;
        }
    }

    public byte[] saveFileToEcologyFromRequest2(HttpServletRequest request) {
        try{
            SystemComInfo syscominfo = new SystemComInfo();

            //得到上传文件的保存目录。 将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
            String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());

            //判断存放上传文件的目录是否存在（不存在则创建）
            File f = new File(createdir);
            if(!f.exists()&&!f.isDirectory()){
                f.mkdir();
            }

            /**
             * 使用Apache文件上传组件处理文件上传步骤：
             *
             * */
            //1、设置环境:创建一个DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();

            //设置上传文件的临时目录
            factory.setRepository(f);

            //2、核心操作类:创建一个文件上传解析器。
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解决上传"文件名"的中文乱码
            upload.setHeaderEncoding("UTF-8");

            //3、判断enctype:判断提交上来的数据是否是上传表单的数据
            if(!ServletFileUpload.isMultipartContent(request)){
                System.out.println("不是上传文件，终止");
                //按照传统方式获取数据
                return new byte[0];
            }

            //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
            List<FileItem> items =upload.parseRequest(request);
            ListIterator<FileItem> itemIterable = items.listIterator();
            while (itemIterable.hasNext()) {
                FileItem item = itemIterable.next();
                String filedName = item.getFieldName();//普通输入项数据的名
                if(!"file".equals(filedName)) {
                    continue;
                }
                //如果fileitem中封装的是上传文件，得到上传的文件名称，
                String fileName = item.getName();//上传文件的名
                //多个文件上传输入框有空 的 异常处理
                if(fileName==null||"".equals(fileName.trim())){  //去空格是否为空
                    continue;// 为空，跳过当次循环，  第一个没输入则跳过可以继续输入第二个
                }
                InputStream in = item.getInputStream(); //获取item中的上传文件的输入流
                if(null == in) {
                    return new byte[0];
                }
                byte[] fileBytes = Tools.toByteArray(in);
                return fileBytes;
            }
            log.error(new ECException("File Not Found From Request"));

            return new byte[0];
        }catch (Exception e) {
            log.error(e);
        }
        return new byte[0];
    }


    public InputStream getInputStream(int fileid, String fromMould){
        InputStream in = null;
        try{
            if("email".equals(fromMould)){
                weaver.email.service.MailFilePreviewService mfps = new weaver.email.service.MailFilePreviewService();
                in = mfps.getInputStreamByMailFileId(fileid + "");
            } else if("editMould".equals(fromMould) || "showMould".equals(fromMould)){
                String tableName = "";
                if("showMould".equals(fromMould)){
                    tableName = "docMould";
                } else{
                    tableName = "DocMouldFile";
                }
                String mouldPath = "";
                int mouldImagefileId = 0;
                RecordSet rs = new RecordSet();
                rs.executeQuery("select mouldName,mouldPath,imagefileid,mouldtype from "+ tableName +" where id=?",fileid);
                if(rs.next()){
                    mouldPath = rs.getString("mouldPath");
                    mouldImagefileId = rs.getInt("imagefileid");
                }
                if(mouldImagefileId > 0){
                    in = ImageFileManager.getInputStreamById(mouldImagefileId);
                }else{
                    in = new BufferedInputStream(new FileInputStream(mouldPath));
                }
            }else{
                ImageFileManager imageFileManager = new ImageFileManager();
                imageFileManager.resetParameter();

                imageFileManager.getImageFileInfoById(fileid);

                return imageFileManager.getInputStream();
            }
        }catch (Exception e){
            log.error(e);
        }

        return in;
    }
}
