package com.weaver.formmodel.mobile.utils;

import com.api.formmode.cache.ModeComInfo;
import com.weaver.formmodel.constant.Constants;
import com.weaver.formmodel.exception.MobileModeException;
import com.weaver.formmodel.util.FileHelper;
import com.weaver.formmodel.util.StringHelper;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocUpload;
import weaver.file.FileManage;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.file.multipart.UploadedFile;
import weaver.formmode.exttools.impexp.common.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.servicefiles.DataSourceXML;
import weaver.workflow.workflow.WFManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;

/**
 * 附件(图片)相关的工具类
 */
public class AttachUtil {

    /**
     * 上传文件
     * @param fu
     * @param user
     * @param modeid
     * @param workflowid
     * @param fieldid
     * @return
     */
    public static Map<String,String> uploadFileToDoc(FileUpload fu, User user,int modeid, int workflowid,int fieldid){
        Map<String,Integer> map = getDocCategoryIds(modeid, fieldid,workflowid);
        int mainid = map.get("mainid");
        int subid = map.get("subid");
        int secid = map.get("secid");
        return uploadFileToCategory(fu, user, mainid, subid, secid);
    }

    /**
     * 上传文件（返回file相关信息）
     * @param fu
     * @param user
     * @param modeid
     * @param workflowid
     * @param fieldid
     * @return
     */
    public static Map<String, Map<String, String>> uploadFileToDoc2(FileUpload fu, User user,int modeid, int workflowid,int fieldid){
        Map<String,Integer> map = getDocCategoryIds(modeid, fieldid,workflowid);
        int mainid = map.get("mainid");
        int subid = map.get("subid");
        int secid = map.get("secid");
        return uploadFileToCategory2(fu, user, mainid, subid, secid);
    }

	/**
	 * 上传文件
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @return
	 */
	public static Map<String,String> uploadFileToDoc(FileUpload fu, User user, int modeid, int workflowid){
		return  uploadFileToDoc(fu,user,modeid,workflowid,-1);
	}
    
	/**
	 * 上传附件到指定目录
	 * 
	 * @param fu
	 * @param user
	 * @param mainid
	 * @param subid
	 * @param secid
	 * @return
	 */
	public static Map<String,String> uploadFileToCategory(FileUpload fu, User user, int mainid, int subid, int secid){
		Map<String,String> fileMap = new HashMap<String,String>();
		try{
		    Hashtable<?, ?> uploadFileNames=fu.getUploadFileNames();
	        for(Object uploadFileName:uploadFileNames.keySet()){
	            String fieldKey=(String)uploadFileName;
	            UploadedFile uploadedFile=(UploadedFile)uploadFileNames.get(fieldKey);
	            String sourcefileName=StringHelper.null2String(uploadedFile.getFileName());
	            if(!StringHelper.isEmpty(sourcefileName)) {
	                int[] ids = DocUpload.uploadDocsToImgs(fu, user, new String[]{fieldKey}, mainid, subid, secid, "", "");
	                if(ids.length > 0){
	                    if(mainid <= 0 && subid <= 0 && secid <= 0){
	                        changeDocToOpen(ids[0]);
	                    }
	                    fileMap.put(fieldKey, String.valueOf(ids[0]));
	                }
	            }
	        }
		}catch(Exception e){
		    e.printStackTrace();
		}
		return fileMap;
	}

