package com.engine.doc.util;

import com.api.doc.detail.util.ImageConvertUtil;
import com.api.doc.util.DocWKNonStandardUtil;
import org.apache.commons.lang.StringEscapeUtils;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import org.apache.xpath.operations.Bool;
import weaver.archives.util.ArchivesFModeUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.docs.docs.AddWater.DocAddWaterForSecond;
import weaver.docs.docs.util.PdfWaterMarkUtil;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.request.RequestManager;
import weaver.wps.CommonUtil;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author：tongh
 * date：2019-2-26 14:38
 * detail： 处理水印工具类
 */
public class WaterMarkUtil extends BaseBean{

    public static final String DOC_USERNAME = "$UserName";
    public static final String DOC_USERCODE = "$UserCode";
    public static final String DOC_USERPHONE = "$UserPhone";
    public static final String DOC_USEREMAIL = "$UserEmail";
    public static final String DOC_USERID = "$UserId";
    public static final String DOC_USERLOGINNAME = "$UserLoginName";
    public static final String DOC_USERDEPART = "$UserDepart";
    public static final String DOC_USERSUB = "$UserSub";
    public static final String DOC_USERDATA = "$NowData";
    public static final String DOC_USERTIME = "$NowTime";
    public static final String DOC_REQUESTNAME = "$ReqName";
    public static final String DOC_REQUESTID = "$ReqId";
    public static final String DOC_REQUESTMARK = "$ReqMark";

    //水印设置页面的位置
    public static final String SYSTEMWMMODULE = "systemwatermark";
    public static final String DOCUMENTWMMODULE = "documentwatermark";

    //设置水印 查看、下载、打印的位置
    public static final String DOCUMENTWATERMARK = "documentwatermark";
    public static final String SECCATEGORYWATERMARK = "seccategorywatermark"; //目录处的设置
    public static final String SECCATEGORYWATERMARKTEMPLATE = "seccategorywatermarktemplate"; //目录模板处的设置

    //设置目录水印的 查看、下载、打印、全局变量
    public static final String SECCATEGORYVIEW = "wmforview";
    public static final String SECCATEGORYDOWNLOAD = "wmfordownload";
    public static final String SECCATEGORYPRINT = "wmforprint";
    public static final String SECCATEGORYWMISOPEN = "isopenwater";
    public static final String WATERCONTENTISNULL = "wmisnull";

    //下载水印要加的模块
    public static final String MOULDDOC = "ecology";
    public static final String MOULDEMAIL = "email";



    public static Map<String,String> getWmParamsMap(User user){
        if(user == null){
            return new HashMap<String,String>();
        }
        return WaterMarkUtil.getWmParamsMap(user,false);
    }

    public static Map<String,String> getWmParamsMap(User user,int fileid,String requestid){
        if(user == null){
            return new HashMap<String,String>();
        }
        return WaterMarkUtil.getWmParamsMap(user,false,fileid,requestid);
    }

