package weaver.interfaces.htsc.util;

import com.api.doc.detail.service.DocViewPermission;
import com.api.doc.detail.util.ImageConvertUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocComInfo;
import weaver.docs.docs.DocManager;
import weaver.docs.docs.DocViewer;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;

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

/**
 * 文档操作工具类
 */
public class DocUtil {


    /**
     * 读取文件写到指定路径
     * @param fromPath 源路径
     * @param iszip 是否压缩
     * @param toPath 目的路径
     * @throws IOException IO异常
     */
    public static void writeFile(String fromPath,int iszip,String toPath) throws IOException {
        OutputStream output = new FileOutputStream(toPath);
        BufferedInputStream inputStream = null;
        BaseBean bb = new BaseBean();
        try {
            if (StringUtils.isNotBlank(fromPath)) {
                File file = new File(fromPath);
                if(!file.exists()) {
                    throw new WebApplicationException(404);
                }
                if (iszip == 1) {
                    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        inputStream = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                }

                byte[] buffer = new byte[4096];
                int n = 0;
                assert inputStream != null;
                while (-1 != (n = inputStream.read(buffer))) {
                    output.write(buffer, 0, n);
                }
                output.flush();
                inputStream.close();
                output.close();
            }
        }catch (IOException e){
            bb.writeLog("e:"+e);
        }finally {
            if(inputStream !=null){
                inputStream.close();
            }
            output.close();
        }
    }

    /**
     * 根据文档后缀返回文档类型
     * @param suffix 后缀
     * @return 文档类型
     */
    public static String getFiletype(String suffix) {
        String fileType = "7";
        if (suffix.equals(".doc")) {
            fileType = "3";
        } else if (suffix.equals(".xls")) {
            fileType = "4";
        } else if (suffix.equals(".ppt")) {
            fileType = "5";
        } else if (suffix.equals(".wps")) {
            fileType = "6";
        } else if (suffix.equals(".docx")) {
            fileType = "7";
        } else if (suffix.equals(".xlsx")) {
            fileType = "8";
        } else if (suffix.equals(".pptx")) {
            fileType = "9";
        } else if (suffix.equals(".et")) {
            fileType = "10";
        } else if (suffix.equals(".pdf")) {
            fileType = "12";
        } else if (suffix.equals(".ofd")) {
            fileType = "13";
        }
        return fileType;
    }


    /**
     * 根据文档类型返回对应的后缀
     * @param doctype 文档类型
     * @return 文档后缀
     */
    public static String getSuffixByDocFiletype(String doctype) {
        String fileType = ".doc";
        if (doctype.equals("3")) {
            fileType = ".doc";
        } else if (doctype.equals("4")) {
            fileType = ".xls";
        } else if (doctype.equals("5")) {
            fileType = ".ppt";
        } else if (doctype.equals("6")) {
            fileType = ".wps";
        } else if (doctype.equals("7")) {
            fileType = ".docx";
        } else if (doctype.equals("8")) {
            fileType = ".xlsx";
        } else if (doctype.equals("9")) {
            fileType = ".pptx";
        } else if (doctype.equals("10")) {
            fileType = ".et";
        } else if (doctype.equals("12")) {
            fileType = ".pdf";
        } else if (doctype.equals("13")) {
            fileType = ".ofd";
        } else if (doctype.equals("14")) {
            fileType = ".uot";
        }
        return fileType;
    }


    /**
     * doc转pdf
     * @param fileid 文件ID
     * @param convertType 转换类型
     * @param user 当前用户
     * @param clientAddress 转换服务器地址
     * @return 转换结果
     */
    public Map<String,Object> docToPdf(int fileid, String convertType, User user,String clientAddress){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(fileid > 0){
            ImageConvertUtil icu = new ImageConvertUtil();
            try{
                apidatas = icu.convertForPath(fileid,user,clientAddress,new HashMap<String,String>(),convertType,ImageConvertUtil.DOC_ACC_TABLE);
            }catch(Exception e){
                apidatas.put("result", -3);
                new BaseBean().writeLog("----docutil docToPdf:",e);
            }
        }else{
            apidatas.put("result", -3);
        }
        return apidatas;
    }