	/**
	 * 上传附件到指定目录（返回file相关信息）
	 *
	 * @param fu
	 * @param user
	 * @param mainid
	 * @param subid
	 * @param secid
	 * @return
	 */
	public static Map<String, Map<String, String>> uploadFileToCategory2(FileUpload fu, User user, int mainid, int subid, int secid){
		Map<String, Map<String, String>> fileMap = new HashMap<String, Map<String, String>>();
		try{
		    Hashtable<?, ?> uploadFileNames=fu.getUploadFileNames();
	        for(Object uploadFileName:uploadFileNames.keySet()){
	            String fieldKey=(String)uploadFileName;
	            UploadedFile uploadedFile=(UploadedFile)uploadFileNames.get(fieldKey);
	            String sourcefileName=StringHelper.null2String(uploadedFile.getFileName());
	            if(!StringHelper.isEmpty(sourcefileName)) {
	                int[] ids = DocUpload.uploadDocsToImgs(fu, user, new String[]{fieldKey}, mainid, subid, secid, "", "");
	                if(ids.length > 0){
	                    if(mainid <= 0 && subid <= 0 && secid <= 0){
	                        changeDocToOpen(ids[0]);
	                    }
											Map<String,String> file = new HashMap<String,String>();
	                    file.put("docid", String.valueOf(ids[0]));
	                    file.put("originalFileName", StringHelper.null2String(uploadedFile.getOriginalFileName()));
	                    file.put("fileSize", StringHelper.null2String(uploadedFile.getFileSize()));
	                    fileMap.put(fieldKey, file);
	                }
	            }
	        }
		}catch(Exception e){
		    e.printStackTrace();
		}
		return fileMap;
	}
	
	/**
	 * 上传文件，无权限，返回路径
	 * 
	 * @param fu
	 * @param user
	 * @return  返回文件路径
	 */
	public static Map<String,String> uploadFileToDoc(FileUpload fu, User user, boolean returnPath){
		Map<String,String> fileMap = uploadFileToDoc(fu, user, -1, -1);
		Map<String,String> imagefileMap = new HashMap<String, String>();
		if(fileMap.size() > 0){
			for(Entry<String, String> entry : fileMap.entrySet()){
				int docid = Util.getIntValue(entry.getValue());
				int imgid = convertDocToImageID(docid);
				imagefileMap.put(entry.getKey(), weaver.general.GCONST.getContextPath() + "/weaver/weaver.file.FileDownload?fileid="+imgid);
			}
		}
		return imagefileMap;
	}
	
	/**
	 * 上传文件，无权限控制
	 */
	public static Map<String,String> uploadFileToDoc(FileUpload fu, User user){
		return uploadFileToDoc(fu, user, -1, -1);
	}
	
	/**
	 * 找固定目录
	 * @return
	 */
	public static Map<String,Integer> getDocCategoryIds(int modeid, int fieldid,int workflowid){
		Map<String,Integer> map = new HashMap<String,Integer>();
		int mainid = 0;
		int subid = 0;
		int secid = 0;
		RecordSet recordSet = new RecordSet();
		if(modeid > 0){
			recordSet.executeQuery("select maincategory,subcategory,seccategory from modeinfo where  (categorytype is null or categorytype=0) and id= ?",modeid);
			if(recordSet.next()){
				mainid = Util.getIntValue(recordSet.getString("maincategory"),0);
				subid = Util.getIntValue(recordSet.getString("subcategory"),0);
				secid = Util.getIntValue(recordSet.getString("seccategory"),0);
			}
			if(fieldid> -1 ){
				recordSet.executeQuery("select * from mode_fileuploadset where modeid = ? and fieldid =?",modeid,fieldid);
				if(recordSet.next() &&  Util.getIntValue(recordSet.getString("categorytype"),9) != 9){
					mainid = Util.getIntValue(recordSet.getString("maincategory"),0);
					subid = Util.getIntValue(recordSet.getString("subcategory"),0);
					secid = Util.getIntValue(recordSet.getString("seccategory"),0);
				}
			}

		}else if(workflowid > 0){
			WFManager WFManager = new WFManager();
			WFManager.setWfid(workflowid);
			try {
				WFManager.getWfInfo();
				int catelogType = WFManager.getCatelogType();
				if(catelogType==0){
					String tempcategory=WFManager.getDocCategory();
					String maincategory=tempcategory.substring(0,tempcategory.indexOf(','));
					String subcategory=tempcategory.substring(tempcategory.indexOf(',')+1,tempcategory.lastIndexOf(','));
					String seccategory=tempcategory.substring(tempcategory.lastIndexOf(',')+1,tempcategory.length());
					
					mainid = Util.getIntValue(maincategory,0);
					subid = Util.getIntValue(subcategory,0);
					secid = Util.getIntValue(seccategory,0);
				}
			} catch (Exception e) {
				recordSet.writeLog(e.toString());
			}
		}
		map.put("mainid", mainid);
		map.put("subid", subid);
		map.put("secid", secid);
		return map;
	}
	