    /**
     *
     * @param user
     * @param preview 是否是预览请求的接口，预览接口请求转换，当人员信息不存在时，展示水印key值
     * @return
     */
    public static Map<String,String> getWmParamsMap(User user,Boolean preview) {
        if(user == null){
            return new HashMap<String,String>();
        }
        return  getWmParamsMap(user,preview,-1,"");
    }
    public static Map<String,String> getWmParamsMap(User user,Boolean preview,int fileid,String requestid){
        if(user == null){
            return new HashMap<String,String>();
        }
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put(DOC_USERNAME,convertWmParams(DOC_USERNAME,user,preview));
        resultMap.put(DOC_USERCODE,convertWmParams(DOC_USERCODE,user,preview));
        resultMap.put(DOC_USERPHONE,convertWmParams(DOC_USERPHONE,user,preview));
        resultMap.put(DOC_USEREMAIL,convertWmParams(DOC_USEREMAIL,user,preview));
        resultMap.put(DOC_USERID,convertWmParams(DOC_USERID,user,preview));
        resultMap.put(DOC_USERLOGINNAME,convertWmParams(DOC_USERLOGINNAME,user,preview));
        resultMap.put(DOC_USERDEPART,convertWmParams(DOC_USERDEPART,user,preview));
        resultMap.put(DOC_USERSUB,convertWmParams(DOC_USERSUB,user,preview));
        resultMap.put(DOC_USERDATA,convertWmParams(DOC_USERDATA,user,preview));
        resultMap.put(DOC_USERTIME,convertWmParams(DOC_USERTIME,user,preview));
        resultMap.put(DOC_REQUESTID,convertWmParams(DOC_REQUESTID,user,preview));
        resultMap.put(DOC_REQUESTMARK,convertWmParams(DOC_REQUESTMARK,user,preview));
        resultMap.put(DOC_REQUESTNAME,convertWmParams(DOC_REQUESTNAME,user,preview));


        resultMap.put("$DOC_UserName",convertWmParams(DOC_USERNAME,user,preview));
        resultMap.put("$DOC_UserCode",convertWmParams(DOC_USERCODE,user,preview));
        resultMap.put("$DOC_UserPhone",convertWmParams(DOC_USERPHONE,user,preview));
        resultMap.put("$DOC_UserEmail",convertWmParams(DOC_USEREMAIL,user,preview));
        resultMap.put("$DOC_UserId",convertWmParams(DOC_USERID,user,preview));
        resultMap.put("$DOC_UserLoginName",convertWmParams(DOC_USERLOGINNAME,user,preview));
        resultMap.put("$DOC_UserDepart",convertWmParams(DOC_USERDEPART,user,preview));
        resultMap.put("$DOC_UserSub",convertWmParams(DOC_USERSUB,user,preview));
        resultMap.put("$DOC_NowData",convertWmParams(DOC_USERDATA,user,preview));
        resultMap.put("$DOC_NowTime",convertWmParams(DOC_USERTIME,user,preview));
        if(DocWKNonStandardUtil.open()){
            RecordSet recordSet = new RecordSet();
            RecordSet rs = new RecordSet();
            if(!"".equals(requestid)){
                resultMap.put("$ReqId",requestid);
                recordSet.executeQuery("select requestname,requestmark from 	workflow_requestbase where requestid =?",requestid);
                if (recordSet.next()){
                    resultMap.put("$ReqMark",Util.null2String(recordSet.getString("requestmark")));
                    resultMap.put("$ReqName",Util.null2String(recordSet.getString("requestname")));
                }
            }else{
                recordSet.executeQuery("select requestid from request_band_doc where docid = (select max(docid) from docimagefile where imagefileid = ?)",fileid);
                if(recordSet.next()){
                    requestid = Util.null2String(recordSet.getString("requestid"));
                    resultMap.put("$ReqId",requestid);
                    rs.executeQuery("select requestname,requestmark from 	workflow_requestbase where requestid =?",requestid);
                    if (rs.next()){
                        resultMap.put("$ReqMark",Util.null2String(rs.getString("requestmark")));
                        resultMap.put("$ReqName",Util.null2String(rs.getString("requestname")));
                    }
                }
            }
            //文档自定义字段创建
            recordSet.executeQuery("select * from cus_formdict where (scope='DocCustomFieldBySecCategory' or id in(select fieldid from cus_formfield where scope = 'DocCustomFieldBySecCategory'))");
            while (recordSet.next()){
                int id = recordSet.getInt("id");
                String fieldname = Util.null2String(recordSet.getString("fieldname"));
                String fieldlabel =  Util.null2String(recordSet.getString("fieldlabel"));
                resultMap.put("$"+fieldname,getCusfielddata(fileid,fieldname));
            }
        }

        return resultMap;
    }
    public static  String getCusfielddata(int fileid,String columnname){
        RecordSet recordSet = new RecordSet();
        try{
            recordSet.executeQuery("select "+columnname+" from cus_fielddata where scope = 'DocCustomFieldBySecCategory' and id = (select max(docid) from docimagefile where imagefileid = ?) ",fileid);
            if(recordSet.next()){
                return  Util.null2String(recordSet.getString(columnname));
            }else{
                return  "";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
    public static String convertWmParams(String Key, User user){
        return WaterMarkUtil.convertWmParams(Key,user,false);
    }

    public static String convertWmParams(String Key, User user,Boolean preview){
        String result = "";
        ResourceComInfo resourceComInfo = null;
        TimeZoneUtil timeZoneUtil = new TimeZoneUtil();
        if(DOC_REQUESTID.equals(Key) || "$ReqId".equals(Key)){

        }else if(DOC_REQUESTMARK.equals(Key) || "$ReqMark".equals(Key)){

        }else if(DOC_REQUESTNAME.equals(Key) || "$ReqName".equals(Key)){

        }else if(DOC_USERNAME.equals(Key) || "$DOC_UserName".equals(Key)){
            result = Util.formatMultiLang(user.getUsername(),user.getLanguage()+"");
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501434, user.getLanguage());
            }
        }else if(DOC_USERCODE.equals(Key) || "$DOC_UserCode".equals(Key)){
            try {
                resourceComInfo = new ResourceComInfo();
                result = resourceComInfo.getWorkcode(String.valueOf(user.getUID()));
                if( preview && (result==null || result.equals(""))){
                    result = SystemEnv.getHtmlLabelName(501435, user.getLanguage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(DOC_USERPHONE.equals(Key) || "$DOC_UserPhone".equals(Key)){
            result = user.getMobile();
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501436, user.getLanguage());
            }
        }else if(DOC_USEREMAIL.equals(Key) || "$DOC_UserEmail".equals(Key)){
            result = user.getEmail();
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501437, user.getLanguage());
            }
        }else if(DOC_USERID.equals(Key) || "$DOC_UserId".equals(Key)){
            result = String.valueOf(user.getUID());
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501438, user.getLanguage());
            }
        }else if(DOC_USERLOGINNAME.equals(Key) || "$DOC_UserLoginName".equals(Key)){
            result = user.getLoginid();
            result = Util.formatMultiLang(result,user.getLanguage()+"");
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501439, user.getLanguage());
            }
        }else if(DOC_USERDEPART.equals(Key) || "$DOC_UserDepart".equals(Key)){
            try {
                resourceComInfo = new ResourceComInfo();
                DepartmentComInfo departmentComInfo = new DepartmentComInfo();
                result = departmentComInfo.getDepartmentname(resourceComInfo.getDepartmentID(String.valueOf(user.getUID())));
                result = Util.formatMultiLang(result,user.getLanguage()+"");
                if( preview && (result==null || result.equals(""))){
                    result = SystemEnv.getHtmlLabelName(501440, user.getLanguage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(DOC_USERSUB.equals(Key) || "$DOC_UserSub".equals(Key)){
            try {
                resourceComInfo = new ResourceComInfo();
                SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
                result = subCompanyComInfo.getSubCompanyname(resourceComInfo.getSubCompanyID(String.valueOf(user.getUID())));
                result = Util.formatMultiLang(result,user.getLanguage()+"");
                if( preview && (result==null || result.equals(""))){
                    result = SystemEnv.getHtmlLabelName(501441, user.getLanguage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(DOC_USERDATA.equals(Key) || "$DOC_NowData".equals(Key)){
            result = TimeUtil.getCurrentTimeString();
            result = timeZoneUtil.getYmdLocaleDate(result);
            result = result.substring(0,10);
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501442, user.getLanguage());
            }
        }else if(DOC_USERTIME.equals(Key) || "$DOC_NowTime".equals(Key)){
            result = TimeUtil.getCurrentTimeString();
            result = timeZoneUtil.getYmdLocaleDate(result);
            result = result.substring(11);
            if( preview && (result==null || result.equals(""))){
                result = SystemEnv.getHtmlLabelName(501443, user.getLanguage());
            }
        }
        return  result;
    }

    public static Map<String,Object> getWmSetting(User user){
        return getWmSetting(null,user);
    }
    /**
     * 获取系统设置的水印
     * @param
     * @param user
     * @return
     */
    public static Map<String,Object> getWmSetting(Map<String,Object> params,User user){
        Boolean convert = false;
        String document = "";
        if(params!=null){
            //判断是否将水印正文由key值转换为value值
            String isconvert = Util.null2String(params.get("isconvert"));
            if(isconvert!=null && !isconvert.equals("")){
                convert = true;
            }
            document = Util.null2String(params.get("document"));
        }
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> wmSetting = new HashMap<>();
        result.put("api_status",true);
        if(document.equals("document")){
            String selectSql = "select isopen,watermarktype,opacity,rotate,imageid,wmwidth,wmheight,wmcontent,family,familyid,fontsize,color,algin from SystemWaterMarkSetting where module = ?";
            RecordSet selectRs = new RecordSet();
            selectRs.executeQuery(selectSql,WaterMarkUtil.DOCUMENTWMMODULE);
//            HashMap familyMap = new HashMap();

            wmSetting.put("isopen","0");
            wmSetting.put("watermarktype","1");
            wmSetting.put("opacity","20");
            wmSetting.put("rotate","20");
            wmSetting.put("imageid","");
            wmSetting.put("wmwidth","200");
            wmSetting.put("wmheight","200");
            wmSetting.put("wmcontent","");
            wmSetting.put("fontsize","14");
            wmSetting.put("familyname","");
            wmSetting.put("familyid","");

            wmSetting.put("color","");
            wmSetting.put("align","");
            wmSetting.put("wmimportset","");
            String wmimportset = "";
//            wmSetting.put("canedit", HrmUserVarify.checkUserRight("SystemSetEdit:Edit", user));
            while (selectRs.next()){
//            Map<String,Object> wmSetting = new HashMap<>();
                wmSetting.put("isopen",Util.getIntValue(selectRs.getString("isopen"),0));
                wmSetting.put("watermarktype",Util.getIntValue(selectRs.getString("watermarktype"),1));
                wmSetting.put("opacity",Util.getIntValue(selectRs.getString("opacity"),20));
                wmSetting.put("rotate",Util.getIntValue(selectRs.getString("rotate"),20));
                wmSetting.put("imageid",Util.getIntValue(selectRs.getString("imageid")));
                wmSetting.put("wmwidth",Util.getIntValue(selectRs.getString("wmwidth"),200));
                wmSetting.put("wmheight",Util.getIntValue(selectRs.getString("wmheight"),200));
                String wmcontent = Util.null2String(selectRs.getString("wmcontent"));
                if(convert){
                    Map<String,String> ParamsMap = WaterMarkUtil.getWmParamsMap(user);
                    for(Map.Entry<String,String> entry : ParamsMap.entrySet()){
                        String key = entry.getKey();
                        String value = entry.getValue();
                        wmcontent = wmcontent.replace(key,value);
                    }
                    wmcontent = delHTMLTag(wmcontent);
                }

                wmSetting.put("wmcontent",wmcontent);
//                wmSetting.put("familyinfo",familyMap);
                wmSetting.put("familyname",Util.null2String(selectRs.getString("family")));
                wmSetting.put("familyid",Util.getIntValue(selectRs.getString("familyid")));
                wmSetting.put("fontsize",Util.null2s(selectRs.getString("fontsize"),"14"));
                wmSetting.put("color",Util.null2String(selectRs.getString("color")));
                wmSetting.put("align",Util.null2String(selectRs.getString("algin")));
            }
            String selectposSql = "select wmforview,wmfordownload,wmforprint from docwatermarksecsetting where setpostion = ?";
            selectRs.executeQuery(selectposSql,WaterMarkUtil.DOCUMENTWATERMARK);
            selectRs.next();

            int wmforview = Util.getIntValue((String) selectRs.getString("wmforview"),1);
            int wmfordownload = Util.getIntValue((String) selectRs.getString("wmfordownload"),1);
            int wmforprint = Util.getIntValue((String) selectRs.getString("wmforprint"),1);
            if(wmforview==1){
                wmimportset += ",1";
            }
            if(wmfordownload==1){
                wmimportset += ",2";
            }
            if(wmforprint ==1){
                wmimportset+=",3";
            }
            if(!wmimportset.equals("")){
                wmimportset = wmimportset.substring(1);
            }
            wmSetting.put("wmimportset",wmimportset);

            //查询所有已经同步的目录id
            String selectidsSql = "select categoryid from docwatermarksecsetting where setpostion = ?";
            selectRs.executeQuery(selectidsSql,WaterMarkUtil.SECCATEGORYWATERMARK);
            String categoryids = "";
            StringBuffer sb = new StringBuffer();
            while (selectRs.next()){
                sb = sb.append(","+selectRs.getString("categoryid"));
            }
            if(!categoryids.equals("")){categoryids = sb.toString().substring(1);}

            wmSetting.put("categoryids",categoryids);

        }else{
            String selectSql = "select isopen,mobileisopen,watermarktype,opacity,rotate,imageid,wmwidth,wmheight,wmcontent from SystemWaterMarkSetting where module = ?";
            RecordSet selectRs = new RecordSet();
            selectRs.executeQuery(selectSql,WaterMarkUtil.SYSTEMWMMODULE);
            BaseBean baseBean = new BaseBean();

            wmSetting.put("isopen","0");
            wmSetting.put("mobileisopen","0");
            wmSetting.put("watermarktype","1");
            wmSetting.put("opacity","20");
            wmSetting.put("rotate","20");
            wmSetting.put("imageid","");
            wmSetting.put("wmwidth","200");
            wmSetting.put("wmheight","200");
            wmSetting.put("wmcontent","");
            wmSetting.put("canedit", HrmUserVarify.checkUserRight("SystemSetEdit:Edit", user));
            //获取白名单
            String whiteListStr = baseBean.getPropValue("doc_watermark_list_weaver","system_watermark_white_list");
            List whiteList = new ArrayList();
            whiteList = WaterMarkUtil.comma2list(whiteListStr);
            wmSetting.put("whitelist",whiteList);
            //获取黑名单
            String blackListStr = baseBean.getPropValue("doc_watermark_list_weaver","system_watermark_black_list");
            List blackList = new ArrayList();
            blackList = WaterMarkUtil.comma2list(blackListStr);
            blackList.add("/spa/workflow/static4form/index.html");
            blackList.add("/spa/workflow/index_form.jsp");
            blackList.add("/spa/workflow/static4mobileform/index.html");
            // 流程表单 选择预留编号, 新建预留编号按钮
            blackList.add("/spa/workflow/static4engine/engine.html#/main/workflowengine/path/codeMaintenance/reserveCode");
            blackList.add("/spa/workflow/static4engine/engine.html#/main/workflowengine/path/codeMaintenance/addReserveCode");
            wmSetting.put("blacklist",blackList);

            while (selectRs.next()){
//            Map<String,Object> wmSetting = new HashMap<>();
                wmSetting.put("isopen",Util.getIntValue(selectRs.getString("isopen"),0));
                wmSetting.put("mobileisopen",Util.getIntValue(selectRs.getString("mobileisopen"),0));
                wmSetting.put("watermarktype",Util.getIntValue(selectRs.getString("watermarktype"),1));
                wmSetting.put("opacity",Util.getIntValue(selectRs.getString("opacity"),20));
                wmSetting.put("rotate",Util.getIntValue(selectRs.getString("rotate"),20));
                String imageid = Util.null2String(selectRs.getString("imageid"));
                wmSetting.put("imageid",DocDownloadCheckUtil.checkPermission(imageid,user));
                wmSetting.put("wmwidth",Util.getIntValue(selectRs.getString("wmwidth"),200));
                wmSetting.put("wmheight",Util.getIntValue(selectRs.getString("wmheight"),200));
                String wmcontent = Util.null2String(selectRs.getString("wmcontent"));
                if(convert){
                    Map<String,String> ParamsMap = WaterMarkUtil.getWmParamsMap(user);
                    for(Map.Entry<String,String> entry : ParamsMap.entrySet()){
                        String key = entry.getKey();
                        String value = entry.getValue();
                        wmcontent = wmcontent.replace(key,value);
                    }
                }
                wmSetting.put("wmcontent",wmcontent);
            }
        }

        result.put("wmSetting",wmSetting);
        return result;
    }

    /**
     * 判断是否打开了水印开关
     * @return
     */
    public static Boolean isOpenWmSetting(){
        Boolean result = false;
        String selectSql = "select isopen from SystemWaterMarkSetting where module = ? ";
        RecordSet selectRs = new RecordSet();
        selectRs.executeQuery(selectSql,WaterMarkUtil.DOCUMENTWMMODULE);
        while (selectRs.next()){
            int isopen = Util.getIntValue(selectRs.getString("isopen"));
            if(isopen==1){
                result = true;
            }
        }
        return result;
    }

    /**
     * 获取水印的类型，图片还是文本水印
     * @return
     */
    public static String getwmType(){
        String result = "text";
        String selectSql = "select watermarktype from SystemWaterMarkSetting where module = ? ";
        RecordSet selectRs = new RecordSet();
        selectRs.executeQuery(selectSql,WaterMarkUtil.DOCUMENTWMMODULE);
        while (selectRs.next()){
            int watermarktype = Util.getIntValue(selectRs.getString("watermarktype"));
            if(watermarktype == 1){
                result = "text";
            }else if(watermarktype == 2){
                result = "img";
            }
        }
        return result;
    }

    /**
     * 根据文件id获取文件的真实路径
     * @param fileid
     * @return
     */
    public static String getFileRealPath(String fileid){
        String sql = "select filerealpath from imagefile where imagefileid = ? ";
        String result = "";
        RecordSet selectRs = new RecordSet();
        selectRs.executeQuery(sql,fileid);
        while (selectRs.next()){
            result = Util.null2String(selectRs.getString("filerealpath"));
        }
        return result;
    }

    /**
     * 根据文件id在服务器上生成临时文件，并获取路径
     * @param fileid
     * @return
     */
    public static String getFilePath(String fileid){
        String sql = "select imagefilename from imagefile where imagefileid = ?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql,fileid);
        String ext = "";
        while (rs.next()){
            String imagefilename = rs.getString("imagefilename");
            ext = imagefilename.contains(".")? imagefilename.substring(imagefilename.lastIndexOf(".") + 1) : "";
        }
        PdfWaterMarkUtil pdfWaterMarkUtil = new PdfWaterMarkUtil();
        String imagepath=pdfWaterMarkUtil.getWaterPdfPath("."+ext);
        ImageFileManager imageFileManager=new ImageFileManager();
        imageFileManager.resetParameter();
        int imagefileid = Util.getIntValue(fileid);
        imageFileManager.getImageFileInfoById(imagefileid);
        InputStream inputStream = imageFileManager.getInputStream();
        try {
            pdfWaterMarkUtil.writeToLocal(imagepath, inputStream);
        } catch (IOException e) {
        }
        return imagepath;
    }

    /**
     * 判断是否部署了永中的转换服务
     * @return
     */
    public static Boolean isOpenYZTrans(){
        Boolean result = false;
        BaseBean bb = new BaseBean();
        String flag = Util.null2s(bb.getPropValue("doc_custom_for_weaver","convert_client_path"),"");
        if(!"".equals(flag)){
            result = true;
        }
        return result;
    }


    /**
     * 将字符串转换为color对象
     * @param str
     * @return
     */
    public static Color string2color(String str){
        int result = Integer.parseInt(str.substring(1),16);
        return new Color(result);
    }
//
//    public static void main(String[] args){
//        System.out.print("resukt-->"+WaterMarkUtil.stringtoRGB("#763838"));
//    }
    /**
     * 16进制颜色转RGB
     * @param
     * @return
     */
    public static String stringtoRGB(String color_16){
        Color color = WaterMarkUtil.string2color(color_16);
        int r,g,b;
        r = color.getRed();
        g = color.getGreen();
        b = color.getBlue();
        String result = String.valueOf(r)+","+g+","+b;
        return result;
    }


    /**
     * 获取系统设置的水印内容
     * @param user
     * @return
     */
    public static String getSystemWaterContent(User user){
        if(user==null){
            return "";
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isconvert","1");
        resultMap.put("document","document");
        Map<String,Object> wmSettingMap = WaterMarkUtil.getWmSetting(resultMap,user);
        Map<String,Object> wmSetting = (Map<String, Object>) wmSettingMap.get("wmSetting");
        BaseBean basebean = new BaseBean();
        String WaterMarkContent = Util.null2String(wmSetting.get("wmcontent"));
        BaseBean bb = new BaseBean();
        bb.writeLog("watermarkutil----------->WaterMarkContent",WaterMarkContent);
//        basebean.writeLog("PdfWaterMarkUtil---getWaterContent--watercontent--="+WaterMarkContent);
        //将正文中的\n替换为\r\n
        WaterMarkContent.replaceAll("\\n","\\r\\n");
        WaterMarkContent = delHTMLTag(WaterMarkContent);
        return WaterMarkContent;
    }
    /**
     * 获取系统设置的水印内容
     * @param user
     * @return
     */
    public static String getSystemWaterContent(User user,int fileid){
        if(user==null){
            return "";
        }
        if(fileid>0){
            RecordSet rs = new RecordSet();
            rs.executeQuery("select docid from docimagefile where imagefileid = ?",fileid);
            rs.next();
            int docid = rs.getInt("docid");
            if(docid>0){
                String watermark_mess = "";
                Map<String, Object> params = new HashMap<>();
                params.put("userId", user.getUID());
                params.put("docId", docid);
                Map<String, Object> archiveWaterMarkRespon = ArchivesFModeUtil.getArchiveWaterMark(params);
                if(archiveWaterMarkRespon.size()>0){
                    watermark_mess = Util.null2String(archiveWaterMarkRespon.get("watermark_mess"));
                }
                return  watermark_mess;
            }
            return getSystemWaterContent(user);
        }else{
            return getSystemWaterContent(user);
        }
    }
    public static String isSystemWaterContentnullByFileid(String fileid){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select seccategory from docdetail where id in (select max(docid) from docimagefile where imagefileid = ?)", fileid);
        rs.next();
        int categoryid = Util.getIntValue(rs.getString("seccategory"));
        rs.executeQuery("select waterid from docwatermarksecsetting where categoryid = ?", categoryid);
        rs.next();
        int waterid = Util.getIntValue(rs.getString("waterid"));

        return WaterMarkUtilNew.isContentnull(waterid);
    }
    public static String isSystemWaterContentnull(String docid){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select seccategory from docdetail where id= ?", docid);
        rs.next();
        int categoryid = Util.getIntValue(rs.getString("seccategory"));
        rs.executeQuery("select waterid from docwatermarksecsetting where categoryid = ?", categoryid);
        rs.next();
        int waterid = Util.getIntValue(rs.getString("waterid"));

        return WaterMarkUtilNew.isContentnull(waterid);
    }


    public static String getwmImgFileid(User user){
        if(user==null){
            return "";
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isconvert","1");
        resultMap.put("document","document");
        Map<String,Object> wmSettingMap = WaterMarkUtil.getWmSetting(resultMap,user);
        Map<String,Object> wmSetting = (Map<String, Object>) wmSettingMap.get("wmSetting");
        BaseBean basebean = new BaseBean();
        //获取图片的imageid
        String imageid = Util.null2String(wmSetting.get("imageid"));
        return imageid;
    }

    /**
     * 将带逗号的字符串，转换为字符数组
     * @param str
     * @return
     */
    public static List comma2list(String str){
        List<String> result = new ArrayList();
        if(str.equals("")){
            return result;
        }
        String[] strArray = str.split(",");
        for(int i=0; i<strArray.length;i++){
            result.add(strArray[i]);
        }
        return result;
    }

    public static Map<String,Object> getCategoryWmSet(String id){
        return getCategoryWmSet(id,true);
    }
    /**
     * 通过文件id来获取到文档id，再由文档id获取到目录id，最后判断目录是否开启了水印设置项，以及应用的位置
     * @param id
     * @return
     */
    public static Map<String,Object> getCategoryWmSet(String id,Boolean isfileid){
        Map<String,Object> result = new HashMap<>();
        String sql = "";
        if(isfileid){
            sql = "select a.categoryid,a.wmforview,a.wmfordownload,a.wmforprint,a.setpostion,b.isopenwater from docwatermarksecsetting a,(select id,isopenwater from docseccategory where id in (select seccategory from docdetail where id in (select max(docid) from docimagefile where imagefileid = ?))) b where a.categoryid = b.id and a.setpostion = ?";

        }else{
            sql = "select a.categoryid,a.wmforview,a.wmfordownload,a.wmforprint,a.setpostion,b.isopenwater from docwatermarksecsetting a,(select id,isopenwater from docseccategory where id = (select seccategory from docdetail where id = ?)) b where a.categoryid = b.id and a.setpostion = ?";
        }

        RecordSet rs = new RecordSet();
        rs.executeQuery(sql,id,WaterMarkUtil.SECCATEGORYWATERMARK);
        String isopenwater = "0";
        String wmforview = "1";
        String wmfordownload = "1";
        String wmforprint = "1";
        if(rs.next()){
             isopenwater = Util.null2s(rs.getString(WaterMarkUtil.SECCATEGORYWMISOPEN),"0");
             wmforview = Util.null2s(rs.getString(WaterMarkUtil.SECCATEGORYVIEW),"1") ;
             wmfordownload = Util.null2s(rs.getString(WaterMarkUtil.SECCATEGORYDOWNLOAD),"1") ;
             wmforprint = Util.null2s(rs.getString(WaterMarkUtil.SECCATEGORYPRINT),"1") ;
        }
        String wmcontent = isfileid ? WaterMarkUtil.isSystemWaterContentnullByFileid(id): WaterMarkUtil.isSystemWaterContentnull(id);

        result.put(WaterMarkUtil.SECCATEGORYVIEW,wmforview);
        result.put(WaterMarkUtil.SECCATEGORYDOWNLOAD,wmfordownload);
        result.put(WaterMarkUtil.SECCATEGORYPRINT,wmforprint);
        result.put(WaterMarkUtil.SECCATEGORYWMISOPEN,isopenwater);
        result.put(WaterMarkUtil.WATERCONTENTISNULL,wmcontent);

        return result;
    }
    public static String getIsOpenAsync (){
        BaseBean baseBean = new BaseBean();
        String isopenasyn = Util.null2s(baseBean.getPropValue("doc_engine_tree_async","isopen"),"0");
        return isopenasyn;
    }

    public static InputStream takefileWater(InputStream imagefile, User user, String filename, int fileid, String extName, String fromMould){
        return takefileWater(imagefile,user,filename,fileid,extName,fromMould,-1,"");
    }
    public static InputStream takefileWater(InputStream imagefile, User user, String filename, int fileid, String extName, String fromMould, int originfileid,String requestid){
    	RecordSet rs = new RecordSet();
    	filename = filename.toLowerCase();
    	rs.executeQuery("select * from wpsprintfileid where imagefileid = "+fileid);
    	if(rs.next()){
    	   
    	    return imagefile;
        }
        String addwaterUseyozoForimg = Util.null2s(new BaseBean().getPropValue("doc_custom_for_weaver","addwaterUseyozoForimg"),"0");
        String addwaterUseyozoForpdf = Util.null2s(new BaseBean().getPropValue("doc_custom_for_weaver","addwaterUseyozoForpdf"),"0");
        InputStream is2 = null;
        DocAddWaterForSecond docAddWaterForSecond = new DocAddWaterForSecond();
        if("pdf".equals(extName.toLowerCase())){
            if(ImageConvertUtil.canViewForWps()){
                is2 = docAddWaterForSecond.docAddWaterForWps(fileid,user,filename,fromMould,originfileid,requestid);
            }else if(ImageConvertUtil.canViewForYOZO()){
                is2  = docAddWaterForSecond.docAddWater(imagefile,user,filename, DocAddWaterForSecond.PDFWATER,fileid,fromMould,originfileid,requestid);
            }
            else{
                is2  = docAddWaterForSecond.pdfAddWater(imagefile,user,filename,fileid,fromMould,originfileid,requestid);
            }
        }else if("jpg".equals(extName.toLowerCase()) || "jpeg".equals(extName.toLowerCase()) || "bmp".equals(extName.toLowerCase())){
            if(ImageConvertUtil.canViewForYOZO()&& "1".equals(addwaterUseyozoForimg)){
                is2 = docAddWaterForSecond.docAddWater(imagefile,user,filename, DocAddWaterForSecond.IMGWATER,fileid,fromMould,originfileid,requestid);
            }else{
                is2 = docAddWaterForSecond.imgAddWater(imagefile,user,filename,fileid,fromMould,requestid);
            }

        }else if("doc".equals(extName.toLowerCase()) || "docx".equals(extName.toLowerCase())){
            if(ImageConvertUtil.canViewForWps()){
                is2 = docAddWaterForSecond.docAddWaterForWps(fileid,user,filename,fromMould,originfileid,requestid);
            }else if(ImageConvertUtil.canViewForYOZO()){
                is2 = docAddWaterForSecond.docAddWater(imagefile,user,filename, DocAddWaterForSecond.DOCWATER,fileid,fromMould,originfileid,requestid);
            }
        }else if(ImageConvertUtil.canConvertPdfForDownload(extName,fileid+"")){
            int pdfImagefile = -1;
            rs.executeQuery("select * from pdf_imagefile_for_wpsview where extparams = ? and fromould = ? and fileid= ?",
                    "fromdoccenter_0", "ecology", fileid);
            if(rs.next()){
                pdfImagefile = Util.getIntValue(rs.getString("pdfimagefileid"),0);
            }else{
                Map<String,Object> convertMap = new HashMap<String,Object>();
                convertMap.put("user", user);
                convertMap.put("fileId", fileid);
                convertMap.put("fileName", filename);
                convertMap.put("targetFilename", filename+".pdf");
                convertMap.put("fromMould", "ecology");
                pdfImagefile = CommonUtil.getOfficedService().convertToPDF(convertMap);
                rs.executeUpdate("insert into pdf_imagefile_for_wpsview(fileid, fromould, pdfimagefileid, extparams, opdatetime) values(?,?,?,?,?)",
                        fileid, "ecology", pdfImagefile, "fromdoccenter_0", DateUtil.getFullDate());
            }
            imagefile = ImageFileManager.getInputStreamById(pdfImagefile);
            if(ImageConvertUtil.canViewForWps()){
                is2 = docAddWaterForSecond.docAddWaterForWps(pdfImagefile,user,filename+".pdf",fromMould,fileid,requestid);
            }else if(ImageConvertUtil.canViewForYOZO()){
                is2  = docAddWaterForSecond.docAddWater(imagefile,user,filename+".pdf", DocAddWaterForSecond.PDFWATER,pdfImagefile,fromMould,fileid,requestid);
            }
            else{
                is2  = docAddWaterForSecond.pdfAddWater(imagefile,user,filename+".pdf",pdfImagefile,fromMould,fileid,requestid);
            }
        }
        if(is2 != null){
            imagefile = is2;
        }
        return imagefile;
    }

    public static String delHTMLTag(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
        String regEx_space = "\\s*|\t";//定义空格回车换行符

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

//        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
//        Matcher m_space = p_space.matcher(htmlStr);
//        htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
        return StringEscapeUtils.unescapeHtml(htmlStr.trim());
    }
}