    /**
     * 根据文档创建新的文档
     * @param oldDocId 源文档id
     * @return 新文档id
     */
    public static int createDocFromAnother(int oldDocId) {
        try {
            DocManager docManager = new DocManager();
            docManager.setId(oldDocId);
            docManager.getDocInfoById();
            String dummycata = "";
            String docStatus = "";
            String docSubject = "";
            RecordSet rs = new RecordSet();
            rs.executeQuery("select catelogid from docdetail doc,docdummydetail dummy where doc.id = dummy.docid and doc.id = ?",oldDocId);
            if (rs.next()) {
                dummycata = rs.getString("catelogid");
            }
            rs.executeQuery("select docStatus,docSubject from docdetail where id =? ",oldDocId);
            if(rs.next()){
                docStatus = rs.getString("docStatus");
                docSubject = rs.getString("docSubject");
            }
            DocManager dm = new DocManager();
            String date = "";
            String time = "";
            date = TimeUtil.getCurrentDateString();
            time = TimeUtil.getOnlyCurrentTimeString();
            int docId = dm.getNextDocId(rs);
            dm.setId(docId);
            dm.setDocType(12);
            dm.setMaincategory(-1);
            dm.setSubcategory(-1);
            dm.setUserCatalogId(dm.getUserCatalogId());
            dm.setSeccategory(docManager.getSeccategory());
            dm.setLanguageid(7);
            dm.setDoccontent("");
            dm.setDocstatus(docStatus);
            dm.setDocsubject(docSubject);
            dm.setDoccreaterid(docManager.getDoccreaterid());
            dm.setDocCreaterType(docManager.getDocCreaterType());
            dm.setUsertype(docManager.getUsertype());
            dm.setOwnerid(docManager.getOwnerid());
            dm.setOwnerType(docManager.getOwnerType());
            dm.setDoclastmoduserid(docManager.getDoclastmoduserid());
            dm.setDocLastModUserType(docManager.getDocLastModUserType());
            dm.setDoccreatedate(date);
            dm.setDoclastmoddate(date);
            dm.setDoccreatetime(time);
            dm.setDoclastmodtime(time);
            dm.setDoclangurage(7);
            dm.setIsapprover("0");
            dm.setIsreply("0");
            dm.setDocdepartmentid(docManager.getDocdepartmentid());
            dm.setDocreplyable("0");
            dm.setParentids("" + docId);
            dm.setOrderable("0");
            dm.setUserid(docManager.getDoccreaterid());
            dm.setDocCode(docManager.getDocCode());
            dm.setSecretLevel(docManager.getSecretLevel());

            // add as follow
            // 1.虚拟目录 2.关键字
            dm.setDummycata(dummycata);
            dm.setKeyword(docManager.getKeyword());
            dm.AddShareInfo();
            DocComInfo dc = new DocComInfo();
            DocViewer dv = new DocViewer();
            dv.setDocShareByDoc("" + docId);
            dc.addDocInfoCache("" + docId);
            dm.AddDocInfo();
            copyDocShareInfo(oldDocId, docId);
            return docId;
        } catch (Exception e) {
            new BaseBean().writeLog("====================createDocFromAnother error",e);
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 复制文档权限
     * @param fromdocid 源文档id
     * @param todocid 目标文档id
     */
    public static void copyDocShareInfo(int fromdocid,int todocid){
        try{
            if(fromdocid<=0||todocid<=0) return;
            RecordSet rs = new RecordSet();
            rs.execute("insert into docshare(docid,sharetype,seclevel,rolelevel,sharelevel,userid,subcompanyid,departmentid,roleid,foralluser,sharesource,isSecDefaultShare,orgGroupId,downloadlevel) select "+todocid+",sharetype,seclevel,rolelevel,sharelevel,userid,subcompanyid,departmentid,roleid,foralluser,sharesource,isSecDefaultShare,orgGroupId,downloadlevel from docshare where docid="+fromdocid+" and sharesource=1");
            rs.execute("insert into shareinnerdoc(sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel) select "+todocid+",type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel from shareinnerdoc where sourceid="+fromdocid+" and sharesource=1");

        } catch(Exception e){
            new BaseBean().writeLog("====================copyDocShareInfo error",e);
            e.printStackTrace();
        }
    }

    /**
     * 套红取消
     * @param id 文档id
     * @return 套红结果
     */
    public static boolean cancelTemplate(int id){
        RecordSet rs = new RecordSet();
        return rs.executeUpdate("update docdetail set hasUsedTemplet='0' where id=?",id);
    }

    /**
     * 是否有权限下载
     * @param user 当前用户
     * @param imagefileId 附件id
     * @return 下载权限判断结果
     */
    public static boolean hasPemissionDownload(User user,int imagefileId){
        if(user == null){
            return false;
        }
        RecordSet rs = new RecordSet();
        if(imagefileId <= 0){
            rs.writeLog("com.engine.odoc.util.DocUtil","======== hasPemissionDownload, imagefileId=" + imagefileId);
            return false;
        }
        int docid = 0;
        rs.executeQuery("select docid from docimagefile where imagefileid=? order by versionid desc",imagefileId);
        if(rs.next()){
            docid = rs.getInt(1);
        }
        if(docid <= 0){
            rs.writeLog("com.engine.odoc.util.DocUtil","======== hasPemissionDownload, imagefileId=" + imagefileId);
            return false;
        }
        DocViewPermission docViewPermission = new DocViewPermission();
        Map<String,Boolean> rightMap = docViewPermission.getShareLevel(docid, user,true);
        Boolean canRead = rightMap.get(docViewPermission.READ);
        if(!canRead){
            return false;
        }
        return true;
    }


    /**
     * 从输入流中输出内容保存至本地。
     * 字节流
     * @param savePath 本地保存路径
     * @param input    输入流
     * @throws IOException IO流异常
     */
    public static void saveByteStream(InputStream input, String savePath) throws IOException {
        PrintStream out = null;
        try {
            out = new PrintStream(savePath);

            int read;
            byte[] data = new byte[8192];
            while ((read = input.read(data)) != -1) {
                out.write(data, 0, read);
            }
            out.flush();
        } finally {
            if (out != null)
                out.close();
        }
    }

    /**
     * 从输入流中输出内容保存至本地。
     * 字符流
     * @param savePath 本地保存路径
     * @param stream   输入流
     * @param charset   编码集
     * @throws IOException IO流异常
     */
    public static void saveCharStream(InputStream stream, String savePath, String charset) throws IOException {
        PrintWriter out = null;
        InputStreamReader input = new InputStreamReader(stream);
        try {
            out = new PrintWriter(savePath, charset);

            int read;
            char[] data = new char[8192];
            while ((read = input.read(data)) != -1) {
                out.write(data, 0, read);
            }
            out.flush();
        } finally {
            if (out != null)
                out.close();
        }
    }


    /**
     * 通过流程requestId获取该流程最新的文档id
     * @param requestId 请求id
     * @return 流程最新文档id
     */
    @Deprecated
    public static String queryDocIdByRequestId(int requestId) {
        String sql = "select max(id) as id from docdetail where fromworkflow=?";
        return SqlUtil.querySingleField(sql,requestId);
    }

    /**
     * 获取流程最新相关文档
     * @param requestId 流程请求id
     * @return 最新文档id
     */
    public static int getDocIdByRequestId(int requestId) {
        String sql = "select max(id) as id from docdetail where fromworkflow=?";
        return Integer.parseInt(SqlUtil.querySingleField(sql, requestId));
    }


    /**
     * 根据文档id获取最新附件id
     * @param docId 文档id
     * @return 最新附件id
     */
    public static int getImageFileIdByDocId(int docId) {
        String sql = " SELECT MAX(IMAGEFILEID) AS FID FROM DOCIMAGEFILE WHERE DOCID=? ";
        return Integer.parseInt(SqlUtil.querySingleField(sql, docId));
    }

    /**
     * 根据附件id查询附件名称
     * @param imageFileId 附件id
     * @return 附件名称
     */
    public static String getImageFileNameByImageFileId(int imageFileId){
        String sql = " SELECT IMAGEFILENAME FROM IMAGEFILE WHERE IMAGEFILEID=? ";
        return SqlUtil.querySingleField(sql, imageFileId);
    }



    /**
     * 通过文档id获得最新附件并将其保存在选定文件夹中。
     * @param docId      文档id
     * @param saveFolder 保存文件到该文件夹下
     * @param fileName   文件名称，此入参为空时使用数据库保存的文档名
     * @return 保存的完整路径
     */
    public static String saveDoc(int docId, String saveFolder, String fileName) {
        int imageFileId = getImageFileIdByDocId(docId);
        if(imageFileId<0){
            return "";
        }

        String imageFileName = getImageFileNameByImageFileId(imageFileId);

        // 如果filename参数为空，则使用真实文件名作为保存的文件名
        String name = Util.null2String(fileName).equals("") ? imageFileName: fileName;
        String savePath;
        if (saveFolder.endsWith(File.separator)) savePath = saveFolder + name;
        else savePath = saveFolder + File.separator + name;

        InputStream inputStream = null;
        try {
            inputStream = ImageFileManager.getInputStreamById(imageFileId);
            saveByteStream(inputStream, savePath);
        }catch (IOException e) {
            return "";
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
        }

        return savePath;
    }

    public static void main(String[] args) {

    }



}



