package weaver.interfaces.htsc.wpscenter.utils;

import net.sf.json.JSONObject;
import org.apache.commons.io.output.ByteArrayOutputStream;
import weaver.docs.docs.ImageFileIdUpdate;
import weaver.file.ImageFileManager;
import weaver.file.other.UrlParamsUtil;
import weaver.general.DesUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Tools {
    private static Logger log = LoggerFactory.getLogger(Tools.class);

    public static final String W_FILES_EXT = ",doc,dot,wps,wpt,docx,dotx,docm,dotm,rtf,";
    public static final String S_FILES_EXT = ",xls,xlt,et,xlsx,xltx,csv,xlsm,xltm,";
    public static final String P_FILES_EXT = ",ppt,pptx,pptm,ppsx,ppsm,pps,potx,potm,dpt,dps,";
    public static final String F_FILES_EXT = ",pdf,";
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    /**
     * WPS 文件ID的前缀，用于与OA中的id区分
     */
    public static final String WPS_FILEID_PREFIX = "wps_";

    public Logger getLog() {
        return log;
    }

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

    public static String getDocType(String ext){
        String type = "";
        String extfix = "," + ext + ",";
        if(W_FILES_EXT.contains(extfix)) {
            type = "w";
        } else if(S_FILES_EXT.contains(extfix)) {
            type = "s";
        } else if(P_FILES_EXT.contains(extfix)) {
            type = "p";
        } else if(F_FILES_EXT.contains(extfix)) {
            type = "f";
        }
        return type;
    }

    public static int getUserLanguageid(User user){
        return null == user ? 7 : user.getLanguage();
    }

    public static boolean isEmptyOrNull(String str){
        return null == str || str.isEmpty();
    }

    public static String null2String(String s) {
        return s == null ? "" : s;
    }

    public static String null2String(String s,String def) {
        return s == null ?(def==null?"":def) : s;
    }

    public static Long getLongValue(String v) {
        return getLongValue(v, -1l);
    }

    public static Long getLongValue(String v, Long def) {
        try {
            return Long.parseLong(v);
        } catch (Exception ex) {
            return def;
        }
    }

    public static String getJsonData(JSONObject json, String key){
        if(null == json){
            return "";
        }
        if(!json.containsKey(key)){
            return "";
        }
        Object o = json.get(key);
        return Util.null2String(o);
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        copy((InputStream)input, (OutputStream)output);
        return output.toByteArray();
    }

    public static String toString(InputStream input) throws Exception {
        return toStringWithLineBreak(input, null);
    }

    public static String toStringWithLineBreak(InputStream input,
                                               String lineBreak) throws Exception {
        List<String> lines = toLines(input);
        StringBuilder sb = new StringBuilder(20480);
        for (String line : lines) {
            sb.append(line);
            if (lineBreak != null) {
                sb.append(lineBreak);
            }
        }
        return sb.toString();
    }

    public static List<String> toLines(InputStream input) throws Exception {
        return toLines(input, "UTF-8");
    }

    public static List<String> toLines(InputStream input, String encoding)
            throws Exception {
        InputStreamReader insreader = new InputStreamReader(input, encoding);
        BufferedReader bin = new BufferedReader(insreader);
        List<String> lines = new ArrayList<String>();
        String line;
        while ((line = bin.readLine()) != null) {
            lines.add(line);
        }
        bin.close();
        insreader.close();
        return lines;
    }

    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        return count > 2147483647L ? -1 : (int)count;
    }

    public static long copyLarge(InputStream input, OutputStream output) throws IOException {
        return copyLarge(input, output, new byte[4096]);
    }

    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count = 0L;

        int n;
        for(boolean var5 = false; -1 != (n = input.read(buffer)); count += (long)n) {
            output.write(buffer, 0, n);
        }
        return count;
    }

    public static void cloze(Closeable c) {
        if(c == null) {
            return;
        }
        try{
            c.close();
        }catch (Exception e) {}
    }

    public static Long getTimeSeconds(String date, String time){
        long createtime = 0;
        if(null == date || date.isEmpty() || null == time || time.isEmpty()){
            return createtime;
        }
        Calendar calendar = TimeUtil.getCalendar(date + " " + time);
        if(calendar == null)
            calendar = Calendar.getInstance();
        createtime = calendar.getTimeInMillis()/1000;
        return createtime;
    }

    public static String getNewWpsFileid(){
        return WPS_FILEID_PREFIX + new ImageFileIdUpdate().getImageFileNewId();
    }

    public static String getDownloadUrl(int fileidInt, String fromMould){
        UrlParamsUtil urlParamsUtil = new UrlParamsUtil();
        String downloadUrl = urlParamsUtil.getDownloadUrl(fileidInt,fromMould);

        // TODO 如果没有填写地址如何处理

        return downloadUrl;
    }

    public static String getFromMould(String fromMould) {
        // 来源模块优化，防止空值
        fromMould = null == fromMould || "".equalsIgnoreCase(fromMould) || "null".equals(fromMould) ? "ecology" : fromMould;
        return fromMould;
    }

    public static int saveToImageFile(byte[] data, String filename, String comefrom){
        if(data.length <= 0 || Tools.isEmptyOrNull(filename)) {
            return -1;
        }
        // 保存数据
        ImageFileManager ifm = new ImageFileManager();
        ifm.setData(data);
        ifm.setComefrom(null == comefrom || "".equals(comefrom) ? "get_file_from_wps" : comefrom);
        ifm.setImagFileName(filename);
        return ifm.saveImageFile();
    }

    public int saveToImageFile(InputStream file, String filename, String comefrom){
        if(null == file || Tools.isEmptyOrNull(filename)) {
            return -1;
        }
        byte[] fileData = new byte[0];
        try {
            fileData = toByteArray(file);
        } catch (IOException e) {
            log.error(e);
        } finally {
            cloze(file);
        }

        if(fileData.length <= 0) {
            return -1;
        }
        
        // 保存数据
        ImageFileManager ifm = new ImageFileManager();
        ifm.setData(fileData);
        ifm.setComefrom(null == comefrom || "".equals(comefrom) ? "get_file_from_wps" : comefrom);

        filename = Util.null2String(filename);
        filename = filename.contains(".") ?
                (filename.substring(0,filename.lastIndexOf(".")) + filename.substring(filename.lastIndexOf(".")).toLowerCase())
                : filename;

        ifm.setImagFileName(filename);
        return ifm.saveImageFile();
    }

    public static String getFileNameWithLowerCaseSuffix(String filename) {
        if(isEmptyOrNull(filename) || !filename.contains(".")){
            return filename;
        }
        int idx = filename.lastIndexOf(".");
        return filename.substring(0,idx) + filename.substring(idx).toLowerCase();
    }

    public static Boolean intersection(String str1, String str2, String separator) {
        if(isEmptyOrNull(str1) || isEmptyOrNull(str2)) {
            return false;
        }

        String [] str1Array = str1.split(separator);
        if(str1Array.length <= 0) {
            return false;
        }
        List<String> temp = Arrays.asList(str1Array);
        List<String> str1List = new ArrayList<String>();
        str1List.addAll(temp);

        String [] str2Array = str2.split(separator);
        if(str2Array.length <= 0) {
            return false;
        }
        temp = Arrays.asList(str2Array);
        List<String> str2List = new ArrayList<String>();
        str2List.addAll(temp);

        // 取交集
        str1List.retainAll(str2List);
        // 如果存有值，表示符合要求
        return !str1List.isEmpty();
    }

    public static String getEncrypt(String str) {
        String result = "";
        try {
            DesUtil des = new DesUtil();
            result = des.encrypt(str);
        } catch (Exception e) {
            result = "-1";
        }
        return result;
    }

    public static String getDecrypt(String encrypted) {
        String dncrypted = "";
        try {
            DesUtil des = new DesUtil();
            dncrypted = des.decrypt(encrypted);
        } catch (Exception e) {
            dncrypted = "-1";
        }
        return dncrypted;
    }

    public static Boolean dateBeforeCompare(String dateStr1, String dateStr2) {
        try {
            Date date1 = sdf.parse(dateStr1);
            Date date2 = sdf.parse(dateStr2);
            return date1.before(date2);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return false;
    }

    public static Map<String, String> getMapStringString(Map<String, Object> param) {
        Map<String, String> result = new HashMap<String, String>();
        if(null == param || param.isEmpty()) {
            return  result;
        }

        Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            result.put(entry.getKey(), Util.null2String(entry.getValue()));
        }

        return result;
    }

    public static String getOSSDownloadUrlForWps(String userAgent, String ossUrl){
        if(Tools.isEmptyOrNull(ossUrl) || !ossUrl.startsWith("http://") && ossUrl.startsWith("https://")) {
            return ossUrl;
        }

        String obsinnerurl = Config.getPropertyValue("doccenter_ossInnerUrl");
        if(Tools.isEmptyOrNull(obsinnerurl)) {
            return ossUrl;
        }

        String wpsUA4View = Config.getPropString("doccenter_wpsUA4View4Download","Apache-HttpClient");
        String wpsUA4Edit = Config.getPropString("doccenter_wpsUA4Edit4Download","Go-http-client");

        if(Config.isLogInfo()) {
            log.info("userAgent:[" + userAgent + "], ossUrl:[" + ossUrl + "]");
        }

        if(Tools.isEmptyOrNull(userAgent) ||    // UA 是空的，不做处理
                Tools.isEmptyOrNull(wpsUA4View) && Tools.isEmptyOrNull(wpsUA4Edit) ||   // 没有配置UA，不做处理
                 !userAgent.contains(wpsUA4View) && !userAgent.contains(wpsUA4Edit)){   // UA不包含对应参数，不做处理
            return ossUrl;
        }

        // 去掉头部
        String resultUrl = ossUrl.replace("http://", "").replace("https://","");
        resultUrl = obsinnerurl + resultUrl.substring(resultUrl.indexOf("/"));

        if(Config.isLogInfo()) {
            log.info("resultUrl:[" + resultUrl + "]");
        }
        return resultUrl;
    }
}