	/**
	 * @param docid
	 * 将文档转为无权限文档
	 */
	public static void changeDocToOpen(int docid){
		RecordSet rs = new RecordSet();
		rs.execute("select docid,imagefileid from DocImageFile where docid="+docid+" order by docid desc");
		if(rs.next()){
			String imagefileid = rs.getString("imagefileid");
			//往DocPicUpload插入imagefileid 无权限控制
			rs.execute("insert into DocPicUpload(imagefileid)values("+imagefileid+")");
		}
	}
	
	/**
	 * 转换文档id 为 图片id
	 * @param docid
	 * @return
	 */
	public static int convertDocToImageID(int docid){
		List<String> datas = convertDocsToImageID(String.valueOf(docid));
		return (datas != null && datas.size() > 0) ? Util.getIntValue(datas.get(0)) : -1;
	}
	
	
	/**
	 *  转换文档id 根据文档ID查询所有的图片ID
	 * @param docids
	 * @return
	 */
	public static Map<String, List<String>> getAllImagesByDocids(String docids){
		Map<String, List<String>> dataMap = new HashMap<String,List<String>>();
		if(StringHelper.isNotEmpty(docids)){
			RecordSet rs = new RecordSet();
			rs.execute("select docid,imagefileid from DocImageFile where docid in ("+docids+") order by docid desc");
			while(rs.next()){
				String docid = rs.getString("docid");
				List<String> imagefileidList = dataMap.get(docid);
				if(imagefileidList == null){
					imagefileidList = new ArrayList<String>();
					dataMap.put(docid, imagefileidList);
				}
				imagefileidList.add(rs.getString("imagefileid"));
			}
		}
		return dataMap;
	}
	
	/**
	 * 转换文档id 为 图片id (适用多文档)
	 * @param docids
	 * @return
	 */
	public static List<String> convertDocsToImageID(String docids){
		List<String> datas = new ArrayList<String>();
		if(StringHelper.isNotEmpty(docids)){
			RecordSet rs = new RecordSet();
			Map<String, List<Map<String, Object>>> dataMap = new HashMap<>();
			rs.execute("select docid,imagefileid from DocImageFile where docid in ("+docids+") order by docid desc");
			while(rs.next()){
				String docid = rs.getString("docid");
				List<Map<String, Object>> docList = dataMap.computeIfAbsent(docid, k -> new ArrayList<>());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("docid", docid);
				map.put("imagefileid", rs.getString("imagefileid"));
				docList.add(map);
			}
			//保证图片显示顺序和字段值一样
			String[] arrayids = docids.split(",");
			for (String arrayid : arrayids) {
				List<Map<String, Object>> docList = dataMap.get(arrayid);
				if (docList == null) {
					continue;
				}
				for (Map<String, Object> doc : docList) {
					datas.add((String) doc.get("imagefileid"));
				}
			}
		}
		return datas;
	}
	public static String convertDocsToImageHtml(String docIds){
	    return convertDocsToImageHtml(docIds, "");
	}
	/**
	 * 将文档id 转换为 图片Html供前台显示
	 * @param docIds
	 * @return
	 */
	public static String convertDocsToImageHtml(String docIds, String empowStr){
		List<String> imgArr = AttachUtil.convertDocsToImageID(docIds);
		if(imgArr.isEmpty()){
			return "";
		}
		String uuid = MobileCommonUtil.getUUID();
		String html = "<div class=\"wev-img-wrapper\">";
		for(int i = 0; i < imgArr.size(); i++){
			html += "<img class=\"wev-img lazyload\" data-src=\""+weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid="+imgArr.get(i)+empowStr+"\" data-groupid=\"group_" + uuid + "\"/>";
		}
		html += "</div>";
		return html;
	}
	
