package com.engine.htsc.doc.cmd;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.doc.util.CommonUtil;
import com.engine.htsc.doc.util.ConvertUtil;
import com.engine.htsc.doc.util.IoUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;

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


public class LetterReadCmd {

    private RecordSet rs = new RecordSet();
    private  RecordSetDataSource rsd = new RecordSetDataSource("Letter");
    private BaseBean bb = new BaseBean();
    private PropBean propBean = new PropBean();
    private String URL = propBean.getPropName("XCOA");
    private final static List<String> UNNUMBER = Arrays.asList("zbggfb","tzgg");

    /**
     * 送阅入口
     * @param params
     */
    public void saveReaderByCode(Map<String, Object> params,String id) {
        String readerIds = (String)params.get("readerIds");
        String readerDepIds = (String)params.get("readerDepIds");
        String readerGroupIds = (String)params.get("readerGroupIds");//按群组送阅    英文逗号分隔id
        String readerOrgIds = (String) params.get("readerOrgIds");//按组织架构送阅
        String requestId = (String)params.get("requestId");
        String handerId = (String)params.get("handerId");
        bb.writeLog("信创公文看阅入口"+requestId);


        //1.根据requestid获取流程主表单所在的表名
        rs.executeQuery("select t2.tablename from workflow_requestbase t0,workflow_base t1,workflow_bill t2 where t0.workflowid = t1.id " +
                "and t1.formid = t2.id and  t0.requestid = ?",new Object[]{requestId});

        String tablename = "";
        if(rs.next()){
            tablename = rs.getString("tablename");
        }

        //2.根据requestid获取流程unnumber
        rs.executeQuery("select UNNUMBER from workflow_base a join\n" +
                "WORKFLOW_REQUESTBASE b on a.id = b.WORKFLOWID and b.REQUESTID = ?",requestId);
        String unnumber = "";
        if (rs.next()) {
            unnumber = rs.getString("UNNUMBER");
        }

        //3.公告类型建模表(gglx)提前转换文字，因为信创流程数据未生成(后期优化)
        String gglxDispatch = "";
        if(UNNUMBER.contains(unnumber)) {
             gglxDispatch = ConvertUtil.getNameByRequestIdAndFiledId(requestId, "gglx");
        }else {
            gglxDispatch = ConvertUtil.getNameByRequestIdAndFiledId(requestId, "lx");
        }
        bb.writeLog("gglxDispatch"+gglxDispatch);

        //4.筛选容许查看的附件
        String allowReadAttachment = filterAttachment(tablename,requestId,"fj");

        //3.查询当前编辑数据的主表数据
        Map<String,String> mainDataMap = new HashMap<>();
        if(StringUtils.isNotEmpty(tablename)) {
            rs.executeQuery("select * from " +tablename+" t where t.requestid = "+requestId);
            if(rs.next()){
                String columnNames[] = rs.getColumnName();
                for(int i=0;i<columnNames.length;i++){
                    String fieldName = columnNames[i].toLowerCase();
                    String fieldValue = Util.null2String(rs.getString(fieldName));
                    mainDataMap.put(fieldName,fieldValue);
                }
            }
        }

        //4.查询当前编辑数据的明细表4数据
        String mainid = mainDataMap.get("id");
        String detailTableName = tablename + "_dt4";
        List<Map> detailList = new ArrayList<>();
        if (StringUtils.isNotEmpty(mainid)) {
            rs.executeQuery("select * from "+detailTableName+" where mainid = ?",mainid);
            while (rs.next()) {
                Map<String,String> detailDataMap = new HashMap<>();
                String columnNames[] = rs.getColumnName();
                for(int i=0;i<columnNames.length;i++){
                    String fieldName = columnNames[i].toLowerCase();
                    String fieldValue = Util.null2String(rs.getString(fieldName));
                    detailDataMap.put(fieldName,fieldValue);
                }
                detailList.add(detailDataMap);
            }
        }

        JSONObject datas = new JSONObject();
        datas.put("tablename",tablename);
        datas.put("mainData",mainDataMap);
        datas.put("detailData",detailList);
        datas.put("readerIds",readerIds);
        datas.put("readerDepIds",readerDepIds);
        datas.put("readerGroupIds",readerGroupIds);
        datas.put("readerOrgIds",readerOrgIds);
        datas.put("handerId",handerId);
        datas.put("unnumber",unnumber);
        datas.put("requestId",requestId);
        datas.put("gglxDispatch",gglxDispatch);
        datas.put("type",new CommonUtil().getWorkflowType(requestId,tablename,unnumber));
        //datas.put("type","0");

        datas.put("allowReadAttachment",allowReadAttachment);
        System.out.println(datas.toJSONString());
        //1.看阅数据上传
        String result = HttpRequest.post(URL+"/xcoa/api/htsc/document/letterSendRead")
                .body(datas.toJSONString())
                .execute().body();
//        String result = HttpRequest.post("http://168.61.8.169:8080/htoa/api/htsc/document/letterSendRead")
//                .body(datas.toJSONString())
//                .execute().body();
        System.out.println(result);
        bb.writeLog("看阅数据传输结果requestid:"+requestId+"==="+result);

        //2.文件上传(文件上传重构，采用DbLink方式)
//        List<String>  bodyList = new ArrayList<>();
//        List<String> attachmentList = new ArrayList<>();
//
//        rs.executeQuery("select zwpdf,fj,gzzdzwpdf from "+tablename+" where requestid = ?",requestId);
//        if (rs.next()) {
//            bodyList.add(Util.null2String(rs.getString("zwpdf")));
//            attachmentList.addAll(Arrays.asList(Util.null2String(rs.getString("fj")).split(",")));
//            attachmentList.addAll(Arrays.asList(Util.null2String(rs.getString("gzzdzwpdf")).split(",")));
//        }
//
//        bb.writeLog("看阅数据是否存在requestud:"+requestId+"==="+id);
//
//        if(StringUtils.isBlank(id)) { //文件传输只做一次
//            bodyList.stream().forEach(s -> bb.writeLog("bodyList:" + s));
//            attachmentList.stream().forEach(s -> bb.writeLog("attachmentList:" + s));
//
//            //正文pdf
//            for (String value : bodyList) {
//                if (StringUtils.isNotBlank(value)) {
//                    try {
//                        fileTransfer(value, unnumber, "0");
//                    } catch (IOException e) {
//                        bb.writeLog("正文传输错误==" + value);
//                        e.printStackTrace();
//                    }
//                }
//            }
//            //可查看附件和规章制度正文pdf
//            for (String value : attachmentList) {
//                if (StringUtils.isNotBlank(value)) {
//                    try {
//                        fileTransfer(value, unnumber, "1");
//                    } catch (IOException e) {
//                        bb.writeLog("附件传输错误" + value);
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }

