package com.engine.htsc.seal.util;

import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.seal.entity.FlowOwner;
import com.engine.htsc.seal.entity.ManualSignEntity;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.util.CreateDocUtil;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.wps.officed.ConvertToPdf;
import weaver.wps.officed.OfficedWatermark;

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

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName EsealUtil.java
 * @createTime 2022年03月16日 13:34:00
 */
public class EsealUtil {

     private MessageDetailLog messageDetailLog =null;
     private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     private BaseBean  bs = new BaseBean();
    /**
     * 获取pdf文件id
     * @param docid
     * @return
     */
    public  String getPdfid(String docid){
        int pdfid = 0;
        try {
            ConvertToPdf convertToPdf = new ConvertToPdf();
            String sql = "select imagefileid,imagefilename from (select * from DocImageFile t where docid = '" + docid + "' order by operatedate desc,operatetime desc ) where ROWNUM <= 1";
            Map<String, Object> map = JAVATools.GetTableToMap(sql, null);
            JAVATools.SetCmdwritelog("用印登记单询getPdfId" + sql);
            int imagefileid = Integer.parseInt(Util.null2String(map.get("imagefileid")));
            String imagefilename = Util.null2String(map.get("imagefilename")).toLowerCase();
            JAVATools.SetCmdwritelog("getPdf:iddocid:" + docid);
            JAVATools.SetCmdwritelog("getPdfid:imagefileid:" + imagefileid);
            JAVATools.SetCmdwritelog("getPdfid:imagefilename:" + imagefilename);
            if (imagefileid > 0 && !StringUtils.isBlank(imagefilename)) {
                String fileTyle = imagefilename.substring(imagefilename.lastIndexOf(".") + 1, imagefilename.length());
                JAVATools.SetCmdwritelog("getPdfid:fileTyle:" + fileTyle);
                if ("pdf".equals(fileTyle)) {
                    pdfid = imagefileid;
                } else {
                    pdfid = convertToPdf.getDownloadPDFUrl(imagefileid, imagefilename, false);
                    if (pdfid <= 0) {
                        pdfid = convertToPdf.getDownloadPDFUrl(imagefileid, imagefilename, false);
                    }
                }
                JAVATools.SetCmdwritelog("getPdfid:pdfid:" + pdfid);
                return Util.null2String(pdfid);
            } else {
                return null;
            }
        }catch (Exception exo){

        }
        return Util.null2String(pdfid);
    }


    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param pdfid 文档ID
     * @return 结果集合
     */
    public Map<String,String> getLatestVersionPDF(String requestid, String pdfid){
        Map<String,String> map = new HashMap<>();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        try{
            String sql = "select imagefileid,imagefilename from imagefile where imagefileid = '"+pdfid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilenamehz = Util.null2String(rs.getString("imagefilename"));
                String postfix="";
                String postfilename="";
                if(imagefilenamehz.split("\\.").length>=2){
                    if(imagefilenamehz.indexOf(".")>0){
                        postfilename=imagefilenamehz.substring(0,imagefilenamehz.lastIndexOf("."));
                    }

                }
                postfix=".pdf";
                String imagefilename = imagefileid+postfix;
                String imagefilepostname="";
                if(!"".equals(postfilename)){
                    imagefilepostname=postfilename+postfix;
                }else{
                    imagefilepostname=imagefileid+postfix;
                }

                bs.writeLog("imagefilename:"+imagefilename);
                bs.writeLog("imagefilepostname:"+imagefilepostname);

                InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                int index;
                byte[] bytes = new byte[1024];
                // 文件夹名称
                String folderName = requestid+"_"+imagefileid+"_"+System.currentTimeMillis();
                String mountdir = Util.null2String(pb.getPropName("AutoSign.mountdir"));
                if("".equals(mountdir)){
                    bs.writeLog("获取的用印上传共享目录为空！");
                    return map;
                }

                String path = mountdir+"/" + folderName;
                // linux下先创建文件夹
                File dir = new File(path);
                //设置写权限，windows下不用此语句
                dir.setWritable(true, false);
                dir.mkdirs();
                //赋权限，正常是当前用户的权限，但是这里和之前的老OA不是同一个用户
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                path += "/"+imagefilename;//创建文件
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream uploadFile = new FileOutputStream(file);
                while ((index = inputstream.read(bytes)) != -1) {
                    uploadFile.write(bytes, 0, index);
                    uploadFile.flush();
                }
                inputstream.close();
                uploadFile.close();
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                String Signmountpath = Util.null2String(pb.getPropName("Signmountpath"));
                String mountpath=Signmountpath+folderName+"/"+imagefilename;
                map.put("mountpath",mountpath);
                map.put("imagefilename",imagefilepostname);
                bs.writeLog("realpath:"+path);
                bs.writeLog("mountpath:"+mountpath);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 印章ID转印章编号
     * @param signid 印章ID
     * @return 印章编号
     */
    public String getSignCode(String signid){
        RecordSet rs = new RecordSet();
        String yzbhvalue="";

        rs.execute("select yzbh from uf_yinzhang where id in ("+signid+") ");

        if (rs.getArray().size()<=0) {
            return "";
        }
        while(rs.next()){
            if(!"".equals(Util.null2String(rs.getString("yzbh")))){
                yzbhvalue+=Util.null2String(rs.getString("yzbh"))+",";
            }
        }
        if(yzbhvalue.length()>0){
            yzbhvalue=yzbhvalue.substring(0,yzbhvalue.length()-1);
        }
        return yzbhvalue;
    }


    /**
     * 获取水印后文件docid
     * @param user
     * @param fileId
     * @param content
     * @return
     */
    public int getWarterMarkDocid(User user, String fileId, String content){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();

        int docid = -1;
        String secId = Util.null2String(pb.getPropName("seal.license.watermark.secId"));
        bs.writeLog("fileId:"+fileId+" secId:"+secId+" content:"+content);

        RecordSet rs = new RecordSet();
        String sql = "select imageFileId from docImageFile where docId = ? order by versionId desc";
        rs.executeQuery(sql, new Object[]{fileId});
        int flag = -1;
        if(rs.next()) {
            flag = rs.getInt(1);
        }
        bs.writeLog("flag:"+flag);

        try{
            ImageFileManager imageFileManager = new ImageFileManager();
            imageFileManager.resetParameter();
            if(flag != -1) {
                imageFileManager.getImageFileInfoById(flag);
                String imageFileName = imageFileManager.getImageFileName();
                String fileType = imageFileName.contains(".")?imageFileName.substring(imageFileName.lastIndexOf(".")):".pdf";
                OfficedWatermark officedWatermark = new OfficedWatermark();
                String fillstyle = bs.getPropValue("water_setting", "fillstyle");
                String font = bs.getPropValue("water_setting", "font");
                String width = bs.getPropValue("water_setting", "width");
                String height = bs.getPropValue("water_setting", "height");
                String rotate = bs.getPropValue("water_setting", "rotate");
                String opacity = bs.getPropValue("water_setting", "opacity");
                HashMap paramMap = new HashMap();
                if(!fillstyle.isEmpty()) {
                    paramMap.put("fillstyle", fillstyle);
                }
                if(!font.isEmpty()) {
                    paramMap.put("font", font);
                }
                if(!width.isEmpty()) {
                    paramMap.put("width", Integer.valueOf(Util.getIntValue(width)));
                }
                if(!height.isEmpty()) {
                    paramMap.put("height", Integer.valueOf(Util.getIntValue(height)));
                }
                if(!rotate.isEmpty()) {
                    paramMap.put("rotate", Double.valueOf(Util.getDoubleValue(rotate)));
                }
                if(!opacity.isEmpty()) {
                    paramMap.put("opacity", Float.valueOf(Util.getFloatValue(opacity)));
                }

                String waterType = OfficedWatermark.WATER_TYPE_PDF;
                if(fileType.toLowerCase().equals(".pdf")) {
                    waterType = OfficedWatermark.WATER_TYPE_PDF;
                } else if(!fileType.toLowerCase().equals(".doc") && !fileType.toLowerCase().equals(".docx")) {
                    waterType = OfficedWatermark.WATER_TYPE_IMG;
                } else {
                    waterType = OfficedWatermark.WATER_TYPE_WORD;
                }

                InputStream inputStream = officedWatermark.addWaterInputStream(flag, imageFileName, waterType, content, paramMap);
                if(inputStream == null) {
                    bs.writeLog("加水印失败！");
                }else{
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.getBOS(inputStream).toByteArray());
                    if(!secId.isEmpty()) {
                        CreateDocUtil createDocUtil = new CreateDocUtil();
                        int secid = Util.getIntValue(secId);
                        docid = createDocUtil.createDocByInputStream(byteArrayInputStream, secid, imageFileName, user);
                        byteArrayInputStream.reset();
                    }
                    byteArrayInputStream.close();
                }
                inputStream.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return docid;
    }


    public  String getNextYear(String dateStr,String pattern,int num) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            Date date = sdf.parse(dateStr);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.YEAR, num);
            return sdf.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 初始化信息
     * @param user
     * @param requestid
     * @return
     */
    public ManualSignEntity initialization(User user, String requestid){
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        ManualSignEntity manualSignEntity = new ManualSignEntity();
        String appid = Util.null2String(pb.getPropName("AutoSign.appId"));//应用ID
        String secret = Util.null2String(pb.getPropName("AutoSign.secret"));//秘钥
        manualSignEntity.setAppId(appid);
        manualSignEntity.setSecret(secret);
        manualSignEntity.setSignUserId(user.getLoginid());
        manualSignEntity.setSignUserName(user.getLastname());
        manualSignEntity.setFlowOwner(getFlowOwner(requestid));

        String requestMark = requestid;
        String requestName=  new SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString();
        String sql="select requestName,requestMark from workflow_requestbase where requestid ="+requestid;
        rs.executeQuery(sql);
        if(rs.next()){
            requestMark = Util.null2String(rs.getString("requestMark"));
            requestName = Util.null2String(rs.getString("requestName"));
        }
        if(requestName.length()>100){
            requestName = requestName.substring(0,100);
        }
        manualSignEntity.setFlowNum(requestMark);
        manualSignEntity.setFlowName(requestName);

        return manualSignEntity;
    }

    public Map<String,String> getUserMap(String userids, String currentUserid){
        Map<String,String> map=new HashMap<>();
        if(StringUtils.isEmpty(userids)){
            return map;
        }
        String username="";
        String usrlogins="";

        String[] userarray=userids.split(",");
        for (String userid:userarray) {
            try {
                User user = new User(Integer.parseInt(userid));
                if(user!=null){
                    usrlogins+=usrlogins== "" ? JAVATools.getHrmworkcode(user.getLoginid()):","+JAVATools.getHrmworkcode(user.getLoginid());
                    username+=username=="" ? user.getUsername():","+user.getUsername();
                }
            }catch (Exception exo){
                System.out.println("user数据有误："+userids);
            }
        }
        if(StringUtils.isNotEmpty(currentUserid)){
            try {
                User user = new User(Integer.parseInt(currentUserid));
                if(user!=null){
                    usrlogins+=usrlogins== "" ? JAVATools.getHrmworkcode(user.getLoginid()):","+JAVATools.getHrmworkcode(user.getLoginid());
                    username+=username=="" ? user.getUsername():","+user.getUsername();
                }
            }catch (Exception exo){
                System.out.println("user数据有误："+userids);
            }
        }
        map.put("username",username);
        map.put("usrlogins",usrlogins);
        return map;
    }

    public String getDatetime(){
        Random random=new Random();
        int inum=  random.nextInt(900)+100;
        return new  SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString()+inum;
    }

    public boolean jjhyycallback(Map<String,Object> map){
        String response=Util.null2String(map.get("response"));
        String tablename=Util.null2String(map.get("tablename"));
        String mainid=Util.null2String(map.get("mainid"));
        String docids=Util.null2String(map.get("docids"));
        String requestid=Util.null2String(map.get("requestid"));
        if(StringUtils.isEmpty(response)){

            messageDetailLog.writeinseertLogs(requestid,"手动签章接口返回结果为空".toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);

            return false;
        }
        JSONObject res = JSONObject.parseObject(response);
        String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
        String message = Util.null2String(res.get("message"));
        if(!"200".equals(status)){
            updateSignStatus(tablename+"_dt7",mainid,docids,"4");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
            return false;
        }
        updateSignStatus(tablename+"_dt7",mainid,docids,"2");
        messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        return true;
    }

    public void updateSignStatus(String tableName, String mainid, String docids, String yyzt){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> docidList = Arrays.asList(docids.split(","));
        for(String docid:docidList){
            String update_sql = "update "+tableName+" set yyzt = '"+yyzt+"' where mainid = '"+mainid+"' and wjmc = '"+docid+"'";
          JAVATools.SetCmdwritelog("-ceshi----"+update_sql);
            rs.executeUpdate(update_sql);
        }
    }
    /**
     * 获得印章签署方
     * @param requestid
     * @return
     */
    public FlowOwner getFlowOwner(String requestid){
        RecordSet rs = new RecordSet();
        DepartmentComInfo dc = new DepartmentComInfo();
        FlowOwner flowOwner = new FlowOwner();
        try{
            flowOwner.setFlowSendTime(sdf.format(new Date()));

            String tableName = JAVATools.getMaintable(requestid);
            String ngr = "";
            String sql = "select ngr from "+tableName+" where requestid = "+requestid;
            rs.executeQuery(sql);
            if(rs.next()){
                ngr= Util.null2String(rs.getString("ngr"));
            }
            User ngrUser = new User(Util.getIntValue(ngr));
            String orgId = Util.null2String(dc.getDepartmentCode(String.valueOf(ngrUser.getUserDepartment())));
            String orgName = Util.null2String(dc.getDepartmentName(String.valueOf(ngrUser.getUserDepartment())));
            String personNum = JAVATools.getHrmworkcode(ngrUser.getLoginid());
            String personName = ngrUser.getLastname();
            personName += "("+personNum+")";
            flowOwner.setOrgId(orgId);
            flowOwner.setOrgName(orgName);
            flowOwner.setPersonNum(personNum);
            flowOwner.setPersonName(personName);
        }catch(Exception e){
            e.printStackTrace();
        }

        return flowOwner;
    }

    private ByteArrayOutputStream getBOS(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            int index;
            while((index = bufferedInputStream.read()) != -1) {
                outputStream.write(index);
            }
            bufferedInputStream.close();
        } catch (Exception e) {

        }

        return outputStream;
    }

}