	/**
	 * 将文档id 转换为 图片Html供前台显示 （九宫格样式）
	 * @param docIds
	 * @return
	 */
	public static String convertDocsToImageHtmlWithGrid(String docIds){
	    return convertDocsToImageHtmlWithGrid(docIds, "");
	}
	public static String convertDocsToImageHtmlWithGrid(String docIds, String empowStr){
		List<String> imgArr = AttachUtil.convertDocsToImageID(docIds);
		if(imgArr.isEmpty()){
			return "";
		}
		String uuid = MobileCommonUtil.getUUID();
		String html = "";
		if(imgArr.size() == 1){
			html = "<div class=\"wev-img-wrapper\"><img class=\"wev-grid-img wev-imggrid-1p lazyload\" data-groupid=\"group_" + uuid + "\" data-src=\""+weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=" + imgArr.get(0) + empowStr + "\"/></div>";
		} else {
			String picCss = "";
			if(imgArr.size() == 4){
				picCss = "4p";
			} else {
				picCss = "10p";
			}
			html = "<div class=\"wev-img-wrapper wev-imggrid wev-imggrid-" + picCss + "\">";
			html += "<ul class=\"wev-imggrid-inner wev-imggrid-" + picCss + "-inner wev-imgflex\">";
			for(int i = 0; i < imgArr.size(); i++){
				html += "<li class=\"wev-grid-img\"><img data-groupid=\"group_" + uuid + "\" class=\"lazyload\" data-src=\""+weaver.general.GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=" + imgArr.get(i) + empowStr + "\"/></li>";
			}
			html += "</ul></div>";
		}
		return html;
	}
	
	public static List<Map<String, Object>> convertDocsToFileMetaList(String docids){
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		if(StringHelper.isNotEmpty(docids)){
			RecordSet recordSet = new RecordSet();
			Map<String, List<Map<String, Object>>> dataMap = new HashMap<>();
			
			int prohibitDownload = 0;
			recordSet.executeQuery("select datavalue from ECOLOGY_MESSAGE_VALVE_CONFIG where type='prohibitDownload' and dataKey='prohibitDownloadSwatch'");
	    	if(recordSet.next()){
	    		prohibitDownload = Util.getIntValue(recordSet.getString("datavalue"), 0);
	    	}
			
			recordSet.execute("select docid, a.imagefileid, a.imagefilename, fileSize, b.miniimgpath from DocImageFile a, imagefile b, (select id, max(versionid) versionid from DocImageFile where docid in ("+docids+") group by id) c where a.imagefileid = b.imagefileid and a.versionId = c.versionid and a.docid in ("+docids+") order by a.docid desc");
			while(recordSet.next()){
				String docid = recordSet.getString("docid");
				List<Map<String, Object>> docList = dataMap.computeIfAbsent(docid, k -> new ArrayList<>());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("docid", docid);
				map.put("imagefileid", recordSet.getString("imagefileid"));
				map.put("imagefilename", recordSet.getString("imagefilename"));
				map.put("miniimgpath", recordSet.getString("miniimgpath"));
				map.put("fileSize", recordSet.getFloat("fileSize"));
				docList.add(map);
			}
			String[] arrayids = docids.split(",");
			for (String arrayid : arrayids) {
				List<Map<String, Object>> docList = dataMap.get(arrayid);
				if (docList == null) {
					continue;
				}
				for (Map<String, Object> doc : docList) {
					Map<String, Object> fileMeta = new HashMap<String, Object>();
					String imageFileName = StringHelper.null2String(doc.get("imagefilename"));
					int index = imageFileName.lastIndexOf(".");
					String suffix = "";
					if (index != -1) {
						suffix = imageFileName.substring(index + 1);
					}

					float fileSize = (Float) doc.get("fileSize");
					String showSize = "";
					if (fileSize >= (1024 * 1024)) {
						showSize = StringHelper.numberFormat2(fileSize / 1024 / 1024) + "M";
					} else if (fileSize >= 1024) {
						showSize = Math.floor(fileSize / 1024) + "K";
					} else {
						showSize = fileSize + "B";
					}
					String fileId = StringHelper.null2String(doc.get("imagefileid"));
					fileMeta.put("docid", arrayid);
					fileMeta.put("imagefileid", fileId);
					fileMeta.put("miniimgpath", StringHelper.null2String(doc.get("miniimgpath")));
					fileMeta.put("suffix", suffix);
					fileMeta.put("name", imageFileName);
					fileMeta.put("size", showSize);
					fileMeta.put("prohibitDownload", prohibitDownload);
					resultList.add(fileMeta);
				}
			}
		}
		return resultList;
	}