        //1.需要同步的文件docid(2021/11/16更新)
        List<String>  bodyList = new ArrayList<>();
        List<String> attachmentList = new ArrayList<>();

        rs.executeQuery("select zwpdf,fj,gzzdzwpdf from "+tablename+" where requestid = ?",requestId);
        if (rs.next()) {
            String zwpdf = Util.null2String(rs.getString("zwpdf"));
            bodyList.add(zwpdf);
            String fj = Util.null2String(rs.getString("fj"));
            if (StringUtils.isNotEmpty(fj)){
                attachmentList.addAll(Arrays.asList(fj.split(",")));
            }
            String gzzdzwpdf = Util.null2String(rs.getString("gzzdzwpdf"));
            if (StringUtils.isNotEmpty(gzzdzwpdf)) {
                attachmentList.addAll(Arrays.asList(gzzdzwpdf.split(",")));
            }
        }

        //文件传输(只传正文pdf用于转ofd文件,其余文档表通过dblink同步)
        for (String value : bodyList) {
            if (StringUtils.isNotBlank(value)) {
                try {
                    fileTransferForDbLink(value,attachmentList);
                } catch (IOException e) {
                    bb.writeLog("文件传输错误 requestid:"+requestId+"正文docid:" + value);
                    e.printStackTrace();
                }
            }
        }



    }

    /**
     * 根据公文requestid和附件类型过滤掉不能查看的附件
     * @param requestId
     * @param attachFiledId
     * @return
     */
    private String filterAttachment (String tablename, String requestId, String attachFiledId) {
        String finalAttIds = "";
        String originAttachIds = ConvertUtil.getValueByRequestIdAndFiledId(requestId, attachFiledId);
        bb.writeLog("公司发文 dt4过滤前附件fj字段 requestid:"+requestId+" "+attachFiledId+":"+originAttachIds);
        if(StringUtils.isNotEmpty(originAttachIds)) {
            String allowViewSQL = " select *  from " + tablename + "_dt4 t where t.mainid = ( select t2.id from " + tablename + " t2 where t2.requestid = " + requestId + ") " +
                    " and t.wdid in (" + originAttachIds + " ) and t.yxck = 1 order by t.id asc ";
            bb.writeLog("公司发文 dt4开始过滤循序查看fj字段 requestid:" + requestId + " 的sql:" + allowViewSQL);
            rs.executeQuery(allowViewSQL);
            while (rs.next()) {
                finalAttIds = finalAttIds + rs.getString("wdid") + ",";
            }
            if (StringUtils.isNotEmpty(finalAttIds)) {
                finalAttIds = finalAttIds.substring(0, finalAttIds.length() - 1);
            }
        }
        return finalAttIds;
    }

    /**
     * 文件传输2 forDblink
     * @param docid
     * @param attachmentList
     * @throws IOException
     */
    public void fileTransferForDbLink (String docid,List<String> attachmentList) throws IOException {
        Integer imagefileid = null;
        String imagefilename = "";
        Map<String,Object> fileInfo = new HashMap<>();
        HashMap<String, Object> paramMap = new HashMap<>();
        rs.executeQuery("select a.IMAGEFILEID,a.IMAGEFILENAME from IMAGEFILE a ,DOCIMAGEFILE b where\n" +
                "    a.IMAGEFILEID = b.IMAGEFILEID and b.DOCID = ?",docid);
        if (rs.next()) {
            imagefileid = Util.getIntValue(rs.getString("IMAGEFILEID"));
            imagefilename = Util.null2String(rs.getString("IMAGEFILENAME"));
        }
        fileInfo.put("server_docid",docid);
        fileInfo.put("server_imagefileid",imagefileid);
        fileInfo.put("server_imagefilename",imagefilename);
        fileInfo.put("attachment",StringUtils.join(attachmentList,","));
        File file = new IoUtil().generateFile(imagefileid, imagefilename);
        paramMap.put("file", file);
        paramMap.put("fileInfo",JSONObject.toJSONString(fileInfo));
        bb.writeLog("fileInfo:"+JSONObject.toJSONString(fileInfo));
        String str = HttpUtil.post(URL+"/xcoa/api/htsc/document/fileTransfer", paramMap);
        bb.writeLog("信创文件传输结果docid"+docid+"===="+str);
    }



    /**
     * 文件传输
     * @param docid
     * @param unnumber
     * @param type 正文0 附件1
     * @throws IOException
     */
    public void fileTransfer (String docid,String unnumber,String type) throws IOException {
        bb.writeLog("fileTransfer:"+docid+"=="+unnumber+"=="+type);
        Integer imagefileid = null;
        String imagefilename = "";
        String docfiletype = "";
        String doccreaterid ="";
        String doctype = "";
        String filerealpath = "";
        Map<String,String> docInfos = new HashMap<>();
        HashMap<String, Object> paramMap = new HashMap<>();
        //文件上传只需将参数中的键指定（默认file），值设为文件对象即可
        rs.executeQuery("select a.IMAGEFILEID,a.IMAGEFILENAME,a.DOCFILETYPE,b.DOCTYPE,b.DOCCREATERID,c.FILEREALPATH from (select docid,imagefileid,imagefilename,docfiletype from docimagefile where\n" +
                "        docid = ? and versionid = (select max(versionid) from docimagefile where docid = ?)) a left join\n" +
                "    DOCDETAIL b on a.DOCID = b.id\n" +
                "left join IMAGEFILE c on a.IMAGEFILEID = c.IMAGEFILEID",new Object[]{docid,docid});
        if (rs.next()) {
            imagefileid = Util.getIntValue(rs.getString("IMAGEFILEID"));
            imagefilename = Util.null2String(rs.getString("IMAGEFILENAME"));
            docfiletype = Util.null2String(rs.getString("DOCFILETYPE"));
            doccreaterid = Util.null2String(rs.getString("DOCCREATERID"));
            doctype = Util.null2String(rs.getString("DOCTYPE"));
            filerealpath = Util.null2String(rs.getString("FILEREALPATH"));
        }
        docInfos.put("imagefilename",imagefilename);
        docInfos.put("docextendname",imagefilename.substring(imagefilename.lastIndexOf(".")+1));
        docInfos.put("docfiletype",docfiletype);
        docInfos.put("doccreaterid",doccreaterid);
        docInfos.put("doctype",doctype);
        docInfos.put("unnumber",unnumber);
        docInfos.put("type",type);
        docInfos.put("docid",docid);
        paramMap.put("docInfo", JSONObject.toJSONString(docInfos));
        bb.writeLog(docid+"docinfo:"+JSONObject.toJSONString(docInfos));
        File file = new IoUtil().generateFile(imagefileid, imagefilename);
        paramMap.put("file", file);
        String str = HttpUtil.post(URL+"/xcoa/api/htsc/document/fileTransfer", paramMap);
        //String str = HttpUtil.post("http://168.61.8.169:8080/htoa/api/htsc/document/fileTransfer", paramMap);

        bb.writeLog("信创文件传输结果docid"+docid+"===="+str);
    }

}
