package com.engine.htsc.meeting.util;

import com.engine.htsc.payment.biz.WfToDocBiz;
import com.weaver.general.GCONST;
import weaver.conn.RecordSet;
import weaver.file.FileManage;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.system.SystemComInfo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static weaver.interfaces.workflow.browser.ExtendBrowser.occurTimes;

public final class Common {

    public static final String OLD_SYNC_TEMP = "/app/ecology/filesystem/pwf/oldsync/";
    /**
     * 签字意见显示长度
     */
    private static final int SING_PAGE_SIZE = 100;
    /**
     * 0关闭签字意见 1 open
     */
    private static final int KEEP_SIGN = 0;
    /**
     * 2html 3pdf
     */
    private static final String GENERATE_DOC_tyPE = "3";
    /**
     * 是否开启水印
     */
    private static final boolean IS_OPEN_WATERMARK = false;

    private static final User user = new User();

    public static String saveProcessPDFWithReturnFilePath(String printModeId, String requestid, String pdfName) {
        saveProcessPDF(printModeId, requestid, pdfName);
        return OLD_SYNC_TEMP + pdfName + "_pdf.pdf";
    }

    public static void saveProcessPDF(String printModeId, String requestid, String pdfName) {
        WfToDocBiz wfToDocBiz = new WfToDocBiz(user, SING_PAGE_SIZE, KEEP_SIGN, GENERATE_DOC_tyPE, printModeId, IS_OPEN_WATERMARK);
        wfToDocBiz.setOnlineHtmlMethod("");
        wfToDocBiz.generatepdfandhtml(requestid, pdfName, OLD_SYNC_TEMP, "save");
    }

    public static Map<String, Object> getImageFileInfo(String fileid) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(Util.getIntValue(fileid));
        String filename = manager.getImageFileName();
        String extname = filename.contains(".") ? filename.substring(filename.lastIndexOf(".") + 1) : "";
        String imgSrc = "";
        if (!("bmp".equals(extname.toLowerCase()) || "jpg".equals(extname.toLowerCase()) ||
                "gif".equals(extname.toLowerCase()) || "png".equals(extname.toLowerCase()))) {
            String selectext = "select iconpath from workflow_filetypeicon where extendname = ?";
            RecordSet rs1 = new RecordSet();
            rs1.executeQuery(selectext, extname);
            if (rs1.next()) {
                String iconpath = Util.null2s(rs1.getString("iconpath"), "");
                imgSrc = "/images/filetypeicons/" + iconpath;
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("acclink", "/weaver/weaver.file.FileDownload?fileid=" + fileid);
        data.put("fileExtendName", extname);
        data.put("fileid", docIdByImageId(fileid));
        data.put("imagefileid", fileid);
        data.put("filelink", "/spa/document/index2file.jsp?imagefileId=" + fileid + "#/main/document/fileView");
        data.put("filename", filename);
        data.put("filesize", manager.getImgsize());
        data.put("imgSrc", imgSrc);
        data.put("isImg", "");
        data.put("loadlink", "/weaver/weaver.file.FileDownload?fileid=" + fileid + "&download=1");
        data.put("showDelete", "true");
        data.put("showLoad", "true");
        data.put("uploaddate", simpleDateFormat.format(manager.getLastModified()));
        return data;
    }

    public static String docIdByImageId(String imageId) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("SELECT DOCID,IMAGEFILEID FROM DocImageFile\n" +
                "WHERE IMAGEFILEID = ?", imageId);
        if (rs.next()) {
            return Util.null2String(rs.getString("DOCID"));
        }
        return "";
    }

    /**
     * 移动附件到对应目录
     * @param secid
     * @param docid
     */
    public static void copyDocFile(int secid,int docid) {
        int seccategoryid = secid;
        SystemComInfo syscominfo = new SystemComInfo();
        String ddefaultpath = syscominfo.getFilesystem();
        if("".equals(ddefaultpath)){
            ddefaultpath = GCONST.getRootPath();
            ddefaultpath = ddefaultpath + "filesystem" + File.separatorChar;
        }
        moveFile(ddefaultpath,""+docid);
    }

    public static void moveFile(String targetpath,String docid) {
        RecordSet rs1 = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql="select * from docimagefile a inner join imagefile b on  b.imagefileid=a.imagefileid where docid=?";
        rs.executeQuery(sql,docid);
        try{
            while(rs.next()){
                String resourcepath=rs.getString("filerealpath");
                if(!resourcepath.startsWith(targetpath)||(resourcepath.startsWith(targetpath)&&occurTimes(resourcepath.substring(targetpath.length()+1),File.separator)!=2)){
                    String createdir = FileUpload.getCreateDir(targetpath+ File.separator);
                    String fileName = UUID.randomUUID().toString();
                    if (resourcepath.lastIndexOf(".") > -1) {
                        fileName += resourcepath.substring(resourcepath.lastIndexOf("."));
                    }
                    boolean flag = FileManage.createDir(createdir);
                    String new_fileRealPath =createdir+fileName;
                    if (flag) {
                        FileManage.copy(resourcepath, new_fileRealPath);
                        rs1.execute("update imagefile set filerealpath='" + new_fileRealPath + "' where imagefileid=" + rs.getString("imagefileid"));
                        FileManage.DeleteFile(resourcepath);
                    }
                }
            }
        }catch(Exception ex){
            rs.writeLog("file move fail："+ex);
            ex.printStackTrace();
        }
    }
}