	public static String convertDocsToFileHtml(String docIds){
	    return convertDocsToFileHtml(docIds, "");
	}
	/**
	 * 将文档id 转换为 附件Html供前台显示
	 * @param docIds
	 * @return
	 */
	public static String convertDocsToFileHtml(String docIds, String empowStr){
		List<Map<String, Object>> fileMetaList = convertDocsToFileMetaList(docIds);
		if(fileMetaList.isEmpty()){
			return "";
		}
		
		String html = "<ul class=\"wev-file-wrapper\">";
		for(int i = 0; i < fileMetaList.size(); i++){
    		Map<String, Object> map = fileMetaList.get(i);
    		String imageFileName = StringHelper.null2String(map.get("name"));
			String imagefileid =  StringHelper.null2String(map.get("imagefileid"));
			String docid =  StringHelper.null2String(map.get("docid"));
			String suffix = StringHelper.null2String(map.get("suffix"));
			
			String className = "wev-file";
			if(suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("gif") || suffix.equalsIgnoreCase("bmp")) {
				className += " wev-pic-file";
    		}else if(suffix.equalsIgnoreCase("doc") || suffix.equalsIgnoreCase("docx")) {
    			className += " wev-word-file";
    		}else if(suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx")) {
    			className += " wev-excel-file";
    		}else if(suffix.equalsIgnoreCase("pdf")) {
    			className += " wev-pdf-file";
    		}else if(suffix.equalsIgnoreCase("htm") || suffix.equalsIgnoreCase("html")) {
    			className += " wev-html-file";
    		}else if(suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx")) {
    			className += " wev-ppt-file";
    		}
			
			String filename = imageFileName + " (" + map.get("size") + ")";
			html += "<li class=\""+className+"\" data-id=\""+imagefileid+"\" data-authorize=\""+empowStr+"\" data-docid=\""+docid+"\" data-name=\""+MobileCommonUtil.encode(imageFileName)+"\"><span>"+filename+"</span><span class=\"wev-file-download\"></span></li>";
		}
		html += "</ul>";
		return html;
	}
	
