package weaver.interfaces.htsc.workflow.odoc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.util.UploadDocUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class CrmRunnable {


    private Log log = LogFactory.getLog(this.getClass());
    String folderName = System.currentTimeMillis()+"";

    /**
     * rms加密处理
     * @return 结果集合
     */
    public String rmsFileEncryption(RequestInfo requestInfo)
    {
        BaseBean bb = new BaseBean();
        bb.writeLog("FileEncryptionAction2===rms====");
        UploadDocUtil uploadDocUtil = new UploadDocUtil();
        String tablename = requestInfo.getRequestManager().getBillTableName();
        String requestid = requestInfo.getRequestid();
        PropBean propBean = new PropBean();
        RecordSet rs = new RecordSet();
        try {
            //1.获取所有后缀名为doc和docx且勾选了查看权限的的文档id
            //1.1.获取所有正文和附件的文档id
            List<String> docidAllList = new ArrayList<>();
            String docidSql = "select zw,fj from " + tablename + " where requestid = ?";
            rs.executeQuery(docidSql, new Object[]{requestid});
            if (rs.next()) {
                String zw = Util.null2String(rs.getString("zw"));
                String fj = Util.null2String(rs.getString("fj"));
                docidAllList.add(zw);
                if (!"".equals(fj)){
                    String[] fjdocid = fj.split(",");
                    Collections.addAll(docidAllList, fjdocid);
                }
            }
            log.info("获取所有正文和附件文档id" + docidAllList.toString());
            //1.2.筛选后缀名
            List<String> docidsuffixList = new ArrayList<>();
            String suffixSql = "select imagefilename from DocImageFile where docid = ?";
            for (String suffixDocid : docidAllList) {
                rs.executeQuery(suffixSql, new Object[]{suffixDocid});
                if (rs.next()) {
                    String imagefilename = Util.null2String(rs.getString("imagefilename"));
                    //2.截取附件名称后缀名
                    int index = imagefilename.lastIndexOf(".");
                    char[] ch = imagefilename.toCharArray();
                    String sufffix = String.copyValueOf(ch, index + 1, ch.length - index - 1);
                    if ("doc".equals(sufffix) || "docx".equals(sufffix)) {
                        docidsuffixList.add(suffixDocid);
                    }
                }
            }
            log.info("筛选后缀名完成" + docidsuffixList.toString());
            //1.3.筛选可查看权限
            List<String> docidList = new ArrayList<>();
            String detailTable = tablename+"_dt4";
            for (String docid :docidsuffixList){
                String perSql = "select yxck from "+detailTable+" where wdid = ?";
                rs.executeQuery(perSql,new Object[]{docid});
                if (rs.next()){
                    String yxck = Util.null2String(rs.getString("yxck"));
                    if ("1".equals(yxck)){
                        docidList.add(docid);
                    }
                }
            }
            log.info("筛选可查看权限"+docidList.toString());
            //2.上传文件至共享盘
            JSONArray dataArray = new JSONArray();
            JSONObject dataObject = new JSONObject();
            for (String docid : docidList){
                Map<String, String> datas = getLatestVersionPDF(requestid, docid);
                dataArray.add(datas);
            }
            dataObject.put("inputFileList",dataArray);
            dataObject.put("requestId",requestid);
            //3.调接口发送数据
            log.info("共享盘上传成功"+dataObject.toString());
            String url = propBean.getPropName("RMSURL");
            String encode = "utf-8";
            Map<String, String> headers = new HashMap<>();
            headers = new HTUtil().getAppHeader();
            log.info("==安全增加headers==="+headers.toString());
            String content = httpPostRaw(url,dataObject.toString(), headers, encode);
            log.info("返回加密后的文件"+content);
            //4.处理返回后的加密文件
            String realpath = propBean.getPropName("RMSSTORAGEADDRESS")+System.currentTimeMillis();
            JSONObject rmsObject = JSONObject.parseObject(content);
            log.info("rmsObject--"+rmsObject);
            JSONArray rmsFileList = rmsObject.getJSONArray("rmsFileList");
            if (rmsFileList.size()>0){
                List<Integer> newDocidList = new ArrayList<>();
                for (int i = 0; i<rmsFileList.size();i++){
                    String oldDocid = rmsFileList.getJSONObject(i).getString("originFileId");
                    String filepath = rmsFileList.getJSONObject(i).getString("pdfRmsFileName");
                    String imageFileName = rmsFileList.getJSONObject(i).getString("imageFileName");
                    log.info("加密前附件id"+oldDocid);
                    //根据原docid获取正文pdfid
                    String zwpdfDocid = "";
                    RecordSet findRs = new RecordSet();
                    String findSql = "select zwpdf from "+tablename+" where  zw = ? and requestid = ?";
                    findRs.executeQuery(findSql,new Object[]{oldDocid,requestid});
                    if (findRs.next()){
                        zwpdfDocid = Util.null2String(findRs.getString("zwpdf"));
                    }
                    log.info("获取正文pdfid"+zwpdfDocid);
                    int newDocid = uploadDocUtil.uploadFileByPath(oldDocid, filepath, realpath,imageFileName);
                    log.info("加密后上传附件id"+newDocid);
                    newDocidList.add(newDocid);
                    String fileidSql = "select imagefileid from docimagefile where docid = ?";
                    rs.executeQuery(fileidSql,new Object[]{newDocid});
                    if (rs.next()){
                        String imagefileid = Util.null2String(rs.getString("imagefileid"));
                        //5.更新建模表
                        String insertSql = "insert into uf_rmsjmb(requestid,docid,rmsdocid,rmsimagefileid,zwpdfdocid) values(?,?,?,?,?)";
                        rs.executeUpdate(insertSql,new Object[]{requestid,oldDocid,newDocid,imagefileid,zwpdfDocid});
                        log.info("建模表更新成功-"+insertSql);
                    }
                }
                //6.更新主表字段
                String newDocidStr = StringUtils.join(newDocidList, ",");
                String updateSql = "update "+tablename+" set rmsfj = '"+newDocidStr+"' where requestid = "+requestid;
                rs.executeUpdate(updateSql);
                log.info("主表字段更新成功-"+newDocidStr);
            }

        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessageid("111111");
            requestInfo.getRequestManager().setMessagecontent("文件加密接口异常，请联系系统管理员！");
        }
        return Action.SUCCESS;
    }
    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param docid 文档ID
     * @return 结果集合
     */
    private Map<String,String> getLatestVersionPDF(String requestid, String docid){
        Map<String,String> map = new HashMap<>();

        try{
            //取最大版本的正文信息
            String sql = "select t.* from (select imagefileid,imagefilename,versionid from docimagefile \n" +
                    "where docid = ? \n" +
                    "order by versionid  desc) t where rownum < 2";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,new Object[]{docid});
            if(rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                int lastIndexOf = imagefilename.lastIndexOf(".");
                String suffix = imagefilename.substring(lastIndexOf);
                imagefilename = new String(imagefilename.getBytes("gbk"));
                String versionid = Util.null2String(rs.getString("versionid"));
                log.info("附件："+imagefilename+"的最新版本是："+versionid);
                InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                int index;
                byte[] bytes = new byte[1024];
                // 文件夹名称
                PropBean propBean = new PropBean();
                String sharedDiskAddress = propBean.getPropName("SharedDiskAddress");
                String path = sharedDiskAddress + folderName;
                // linux 下 先创建文件夹
                File dir = new File(path);
                //设置写权限，windows下不用此语句
                dir.setWritable(true, false);
                dir.mkdirs();
                //赋权限，正常是当前用户的权限，但是这里和之前的老OA不是同一个用户
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                path += "/"+docid+suffix;//创建文件
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                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);
                map.put("imageFileName",imagefilename);
                map.put("originFileName",path);
                map.put("originFileId",docid);
                map.put("pdfFileName","");
                map.put("pdfRmsFileName","");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 发送http请求
     * @param url        接口地址
     * @param stringJson 请求的 json 字符串
     * @param headers    头部参数
     * @param encode     编码
     * @return 响应结果
     */
    private String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode)
    {
        BaseBean bb = new BaseBean();
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            bb.writeLog("httpResponse===" + "httpResponse===" + httpResponse);
            HttpEntity entity = httpResponse.getEntity();
            bb.writeLog("entity", "entity===" + entity);
            content = EntityUtils.toString(entity, encode);
            bb.writeLog("content", "content===" + content);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }


}