	/**
	 * 将base64 上传 最后转换为文档id返回
	 * @param fileName
	 * @param uploaddata
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @param fieldid
	 * @return
	 */
	public static int convertFileBase64ToDoc(String fileName,String uploaddata, FileUpload fu, User user, int modeid, int workflowid,int fieldid){
		try{
			Map<String,Integer> map = getDocCategoryIds(modeid,fieldid, workflowid);
			int mainid = map.get("mainid");
			int subid = map.get("subid");
			int secid = map.get("secid");
			return convertFileBase64ToDoc(fileName,uploaddata,fu,user,modeid,workflowid,mainid,subid,secid);
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * 上传 最后转换为文档id返回
	 * @param fileName
	 * @param uploaddata
	 * @param fu
	 * @param user
	 * @param workflowid
	 * @param mainid
	 * @param subid
	 * @param secid
	 * @param modeid
	 * @return
	 */
	public static int convertFileBase64ToDoc(String fileName,String uploaddata, FileUpload fu, User user, int modeid,int workflowid,int mainid,int subid,int secid){
		try{
			String filetype ="";
			if(fileName.contains(".")){
				filetype = fileName.substring(fileName.lastIndexOf('.') + 1);
			}
			MobileUpload mupload = new MobileUpload(fu.getRequest(), mainid, subid, secid);
			int docid = mupload.upload(fileName, uploaddata, filetype, user, "", "");
			if(modeid == -1 && workflowid == -1){
				changeDocToOpen(docid);
			}
			return docid;
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}


	/**
	 * 将base64 上传 最后转换为文档id返回
	 * @param fileName
	 * @param uploaddata
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @return
	 */
	public static int convertFileBase64ToDoc(String fileName,String uploaddata, FileUpload fu, User user, int modeid, int workflowid){
		return convertFileBase64ToDoc(fileName,uploaddata,fu,user,modeid,workflowid,-1);
	}

	/**
	 * 将base64 上传 最后转换为文档id返回
	 * @param base64Content
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @return
	 */
	public static int convertImageBase64ToDoc(String base64Content, FileUpload fu, User user, int modeid, int workflowid){
		return convertImageBase64ToDoc(base64Content,fu,user,modeid,workflowid,MobileCommonUtil.getHtmlLabelName(390149, user.getLanguage(), "移动建模图片附件")+"-"+System.currentTimeMillis());
	}

	/**
	 *
	 * @param base64Content
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param fieldid
	 * @param workflowid
	 * @param fileName
	 * @return
	 */
	public static int convertImageBase64ToDoc(String base64Content, FileUpload fu, User user, int modeid, int fieldid,int workflowid,String fileName){
		try{
			Map<String,Integer> map = getDocCategoryIds(modeid,fieldid, workflowid);
			int mainid = map.get("mainid");
			int subid = map.get("subid");
			int secid = map.get("secid");
			return convertImageBase64ToDoc(base64Content,fu,user,modeid,mainid,subid,secid,workflowid,fileName);
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}


	public  static int convertFileIdToDocid(int fileid){
		int docid = -1;
		RecordSet rs = new RecordSet();
		rs.executeQuery("select docid from docimagefile  where imagefileid = ? ", fileid);
		if(rs.next()){
			docid = rs.getInt("docid");
			return docid;
		}else{
			return docid;
		}

	}
	/**
	 *
	 * @param base64Content
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param mainid
	 * @param subid
	 * @param secid
	 * @param workflowid
	 * @param fileName
	 * @return
	 */
	public static int convertImageBase64ToDoc(String base64Content, FileUpload fu, User user, int modeid, int mainid,int subid,int secid,int workflowid,String fileName){
		try{
			String[] contentArr = base64Content.split(";");

			String imgtype = contentArr[0].substring(11);
			if("jpeg".equalsIgnoreCase(imgtype)){
				imgtype = "jpg";
			}
			String uploaddata = contentArr[1].substring(7);
			MobileUpload mupload = new MobileUpload(fu.getRequest(), mainid, subid, secid);
			int docid = mupload.upload(fileName + "." + imgtype, uploaddata, "image/png", user, "", "");
			if(modeid == -1 && workflowid == -1){
				changeDocToOpen(docid);
			}
			return docid;
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * 将base64 上传 最后转换为文档id返回
	 * @param base64Content
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @param fileName
	 * @return
	 */
	public static int convertImageBase64ToDoc(String base64Content, FileUpload fu, User user, int modeid, int workflowid,String fileName){
		return convertImageBase64ToDoc(base64Content,fu,user,modeid,Util.getIntValue(fu.getParameter("fieldid")),workflowid,fileName);
	}

	public static String convertDocsToAudioHtml(String docIds, String empowStr, User user){
		if(StringHelper.isEmpty(docIds)){
			return "";
		}
		//docIds为docid和音频文件path混合的字符串
		String[] docIdArr = docIds.split(",");
		
		JSONArray audioUrlList = new JSONArray();
		for(String docId : docIdArr){
			if(StringHelper.isEmpty(docId)) continue;
			boolean isInt = Util.getIntValue(docId) != -1;
			if(isInt){
				List<String> fileIdList = convertDocsToImageID(docId);
				for (String fileId : fileIdList) {
					audioUrlList.add(weaver.general.GCONST.getContextPath() + "/weaver/weaver.file.FileDownload?fileid=" + fileId + empowStr);
				}
			} else {
				audioUrlList.add(docId);
			}
		}
		String html = "";
		if(audioUrlList.size() > 0){
            String uuid = MobileCommonUtil.getUUID();
            html += "<div id=\"audios_"+uuid+"\" class=\"wev-audio-list\"></div>"
                    + "<script>"
                    + "var audioUrlList = "+audioUrlList.toString()+".filter(function(fileId) {return !!fileId;});\n"
                    + "audioUrlList.forEach(function(src){\n"
                    + "    require(['voiceHelper'], function (Voice) {\n"
                    + "        new Voice(src, {\n"
                    + "            container: $('#audios_"+uuid+"'),\n"
                    + "            canDelete: false\n"
                    + "        });\n"
                    + "    });\n"
                    + "});\n"
                    + "</script>";
        }
		return html;
	}
	
	/**
	 * 根据fileid获取上传文件服务器路径
	 * 对于服务器文件上传到阿里云后被删除获取不到的情况，从阿里云获取后在filerealpath下新建文件
	 * @return
	 */
	public static String getFileRealPath(int fileid){
		if(fileid == 0 || fileid == -1){
			throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(390154, MobileCommonUtil.getLanguageForPC(), "导入文件不能为空"));
		}
	
		RecordSet rs=new RecordSet();
		String filerealpath="";
		String isaesencrypt = "";
		String aescode = "";
		
		rs.executeQuery("select filerealpath,isaesencrypt,aescode from imagefile where imagefileid = ? ", fileid);
		if(rs.next()){
			filerealpath =  rs.getString("filerealpath");
			isaesencrypt = Util.null2String(rs.getString("isaesencrypt"));
			aescode = Util.null2String(rs.getString("aescode"));
		}
		
		if("".equals(filerealpath)){
			throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(390155, MobileCommonUtil.getLanguageForPC(), "压缩文件上传失败，filerealpath为空"));
		}
		
		File zipFile = new File(filerealpath);
		if(!zipFile.exists()){//判断服务器上是否存在上传的文件
		    //从阿里云获取文件流 并创建文件。
            InputStream in = ImageFileManager.getInputStreamById(fileid);
            FileHelper.writeFile(in, filerealpath);
		}else{
		    try {
		    	if("1".equals(isaesencrypt)){//文件存在且加密。
		            String fileNameWin = filerealpath.substring(filerealpath.lastIndexOf("/")+1);  
		            String fileNameUnix = filerealpath.substring(filerealpath.lastIndexOf("\\")+1); 
		    		String zipFileName = "";
		            //对没有后缀的文件复制后的文件增加.zip
		    		if((!fileNameWin.equals(filerealpath) && fileNameWin.indexOf(".") != -1) || (!fileNameUnix.equals(filerealpath) && fileNameUnix.indexOf(".") != -1)){
		    			int dot = filerealpath.lastIndexOf(".");
			    		zipFileName =  filerealpath.substring(0, dot) + "_" + StringUtils.getRandom() + "." + filerealpath.substring(dot + 1);
		    		}else{
		    			zipFileName =  filerealpath + "_" + StringUtils.getRandom() + ".zip";
		    		}
		    		
		    		FileManage.copy(filerealpath, zipFileName, isaesencrypt, aescode);
		    		
					zipFile.delete();//删除复制前的文件
		    		return zipFileName;
		    	}
			} catch (IOException e) {
				e.printStackTrace();
				throw new MobileModeException(MobileCommonUtil.getHtmlLabelName(390156, MobileCommonUtil.getLanguageForPC(), "导入文件解密复制失败：")+filerealpath);
			}
		}
		return filerealpath;
	}
	
	/**
	 * 获取临时赋权url
	 * @param modeid
	 * @param billid
	 * @return
	 */
	public static String getEmpowStr(int modeid, String billid){
	    if(modeid == -1) return "";
	    ModeComInfo modeCache = new ModeComInfo();
	    String empowType = modeCache.getEmpowmenttype(String.valueOf(modeid));
        if (!"".equals(empowType)&& "0".equals(empowType.split(",")[0])) {
            return "&formmode_authorize=formmode_authorize&moduleid=formmode&authorizemodeId=" + modeid + "&authorizeformmodebillId=" + billid;
        }
        return "";
	}
	/**
     * 获取临时赋权url
     * @param modeid
     * @param billid
     * @return
     */
    public static String getEmpowStr(int modeid, int formid, String billid){
        if(formid == -1 && modeid == -1) return "";
        if(modeid == -1){
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from modeinfo where formid=? order by id asc", formid);
            if(rs.next()){
                modeid = rs.getInt("id");
            }
            rs = null;
        }
        return getEmpowStr(modeid, billid);
    }

	/**
	 * 生成指定高宽缩略图，并返回文档id
	 * @param originDocid 原始文档id
	 * @param width
	 * @param height
	 * @param fu
	 * @param user
	 * @param modeid
	 * @param workflowid
	 * @return
	 */
	public static int generateThumbnail(int originDocid, int width, int height, FileUpload fu, User user, int modeid, int workflowid) {
		int thumbnail = -1;
		int imagefileid = convertDocToImageID(originDocid);
		if (imagefileid > -1) {
			InputStream imagefile = null;
			try {
				ImageFileManager ifm = new ImageFileManager();
				ifm.getImageFileInfoById(imagefileid);
				if (!ifm.getImageFileType().toLowerCase().contains("image")) return -1;

				String[] nameSplit = ifm.getImageFileName().split("\\.");
				String mineType = nameSplit.length > 1 ? nameSplit[1] : "jpg";
				ByteArrayOutputStream outStream = new ByteArrayOutputStream();
				imagefile = ifm.getInputStream();
				if (imagefile != null) {
					Thumbnails.of(imagefile).size(width, height).toOutputStream(outStream);
					Map<String, Integer> map = getDocCategoryIds(modeid, Util.getIntValue(fu.getParameter("fieldid")) , workflowid);
					int mainid = map.get("mainid");
					int subid = map.get("subid");
					int secid = map.get("secid");

					MobileUpload mupload = new MobileUpload(fu.getRequest(), mainid, subid, secid);
					thumbnail = mupload.upload(nameSplit[0] + "_thumbnail" + "." + mineType, outStream.toByteArray(), "image/png", user, "", "");
					if (modeid == -1 && workflowid == -1) {
						changeDocToOpen(thumbnail);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			} finally {
				try {
					imagefile.close();
				} catch (Exception e) {
				}
			}
		}
		return thumbnail;
	}

	/**
	 * 文件转Base64
	 * @param fu
	 * @return
	 */
	public static String convertFileToBase64(FileUpload fu) {
        try{
            Hashtable<?, ?> uploadFileNames=fu.getUploadFileNames();
            for(Object uploadFileName:uploadFileNames.keySet()){
                String fieldKey=(String)uploadFileName;
                UploadedFile uploadedFile=(UploadedFile)uploadFileNames.get(fieldKey);
                String fileName = Util.null2String(uploadedFile.getFileName());
                String filePath = Util.null2String(uploadedFile.getFilePath());
                if(!StringHelper.isEmpty(fileName)) {
                    byte[] b = Files.readAllBytes(Paths.get(filePath, fileName));
                    return Base64.getEncoder().encodeToString(b);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
	
	public static String getAttachIdentify(String dataSource, String tableName, String fieldName, String billid){
	    if(StringHelper.isEmpty(dataSource)){
	        dataSource = DataSourceXML.SYS_LOCAL_POOLNAME;
	    }
	    String identify = dataSource + Constants.SPLIT + tableName + Constants.SPLIT + fieldName + Constants.SPLIT + billid;
	    return identify.toLowerCase();
	}


}
