package com.engine.htsc.riskReport.service;

import com.alibaba.fastjson.JSONObject;
import com.api.doc.search.service.DocShareService;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.common.util.ServiceUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.htsc.cube.task.SyncFavoriteThread;
import com.engine.htsc.doc.common.AsyncThread;
import com.engine.htsc.doc.util.*;
import com.engine.htsc.workflow.util.WorkflowUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
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.conn.RecordSetTrans;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.DocViewer;
import weaver.docs.docs.VersionIdUpdate;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.util.HT_Util;
import weaver.interfaces.htsc.util.UploadDocUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.wps.officed.ConvertToPdf;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipInputStream;


/**
 * 风险报告送阅操作类 保存送阅记录 CDOY_cduc_0696
 */
public class RiskReportSendReadService {

    private RecordSet rs = new RecordSet();
    private BaseBean bb = new BaseBean();
    private PropBean propBean = new PropBean();
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     *  送阅
     * @param params
     * @return
     */
    public Map<String, Object> saveReaderByCode(Map<String, Object> params) {
        Map<String, Object> retunData = new HashMap<>();
        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");

        saveReaderByCode(handerId,readerIds,readerDepIds,readerGroupIds,readerOrgIds,requestId,params);
        retunData.put("isSuccess","1");
        return retunData;
    }

    /**
     * 传阅
     * @param params
     * @return
     */
    public Map<String,Object> doCirculate(Map<String, Object> params) {
        Map<String, Object> retunData = new HashMap<>();
        String handerId = (String)params.get("handerId");
        String readerIds = (String)params.get("readerIds");
        String requestId = (String)params.get("requestId");

        doCirculate(handerId,readerIds,requestId);
        retunData.put("isSuccess","1");
        return retunData;
    }

    /**
     * 获取已经送阅过的记录
     * @param params
     * @return
     */
    public Map<String, Object> getHasSendRead(Map<String, Object> params) {

        Map<String, Object> retunData = new HashMap<>();
        List<Map<String, Object>> hasSendRecordView = new ArrayList<>();
        List<Map<String, Object>> needSendRecordView = new ArrayList<>();
        try {
            String requestId = (String) params.get("requestId");
            String targetDepts = (String) params.get("sybm");//送阅部门 隐藏字段
            String targetReaderIds = (String) params.get("syry");//送阅人员 隐藏字段
            String targetGroups = (String) params.get("syqz");//送阅群组 隐藏字段
            String targetOrgIds = (String) params.get("syjg");//送阅机构 隐藏字段

            //已经送阅过的
            String hasUserIds = "";
            String hasDeptIds = "";
            String hasGroupIds = "";
            String hasOrgIds = "";

            bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 前台过来的 requestId:"+requestId+" targetGroups:"+targetGroups +" targetOrgIds:"+targetOrgIds
                    + " targetDepts:"+targetDepts+ " targetReaderIds:"+targetReaderIds);
            List<Map<String, Object>> hasSendRecord = getHasSendRead(requestId);

            if (null != hasSendRecord && hasSendRecord.size() > 0) {//已送阅
                for (Map<String, Object> record : hasSendRecord) {
                    if(null!=record.get("syry")&&StringUtils.isNotEmpty((String)record.get("syry"))) {
                        hasUserIds = hasUserIds + (String)record.get("syry")+",";
                        bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅人员sydx:"+(String)record.get("sydx"));
                    }
                    if(null!=record.get("sybm")&&StringUtils.isNotEmpty((String)record.get("sybm"))) {
                        hasDeptIds = hasDeptIds + (String)record.get("sybm")+",";
                        bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅部门sybm:"+(String)record.get("sybm"));
                    }
                    if(null!=record.get("syjg")&&StringUtils.isNotEmpty((String)record.get("syjg"))) {
                        hasOrgIds = hasOrgIds + (String) record.get("syjg")+",";
                        bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅机构syjg:"+(String)record.get("syjg"));
                    }
                    if(null!=record.get("syqz")&&StringUtils.isNotEmpty((String)record.get("syqz"))) {
                        hasGroupIds = hasGroupIds +(String)record.get("syqz")+",";
                        bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅群组syqz:"+(String)record.get("syqz"));
                    }

                    Map<String, Object> recordView = HRResourceUtil.deepClone(record);//原纪录拷贝
                    List<Map<String, Object>> sendUser = HRResourceUtil.getUserInfoMap((String) recordView.get("syry"));
                    List<Map<String, Object>> sendDEpartment = HRResourceUtil.getDepartmentInfoMap((String) recordView.get("sybm"));
                    List<Map<String, Object>> sendOrg = HRResourceUtil.getOrgInfoMap((String)recordView.get("syjg"));
                    List<Map<String, Object>> sendGroup = HRResourceUtil.getGroupInfoMap((String)recordView.get("syqz"));
                    recordView.put("sydx",sendUser);//转成前台易于展示的方式
                    recordView.put("sybm",sendDEpartment);
                    recordView.put("syjg",sendOrg);
                    recordView.put("syqz",sendGroup);
                    hasSendRecordView.add(recordView);
                }
            }


            //去掉已送阅的
            String needUserids = HRResourceUtil.diffInLeftNotInRight(targetReaderIds,hasUserIds);
            String needDepts = HRResourceUtil.diffInLeftNotInRight(targetDepts,hasDeptIds);
            String needOrgIds = HRResourceUtil.diffInLeftNotInRight(targetOrgIds,hasOrgIds);
            String needGroupIds = HRResourceUtil.diffInLeftNotInRight(targetGroups,hasGroupIds);

            needSendRecordView.addAll(HRResourceUtil.getUserInfoMap(needUserids));
            needSendRecordView.addAll(HRResourceUtil.getDepartmentInfoMap(needDepts));
            needSendRecordView.addAll(HRResourceUtil.getOrgInfoMap(needOrgIds));
            needSendRecordView.addAll(HRResourceUtil.getGroupInfoMap(needGroupIds));

            bb.writeLog("requestId:"+requestId+"获取需要送阅的四种 needUserids:"+needUserids+" needDepts:"+needDepts+
                    " needOrgIds:"+needOrgIds+" needGroupIds:"+needGroupIds);
            bb.writeLog("requestId:"+requestId+" needSendRecordView.大小"+needSendRecordView.size());

        }catch(Exception e) {
            e.printStackTrace();
        }

        retunData.put("needSendReadList",needSendRecordView);
        retunData.put("hasSendReadList",hasSendRecordView);
        retunData.put("isSuccess","1");
        return retunData;
    }

    /**
     * 获取已经送阅过的记录
     * @param requestId
     * @return
     */
    private List<Map<String, Object>> getHasSendRead(String requestId) {
        List<Map<String, Object>> sendList = new ArrayList<>();
        rs.executeQuery("select * from uf_fxbgsyjl t where t.lcid = ?  order by t.sysj desc ",new Object[]{requestId});
        while(rs.next()) {
            Map<String,Object> record = 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));
                record.put(fieldName, fieldValue);
            }
            sendList.add(record);//保存所有的表记录
        }
        bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead sendList大小为:"+sendList.size());
        System.out.println("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead sendList大小为:"+sendList.size());
        return sendList;
    }

    /**
     *  生成送阅记录
     * @param  handerId 处理人id
     * @param readerIds 看阅对象工号（选人的情况）
     * @param readerDepIds 看阅部门 （选部门的情况）
     * @param readerGroupIds 看阅群组 （选群组的情况）
     * @param requestId 泛微流程编号
     * @param params 保留参数
     * @return
     */
    private void saveReaderByCode(String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                                    String requestId,Map<String,Object> params) {
        //主表字段
        //根据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");
            bb.writeLog("风险报告 RiskReportSendReadCmd--saveReaderByCode requestid:"+requestId+"对应的流程表单的表名为:"+tablename);
        }

        //查询当前编辑数据的主表数据
        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);
                }
            }
        }

        //生成送阅最终权限记录
        doSaveOrUpdate(tablename,handerId,readerIds,readerDepIds,readerGroupIds,readerOrgIds, requestId,params);
        //刷新泛微的建模权限
        modelRightRefresh(handerId,requestId);
        //将本次送阅的和已经送过的调用rms接口更新权限
        try {
            invokeRMSPutPolicy(handerId, readerIds, readerDepIds, readerGroupIds, readerOrgIds, requestId, params);
        }catch(Exception e) {
            e.printStackTrace();
            bb.writeLog("requestId:"+requestId+" 更新rms策略翻车:"+e.getMessage(),e);
        }
        //发送企微消息
        AsyncThread send = new AsyncThread(this, "sendLinkMessage",
                new Object[] { requestId,readerIds, readerDepIds, readerOrgIds, readerGroupIds, params});
        send.start();
    }

    /**
     * 保存送阅记录一波流
     * @param tablename
     * @param handerId
     * @param readerIds
     * @param readerDepIds
     * @param readerGroupIds
     * @param requestId
     * @param params
     */
    private void doSaveOrUpdate(String tablename,String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                                String requestId,Map<String,Object> params) {
        Map<String, String> sendReadDatas = new CommonUtil().getSendReadDatas(readerIds, readerDepIds, readerOrgIds, readerGroupIds);
        String readuserids = sendReadDatas.get("readuserids");
        String readgroupids = sendReadDatas.get("readgroupids");
        String querySQL = " select * from uf_fxbgky t where t.lcid = ?";
        rs.executeQuery(querySQL, new Object[]{requestId});
        if(rs.next()){
            bb.writeLog("风险报告 查询泛微主表送阅记录存在 RiskReportSendReadCmd--doSaveOrUpdate  lcid:"+requestId+" 执行更新方法");
            String syry_readuserids = rs.getString("readuserids");
            String syry_readgroupids = rs.getString("readgroupids");
            String syry_db = rs.getString("syry");
            String sybm_db = rs.getString("sybm");
            String syjg_db = rs.getString("syjg");
            String syqz_db = rs.getString("syqz");
            doUpdateMainReader(readerIds,readerDepIds,readerGroupIds,readerOrgIds,requestId,params,syry_db,sybm_db,syjg_db,syqz_db,syry_readuserids,syry_readgroupids,readuserids,readgroupids);
        }else {
            bb.writeLog("风险报告 查询泛微主表送阅记录不存在 RiskReportSendReadCmd--doSaveOrUpdate  lcid:"+requestId+" 执行插入方法");
            doSaveMainReader(tablename,handerId,readerIds,readerDepIds,readerGroupIds,readerOrgIds,requestId,params,readuserids,readgroupids);
        }

        //调用文件权限接口TODO
        doSaveShareDoc(tablename,handerId,readerIds,readerDepIds, readerGroupIds, readerOrgIds,requestId, params);
        bb.writeLog("requestId:"+requestId+"送阅后调用文件权限接口完成");
        //保存操作记录
        doSaveOperationRecord(tablename,handerId,readerIds,readerDepIds,readerGroupIds,readerOrgIds,requestId,params);
        bb.writeLog("requestId:"+requestId+"保存操作记录完成");

    }

    /**
     * 保存送阅记录到数据库
     * @param handerId
     * @param readerIds
     * @param readerDepIds
     * @param readerGroupIds
     * @param requestId
     * @param params
     */
    private void doSaveMainReader(String tablename,String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                                  String requestId,Map<String,Object> params,String readuserids,String readgroupids) {
        //数据库save
        String noticeReadformid = propBean.getPropName("RiskReport-SendReadFormID");
        String dispatchTypeStr = "";
        String batchInsertSQL = "";
        //筛选出勾选了允许查看的附件
        String fj = filterAttachment(tablename,requestId,"fj");
        RiskReportService riskReportService = ServiceUtil.getService(RiskReportService.class);
        riskReportService.docConvertToPdf(requestId);

        //构造送阅记录的表单数据 只做一遍
        batchInsertSQL = "insert into uf_fxbgky t (t.ID,t.REQUESTID,t.JJCD,t.LXFS,t.NGRQ,t.SYFW,t.SFCWGZ,t.BGLB,t.BGLX,t.BGNRGS,t.gzzdzwpdf," +
                "t.ZSDW,t.CSDW,t.SZJG,t.WZ,t.ZS,t.LSLCLJ,t.SZBM,t.NGBM,t.FJ2," +
                "t.MJ,t.WH,t.ZW,t.GSFSDW,t.SFYQYWZSJ,t.LCBH,t.BZ,t.CS," +
                "t.JJYY,t.NGR,t.CB,t.SFNBSY,t.YZ,t.FJ3,t.SFLSLCSJ,t.LSLCCYR,t.TZYDYY," +
                "t.ZT,t.FORMMODEID,t.MODEDATACREATER,t.MODEDATACREATERTYPE,t.MODEDATACREATEDATE,t.MODEDATACREATETIME,t.MODEDATAMODIFIER," +
                "t.MODEDATAMODIFYDATETIME,t.MODEUUID,t.BT,t.LCID,t.SYBM,t.SYRY,t.syjg,t.syqz,t.readuserids,t.readgroupids,t.FJ,t.zwpdf,t.rmsfj,t.sfcy,t.lastupdatetime"+
                ")" +
                "select uf_fxbgky_id.nextval,t2.REQUESTID,t2.JJCD,t2.LXFS,t2.NGRQ,t2.SYFW,t2.SFCWGZ,t2.BGLB,t2.BGLX,t2.BGNRGS,t2.gzzdzwpdf," +
                "t2.ZSDW,t2.CSDW,t2.SZJG,t2.WZ,t2.ZS,t2.LSLCLJ,t2.SZBM,'"+getDeptHistoryName(tablename,requestId)+"',t2.FJ2," +
                "t2.MJ,t2.WH,t2.ZW,t2.GSFSDW,t2.SFYQYWZSJ,t2.LCBH,t2.BZ,t2.CS," +
                "t2.JJYY,t2.NGR,t2.CBDW,t2.SFNBSY,t2.YZ,t2.FJ3,t2.SFLSLCSJ,t2.LSLCCYR,t2.TZYDYY," +
                "t2.ZT,'"+noticeReadformid+"','"+handerId+"','0',to_char(SYSDATE,'YYYY-MM-DD'),to_char(SYSDATE,'HH24:MI:SS'),'"+handerId+"'," +
                "to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS'),to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS')||'SYSTEM',t3.requestname,t2.requestid,'" +readerDepIds+"','"+readerIds+"','"+
                readerOrgIds+"','"+readerGroupIds+"','"+readuserids+"','"+readgroupids+"','"+fj+"',t2.zwpdf,t2.rmsfj,t2.sfcy,to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS') "+
                "from "+tablename+" t2,workflow_requestbase t3 where t3.requestid = t2.requestid and  t2.requestid = '"+requestId+"'";
        bb.writeLog("风险报告 RiskReportSendReadCmd--doSave  requestid:"+requestId+"插入送阅记录sql打印:"+batchInsertSQL);
        System.out.println("风险报告 RiskReportSendReadCmd--doSave  requestid:"+requestId+"插入送阅记录sql打印:"+batchInsertSQL);
        rs.executeUpdate(batchInsertSQL);


        String mainId = "";
        String mainIdSQL = " select t.id from uf_fxbgky t where t.lcid =  '"+requestId+"'";
        rs.executeQuery(mainIdSQL);
        if(rs.next()) {
            mainId = rs.getString("id");
            bb.writeLog("风险报告 RiskReportSendReadCmd--doSave  requestid:"+requestId+" 看阅主记录的序列为:"+mainId);
        }

        //将风险报告附件权限dt4插入到建模dt4  只做一遍
        String operatetime = TimeUtil.getCurrentTimeString();
        String batchInsertSQL2 = " insert into uf_fxbgky_dt4 t (id,mainid,wdid,fjid,bt,yxck,yxxz,sflzlc,mxid,lastupdatetime) "+
                " select uf_fxbgky_dt4_id.nextval,"+mainId +",t1.wdid,t1.fjid,t1.bt,t1.yxck,t1.yxxz,t1.sflzlc,t1.id,'"+operatetime +"' from  "+tablename+"_dt4 t1 "+
                " where t1.mainid = ( "+
                " select t2.id from "+tablename+" t2 where t2.requestid = '"+requestId+"' ) ";
        bb.writeLog("风险报告 RiskReportSendReadCmd--dt4保存  requestid:"+requestId+"插入建模dt4记录sql打印:"+batchInsertSQL2);
        rs.executeUpdate(batchInsertSQL2);
        bb.writeLog("风险报告 RiskReportSendReadCmd--dt4保存完成泛微说不生效  requestid:"+requestId+"插入建模dt4记录sql打印:"+batchInsertSQL2);

        //将uf_gwky的zwpdf信息存入uf_gwky_dt7(王杰)//TODO
        rs.execute("select zwpdf from uf_fxbgky where LCID = '"+requestId+"'");
        rs.next();
        String wdid = Util.null2String(rs.getString("zwpdf"));
        String fjid = FileUtil.getFjid(wdid);
        String fileid = FileUtil.getFileid(fjid);
        String imagefilename = FileUtil.getImageFileName(fjid);
        String batchInsertSQL3 = "insert into uf_fxbgky_dt7 (MAINID,WDID,FJID,BT,FILEID,lastupdatetime) values (?,?,?,?,?,?)";

        rs.executeUpdate(batchInsertSQL3,mainId,wdid,fjid,imagefilename,fileid,operatetime);
        rs.next();
        bb.writeLog("风险报告 RiskReportSendReadCmd--dt7保存  requestid:"+requestId+"插入建模dt7记录sql打印:"+batchInsertSQL3);

    }


    /**
     * 保存送阅记录操作日志 只存在人传人
     * @param tablename
     * @param handerId
     * @param readerIds
     * @param readerDepIds
     * @param readerGroupIds
     * @param requestId
     * @param params
     */
    private void doSaveOperationRecord(String tablename,String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                                       String requestId,Map<String,Object> params) {

        String formmodeid = propBean.getPropName("RiskReport-SendReadOperationFormID");
        String batchInsertOperationSQL = " insert into uf_fxbgsyjl t(t.id,t.requestid,t.lcid,t.syry,t.sybm,t.syjg,t.syqz,t.sysj,t.formmodeid,t.MODEDATACREATEDATE,t.MODEDATACREATETIME) "+
                " select uf_fxbgsyjl_id.nextval,'"+requestId+"','"+requestId+"','"+readerIds+"','"+readerDepIds+"','"+readerOrgIds+"','"+readerGroupIds+
                "',to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS'),'"+formmodeid+"',to_char(SYSDATE,'YYYY-MM-DD'),to_char(SYSDATE,'HH24:MI:SS') from dual";
        bb.writeLog("风险报告 RiskReportSendReadCmd--doSave  requestid:"+requestId+"插入送阅记录已送阅操作sql打印:"+batchInsertOperationSQL);
        rs.executeUpdate(batchInsertOperationSQL);
    }


    /**
     * 多次重复送阅时更新送阅记录
     */
    private void doUpdateMainReader(String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds, String requestId,Map<String,Object> params,
                                     String syry_db,String sybm_db,String syjg_db,String syqz_db,String syry_readuserids,String syry_readgroupids,String readuserids,String readgroupids) {
        //更新送阅主表
        String readerIdTemp = StringUtils.isNotEmpty(readerIds)?syry_db+","+readerIds:syry_db;
        String readerDepIdTemp = StringUtils.isNotEmpty(readerDepIds)?sybm_db+","+readerDepIds:sybm_db;
        String readerGroupIdTemp = StringUtils.isNotEmpty(readerGroupIds)?syqz_db+","+readerGroupIds:syqz_db;
        String readerOrgIdTemp = StringUtils.isNotEmpty(readerOrgIds)?syjg_db+","+readerOrgIds:syjg_db;
        String readuseridsTemp = StringUtils.isNotEmpty(readuserids)?syry_readuserids+","+readuserids:syry_readuserids;
        String readgroupidsTemp = StringUtils.isNotEmpty(readgroupids)?syry_readgroupids+","+readgroupids:syry_readgroupids;
        String updateSQL = " update uf_fxbgky t set t.readuserids ='"+readuseridsTemp+"',t.readgroupids='"+readgroupidsTemp+"'," +
                "t.syry = '"+readerIdTemp+"', t.sybm = '"+readerDepIdTemp+"', t.syjg = '"+readerOrgIdTemp+"', "+
                " t.syqz = '"+readerGroupIdTemp+"', t.lastupdatetime = to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS') "+
                " where t.lcid = '"+requestId+"'";
        bb.writeLog("风险报告 RiskReportSendReadCmd--doUpdateMainReader 更新送阅主表sql:"+updateSQL);
        rs.executeUpdate(updateSQL);
    }

    /**
     * 获取已经传阅过的记录+当前用户可选择的传阅对象 人传人
     * @param params
     * @return
     */
    public Map<String,Object> getHasCirculated(Map<String, Object> params) {

        Map<String, Object> retunData = new HashMap<>();
        List<Map<String, Object>> hasSendRecordView = new ArrayList<>();
        List<Map<String, Object>> needSendRecordView = new ArrayList<>();
        try {

            String requestId = (String) params.get("requestId");
            String cyry = (String) params.get("handerId");//前台传过来的传阅人员 即当前看阅人
            String querySQL = " select * from uf_fxbgky t where t.lcid = ?";
            rs.executeQuery(querySQL, new Object[]{requestId});
            bb.writeLog("风险报告 RiskReportSendReadCmd--getHasCirculated requestid:"+requestId+"传阅时获取主表送阅记录sql:"+querySQL);
            if(rs.next()){
                String sybm_db = rs.getString("sybm");
                String syry_db = rs.getString("syry");
                String syjg_db = rs.getString("syjg");
                String syqz_db = rs.getString("syqz");
                List<Map<String, Object>> sybm_map = HRResourceUtil.getDepartmentInfoMap(sybm_db);
                List<Map<String,Object>> syry_map = HRResourceUtil.getUserInfoMap(syry_db);
                List<Map<String,Object>> syqz_map = HRResourceUtil.getGroupInfoMap(syqz_db);
                List<Map<String,Object>> syjg_map = HRResourceUtil.getOrgInfoMap(syjg_db);
                Map<String,Object> cyryUserinfo = HRResourceUtil.getUserInfoMap(cyry).get(0);//当前传阅人员
                bb.writeLog("风险报告 RiskReportSendReadCmd--getHasCirculated requestid:"+requestId+"当前传阅人员:"+cyryUserinfo);

                //查询当前传阅人的所有部门 群组 角色
                String cyryAllUserIds = HRResourceUtil.getAllUserIdsByUserIds(cyry);
                String cyryAllDepartmentIds = HRResourceUtil.getAllDepartmentIdsByUserIds(cyry);
                String cyryBelongGroupIds =  HRResourceUtil.getBelongGroupIdsByUserId(cyry);

                List<String> finalUserids = new ArrayList<>();//最终可以传阅人员

                //基于人送的 则传阅对象为这个人所在部门下的所有人
                if(StringUtils.isNotEmpty(BeanUtil.commonLeftAndRight(cyryAllUserIds,syry_db))) {
                    String depids = HRResourceUtil.getExactDepartmentIdsByUserIds(BeanUtil.commonLeftAndRight(cyryAllUserIds,syry_db));
                    bb.writeLog(requestId+"传阅基于人送的common:"+BeanUtil.commonLeftAndRight(cyryAllUserIds,syry_db)+" depids:"+depids);
                    finalUserids.addAll(HRResourceUtil.getUserIdListByDepIds(depids));
                }
                //基于部门送的 则传阅对象为这个部门下的所有人
                if(StringUtils.isNotEmpty(BeanUtil.commonLeftAndRight(cyryAllDepartmentIds,sybm_db))) {
                    String depids = BeanUtil.commonLeftAndRight(cyryAllDepartmentIds,sybm_db);
                    bb.writeLog(requestId+"传阅基于部门送的common:"+BeanUtil.commonLeftAndRight(cyryAllDepartmentIds,sybm_db)+ " depids:"+depids);
                    finalUserids.addAll(HRResourceUtil.getUserIdListByDepIds(depids));
                }


                //基于群组送的 则传阅对象为这个群组里面的所有人
                if(StringUtils.isNotEmpty(BeanUtil.commonLeftAndRight(cyryBelongGroupIds,syqz_db))) {
                    String qzids = BeanUtil.commonLeftAndRight(cyryBelongGroupIds,syqz_db);
                    bb.writeLog(requestId+"传阅基于群组送的common:"+BeanUtil.commonLeftAndRight(cyryBelongGroupIds,syqz_db)+" qzids:"+qzids);
                    finalUserids.addAll(HRResourceUtil.getUserIdListByGroupIds(qzids));
                }

                if(CollectionUtils.isNotEmpty(finalUserids)) {//去重
                    BeanUtil.removeDuplicateWithOrder(finalUserids);
                }

                List<Map<String, Object>> circulateHistoryViewList = new ArrayList();
                String queryHistorySQL = " select t.*  from uf_cyjl t where t.cyry = ? and t.lcid = ? order by t.sysj desc ";
                bb.writeLog("风险报告 RiskReportSendReadCmd--getHasCirculated requestid:"+requestId+"查询某人历史传阅记录:"+queryHistorySQL);
                rs.executeQuery(queryHistorySQL, new Object[]{cyry, requestId});
                while (rs.next()) {
                    Map<String,Object> record = 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));
                        record.put(fieldName, fieldValue);
                    }
                    Map<String, Object> recordView = HRResourceUtil.deepClone(record);//原纪录拷贝
                    if(null!=recordView.get("syry")) {
                        List<Map<String, Object>> sendUser = HRResourceUtil.getUserInfoMap((String) recordView.get("syry"));
                        recordView.put("syry",sendUser);
                    }
                    circulateHistoryViewList.add(recordView);
                }
                retunData.put("circulateHistoryList",circulateHistoryViewList);//当前用户该流程的历史传阅记录
                retunData.put("circulateAvaliableUsers",HRResourceUtil.getUserInfoMap(finalUserids));//可传阅的人员范围
            }
        }catch (Exception e) {
            e.printStackTrace();
            bb.writeLog("风险报告 RiskReportSendReadCmd传阅出错:"+e,e.getMessage());
        }
        return retunData;
    }

    /**
     * 传阅 人传人
     * @param handerId
     * @param readerIds
     * @param requestId
     */
    private void doCirculate(String handerId, String readerIds, String requestId) {
        bb.writeLog(df.format(new Date())+"传阅你们说卡 step1 requestId:"+requestId);

        List<String> readerIdsList = BeanUtil.splitByPerNum(readerIds,100);

        for (String perReaderId : readerIdsList) {
            String batchInsertOperationSQL = " insert into uf_cyjl " +
                    "values (uf_cyjl_id.nextval," + requestId + ",'" + requestId + "',to_char(SYSDATE,'YYYY-MM-DD HH24:MI:SS')," + handerId + ",'" + perReaderId + "' )";
            bb.writeLog("风险报告 RiskReportSendReadCmd--doCirculate  requestid:" + requestId + "插入传阅记录:" + batchInsertOperationSQL);
            rs.executeUpdate(batchInsertOperationSQL);
            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step2 requestId:" + requestId);
            //更新公文看阅主表信息 做成和老oa一样 只添加策略，不添加送阅对象送阅
            //doUpdateMainReader(perReaderId, "", "", "", requestId, null);

            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step3 requestId:" + requestId);
            bb.writeLog("风险报告 RiskReportSendReadCmd--doCirculate  requestid:" + requestId + " 传阅完成");


            //根据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});
            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step4 requestId:" + requestId);
            String tablename = "";
            if (rs.next()) {
                tablename = rs.getString("tablename");
                bb.writeLog("风险报告 RiskReportSendReadCmd--saveReaderByCode requestid:" + requestId + "对应的流程表单的表名为:" + tablename);
            }
            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step5 requestId:" + requestId);
            //调用文件权限接口TODO
            doSaveShareDoc(tablename, handerId, perReaderId, "", "", "", requestId, null);
            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step6 requestId:" + requestId);
            //刷新泛微的建模权限
            modelRightRefresh(handerId, requestId);
            bb.writeLog(df.format(new Date()) + "传阅你们说卡 step7 requestId:" + requestId);

            //刷新rms策略权限
            //将本次送阅的和已经送过的调用rms接口更新权限
            try {
                invokeRMSPutPolicy(handerId, readerIds, null, null, null, requestId,null);
            }catch(Exception e) {
                e.printStackTrace();
                bb.writeLog("requestId:"+requestId+" 传阅更新rms策略翻车:"+e.getMessage(),e);
            }
        }
    }

    /**
     * 添加文档权限记录
     * @param tablename
     * @param handerId
     * @param readerIds
     * @param readerDepIds
     * @param readerGroupIds
     * @param requestId
     * @param params
     * seclevel-权限（1-查看；2-编辑，3-完全控制）
     */
    public void doSaveShareDoc(String tablename,String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                               String requestId,Map<String,Object> params)  {

        String zw_docid = "";
        String zwpdf_docid = "";
        //先查询正文和正文pdf文件id
        String findPdfSQL = " select zw,zwpdf from "+tablename+" t where t.requestid = "+requestId;
        bb.writeLog("发文 查询正文和正文pdf文件 requestId:"+requestId+" sql:"+findPdfSQL);
        rs.executeQuery(findPdfSQL);
        if(rs.next()) {
            zw_docid = rs.getString("zw");
            zwpdf_docid = rs.getString("zwpdf");
            bb.writeLog("发文 查询正文和正文pdf文件 requestId:"+requestId+" zw_docid:"+zw_docid+" zwpdf_docid:"+zwpdf_docid);
        }

        //泛微用来同步shareinnerdoc数据的方法 直接调用
        DocViewer dv = new DocViewer();
        DocShareService docShareService = new DocShareService();
        User currentUser = User.getUser(Integer.valueOf(handerId),0);
        String fileRightSQL = " select * from "+tablename+"_dt4 t where t.mainid = ( "+
                " select t2.id from "+ tablename +" t2 where t2.requestid = '"+ requestId+"' ) ";
        bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 查询公文流程附件全部权限sql:"+fileRightSQL);
        rs.executeQuery(fileRightSQL);
        while (rs.next()) {
            String allowView = rs.getString("yxck");//允许查看
            String docid = rs.getString("wdid");//文档id
            boolean allowDownload = rs.getString("yxxz").equals("0")?false:true;//是否允许下载
            bb.writeLog("requestid:"+requestId+" 查询公文流程附件权限结果:"+" docid:"+docid+" 允许查看:"+allowView+" 允许下载:"+allowDownload);
            if("0".equals(allowView)) {
                bb.writeLog("requestid:"+requestId+" 风险报告 RiskReportSendReadCmd-dt4附件权限 docid:"+docid+" 不允许查看则跳过");
                continue;
            }else {
                if(StringUtils.isNotEmpty(readerDepIds)) {
                    //华泰组织机构和具体部门 是否包含下级部要区分对待
                    /**
                     * @params 	user-当前用户
                     * 			docid-文档id
                     * 			departmentids-部门id集合，逗号隔开（被赋予权限对象）
                     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
                     *			fromlevel-最低安全级别
                     *			tolevel-最高安全级别
                     *			containsSub-是否含下级
                     *			download-是否可下载
                     * */
                    bb.writeLog("requestid:"+requestId+" 按部门添加权限参数:"+currentUser+","+Integer.valueOf(docid)+","+readerDepIds+","+allowDownload);
                    docShareService.addShareForDepartment(currentUser,Integer.valueOf(docid),readerDepIds,1,0,255,false,allowDownload);
                    bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" dt4附件权限 docid:"+docid+" 按部门添加权限完成"+" departmentIds:"+readerDepIds);
                    if(docid.equals(zw_docid)&&StringUtils.isNotEmpty(zwpdf_docid)) {//如果是正文 则正文pdf的下载权限和正文一样
                        docShareService.addShareForDepartment(currentUser,Integer.valueOf(zwpdf_docid),readerDepIds,1,0,255,false,allowDownload);
                        bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 正文对应的pdf件 zwpdf_docid:"+zwpdf_docid+" 按部门添加权限完成"+" departmentIds:"+readerDepIds);
                    }
                }
                if(StringUtils.isNotEmpty(readerIds)) {
                    /**
                     * @params 	user-当前用户
                     * 			docid-文档id
                     * 			userids-用户id集合，逗号隔开（被赋予权限对象）
                     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
                     *			download-是否可下载
                     * */
                    bb.writeLog("requestid:"+requestId+" 按人员添加权限参数:"+currentUser+","+Integer.valueOf(docid)+","+readerIds+","+allowDownload);
                    docShareService.addShareForUser(currentUser,Integer.valueOf(docid),readerIds,1,allowDownload);
                    bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" dt4附件权限 docid:"+docid+" 按人员添加权限完成"+" readerIds:"+readerIds);
                    if(docid.equals(zw_docid)&&StringUtils.isNotEmpty(zwpdf_docid)) {//如果是正文 则正文pdf的下载权限和正文一样
                        docShareService.addShareForUser(currentUser,Integer.valueOf(zwpdf_docid),readerIds,1,allowDownload);
                        bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 正文对应的pdf件 zwpdf_docid:"+zwpdf_docid+" 按人员添加权限完成"+" readerIds:"+readerIds);
                    }
                }
                if(StringUtils.isNotEmpty(readerGroupIds)) {
                    bb.writeLog("requestid:"+requestId+" 按群组添加权限参数:"+currentUser+","+Integer.valueOf(docid)+","+readerGroupIds+","+allowDownload);
                    addShareForGroup(requestId,currentUser,docid,readerGroupIds,allowDownload);
                    bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" dt4附件权限 docid:"+docid+" 按群组添加权限完成"+" readerGroupIds:"+readerGroupIds);
                    if(docid.equals(zw_docid)&&StringUtils.isNotEmpty(zwpdf_docid)) {//如果是正文 则正文pdf的下载权限和正文一样
                        addShareForGroup(requestId,currentUser,zwpdf_docid,readerGroupIds,allowDownload);
                        bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 正文对应的pdf件 zwpdf_docid:"+zwpdf_docid+" 按群组添加权限完成"+" readerGroupIds:"+readerGroupIds);
                    }
                }
                if(StringUtils.isNotEmpty(readerOrgIds)) {//按组织机构一定要包含下级 泛微这个产品曲线救国
                    bb.writeLog("requestid:"+requestId+" 按组织机构添加权限参数:"+currentUser+","+Integer.valueOf(docid)+","+readerOrgIds+","+allowDownload);
                    docShareService.addShareForDepartment(currentUser,Integer.valueOf(docid),readerOrgIds,1,0,255,true,allowDownload);
                    bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" dt4附件权限 docid:"+docid+" 按组织机构添加权限完成"+" readerOrgIds:"+readerOrgIds);
                    if(docid.equals(zw_docid)&&StringUtils.isNotEmpty(zwpdf_docid)) {//如果是正文 则正文pdf的下载权限和正文一样
                        docShareService.addShareForDepartment(currentUser,Integer.valueOf(zwpdf_docid),readerOrgIds,1,0,255,true,allowDownload);
                        bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 正文对应的pdf件 zwpdf_docid:"+zwpdf_docid+" 按组织机构添加权限完成"+" readerOrgIds:"+readerOrgIds);
                    }
                }


                try{
                    bb.writeLog("requestId:"+requestId+"setDocShareByDoc docid:"+docid+"开始");
                    dv.setDocShareByDoc(docid + "");
                    bb.writeLog("requestId:"+requestId+"setDocShareByDoc docid:"+docid+"完成");
                }catch(Exception e){
                    e.printStackTrace();
                    bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" dt4附件权限 docid:"+docid+" 同步shareinnerdoc出错:"+e.getMessage(),e);
                }
            }
        }

        try{//综合发文没有正文pdf
            if(StringUtils.isNotEmpty(zwpdf_docid)) {
                bb.writeLog("requestId:" + requestId + "setDocShareByDoc zwpdf_docid:" + zwpdf_docid + "开始");
                dv.setDocShareByDoc(zwpdf_docid + "");
                bb.writeLog("requestId:" + requestId + "setDocShareByDoc zwpdf_docid:" + zwpdf_docid + "完成");
            }
        }catch(Exception e){
            e.printStackTrace();
            bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:"+requestId+" 正文的pdf件 zwpdf_docid:"+zwpdf_docid+" 同步shareinnerdoc出错:"+e.getMessage(),e);
        }
    }


    /**
     * 刷新泛微建模权限信息
     * @param  handleId  当前处理人id
     * @param requestId
     */
    public void modelRightRefresh(String handleId, String requestId) {

        ModeRightInfo moderight = new ModeRightInfo();

        //刷新送阅主表
        String mainSQL = " select * from uf_fxbgky t where t.lcid = ? ";
        rs.executeQuery(mainSQL,new Object[]{requestId});
        if(rs.next()) {
            String mainFormid = rs.getString("formmodeid");
            String id = rs.getString("id");
            moderight.editModeDataShare(Integer.valueOf(handleId), Integer.valueOf(mainFormid), Integer.valueOf(id));
            bb.writeLog("风险报告 送阅后刷新主表建模权限 requestid:"+requestId+" userid:"+ handleId +" billid:"+id);
        }

        //刷新送阅记录表
        String operateSQL = " select * from uf_fxbgsyjl t where t.lcid = ? ";
        while(rs.next()) {
            String operationFormid = rs.getString("formmodeid");
            String id = rs.getString("id");
            moderight.editModeDataShare(Integer.valueOf(handleId), Integer.valueOf(operationFormid), Integer.valueOf(id));
            bb.writeLog("风险报告 送阅后刷新操作记录表建模权限 requestid:"+requestId+" userid:"+ handleId +" billid:"+id);
        }
    }

    /**
     * 根据公文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;
    }

    /**
     * 调用RMS接口
     * @param handerId
     * @param readerIds
     * @param readerDepIds
     * @param readerGroupIds
     * @param readerOrgIds
     * @param requestId
     * @param params
     * @return
     */
    private String invokeRMSPutPolicy(String handerId, String readerIds,String readerDepIds, String readerGroupIds, String readerOrgIds,
                                      String requestId,Map<String,Object> params) throws Exception{
        String hasUserIds = "";
        String hasDeptIds = "";
        String hasOrgIds = "";
        String hasGroupIds = "";

        List<Map<String, Object>> hasSendRecord = getHasSendRead(requestId);

        if (null != hasSendRecord && hasSendRecord.size() > 0) {//已送阅
            for (Map<String, Object> record : hasSendRecord) {
                if(null!=record.get("syry")&&StringUtils.isNotEmpty((String)record.get("syry"))) {
                    hasUserIds = hasUserIds + (String)record.get("syry")+",";
                    bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅人员sydx:"+(String)record.get("sydx"));
                }
                if(null!=record.get("sybm")&&StringUtils.isNotEmpty((String)record.get("sybm"))) {
                    hasDeptIds = hasDeptIds + (String)record.get("sybm")+",";
                    bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅部门sybm:"+(String)record.get("sybm"));
                }
                if(null!=record.get("syjg")&&StringUtils.isNotEmpty((String)record.get("syjg"))) {
                    hasOrgIds = hasOrgIds + (String) record.get("syjg")+",";
                    bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅机构syjg:"+(String)record.get("syjg"));
                }
                if(null!=record.get("syqz")&&StringUtils.isNotEmpty((String)record.get("syqz"))) {
                    hasGroupIds = hasGroupIds +(String)record.get("syqz")+",";
                    bb.writeLog("风险报告 获取已送阅 RiskReportSendReadCmd-getHasSendRead 数据库已送阅记录 requestId:"+requestId+" 送阅群组syqz:"+(String)record.get("syqz"));
                }
            }
        }

        String totalUserIds = hasUserIds+readerIds;
        String totalDeptIds = hasDeptIds+readerDepIds;
        String totalsOrgIds = hasOrgIds+readerGroupIds;
        String totalGroupIds = hasGroupIds+readerOrgIds;

        List<String> readerBadge = HRResourceUtil.getUserBadgeList(totalUserIds);
        List<String> readerDeptCodes = HRResourceUtil.getDeptcodeList(totalDeptIds);
        readerDeptCodes.addAll(HRResourceUtil.getOrgcodeList(totalsOrgIds));
        List<String> readerGroups = HRResourceUtil.getGroupcodeList(totalGroupIds);
        JSONObject dataObject = new JSONObject();
        dataObject.put("readerBadges",readerBadge);
        dataObject.put("readerDeptCodes",readerDeptCodes);
        dataObject.put("readerGroupCodes",readerGroups);
        dataObject.put("requestId",requestId);
        //TODO   rms的其他控制参数
        dataObject.put("allowPrint",false);
        dataObject.put("allowCopy",false);

        String url = propBean.getPropName("RMSSendReaderForNew");
        String encode = "utf-8";
        Map<String, String> headers = new HashMap<>();
        bb.writeLog("requestId:"+requestId+" 风险报告送阅环节调用rms接口参数:"+dataObject.toString());
        headers = new HTUtil().getAppHeader();
        bb.writeLog("requestId:"+requestId+"invokeRMSPutPolicy==安全增加headers==="+headers.toString());
        String content = httpPostRaw(url,dataObject.toString(), headers, encode);
        bb.writeLog("requestId:"+requestId+"invokeRMSPutPolicy== httpPostRaw返回:"+content);
        JSONObject rmsObject = JSONObject.parseObject(content);
        bb.writeLog("requestId:"+requestId+" 风险报告送阅环节调用rms返回:"+rmsObject.toString());
        return content;
    }

    /**
     * 发送http请求
     *
     * @param url        接口地址
     * @param stringJson 请求的 json 字符串
     * @param headers    头部参数
     * @param encode     编码
     * @return 响应结果
     */
    private String httpPostRaw(String url, String stringJson, Map<String, String> headers,
                               String encode) {
        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;
    }


    /**
     * 发送企业微信公文看阅消息
     * @param requestId
     * @return
     */
    private String sendLinkMessage(String requestId,String readerIds, String deptIds, String orgIds, String groupIds,
                                   Map<String,Object> param) {
        bb.writeLog("requestId:"+requestId+" 开始sendLinkMessage readerIds:"+readerIds+" deptIds:"+deptIds+" orgIds:"+orgIds+" groupIds:"+groupIds);
        String linkDocMessageId = propBean.getPropName("LinkDocMessageId");

        List<String> receiverList = HRResourceUtil.getAllUserIdsByUserIdDepIdOrgIdGroupId(
                BeanUtil.convertStrToList(readerIds),
                BeanUtil.convertStrToList(deptIds),
                BeanUtil.convertStrToList(orgIds),
                BeanUtil.convertStrToList(groupIds),null);

        String tablename = ConvertUtil.getMainTableName(requestId);
        //企微每900人调用一次
        List<List<String>> receiversList = BeanUtil.splitList(receiverList,900);

        receiversList = getDistinctList(receiversList);

        String queryModelSQL = " select t2.departmentname,t.lcbt,t3.workflowname from "+tablename+" t,HRMDEPARTMENT t2,workflow_base t3,workflow_requestbase t4 " +
                " where  t.szbm = t2.id  and t3.id = t4.workflowid and  t4.requestid = t.requestid " +
                " and  t.requestid = ? ";
        bb.writeLog("requestId:"+requestId+" 开始构造企微消息查询流程信息sql:"+queryModelSQL);
        rs.executeQuery(queryModelSQL,new Object[]{requestId});
        if(rs.next()) {
            String title = rs.getString("workflowname")+"待阅通知";
            String context = "请及时看阅"+rs.getString("departmentname")+"发布的\""+ rs.getString("lcbt")+"\"\""+rs.getString("workflowname")+"\"！";
            String linkUrl = null;
            String linkMobileUrl = null;
//            String linkMobileUrl = propBean.getPropName("DocReadMobileUrl"); // 移动端链接

            //查询看阅id 拼接详情地址
            String querySQL = " select id from uf_fxbgky t where t.lcid = ?";
            rs.executeQuery(querySQL, new Object[]{requestId});
            if(rs.next()){
                linkUrl+=rs.getString("id");
//                linkMobileUrl+=rs.getString("id");
            }

            for (List<String> subreceivers : receiversList) {

                MessageType messageType = MessageType.newInstance(Integer.parseInt(linkDocMessageId)); // 消息来源（见文档第四点补充 必填）
                Set<String> userIdList =  new HashSet<>(subreceivers); // 接收人id 必填
                try {
                    bb.writeLog("requestId:"+requestId+" 开始发送消息 title:"+title+" context:"+context+" userIdList:"+userIdList+" linkUrl:"+linkUrl+" linkMobileUrl:"+linkMobileUrl);
                    MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl, linkMobileUrl);
                    messageBean.setCreater(1);// 创建人id
                    Util_Message.store(messageBean);
                    bb.writeLog("requestId:"+requestId+" 推送消息完成 title:"+title+" context:"+context+" userIdList:"+userIdList);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
        return null;
    }

    public List<List<String>> getDistinctList(List<List<String>> receiversList) {
        HashMap<String,String> map = new HashMap<>();
        for (List<String> stringList:receiversList){
            String ids = StringUtils.join(stringList.toArray(),",");
            String sql = "select id,workcode from hrmresource where id in ( "+ids+" )";
            bb.writeLog("风险报告 RiskReportSendReadCmd--getDistinctList 查询人员id和workcode:"+sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                map.put(Util.null2String(rs.getString("workcode")),Util.null2String(rs.getString("id")));
            }
        }
        List<String> valueList =new ArrayList<String>(map.values());
        receiversList = BeanUtil.splitList(valueList,900);
        return receiversList;
    }

    /**
     * 按群组添加文件权限 泛微文件权限不支持群组 只能转换成当时的部门人员快照  后续新增部门人员无权查看文件
     * @param requestId
     * @param currentUser 当前操作人
     * @param docid 文档id
     * @param readerGroupIds 看阅群组id(英文逗号分割)
     * @param allowDownload 是否允许下载
     */
    public void addShareForGroup(String requestId, User currentUser,String docid,String readerGroupIds,boolean allowDownload) {
        readerGroupIds = readerGroupIds.replaceAll(",","','");
        readerGroupIds = "'"+readerGroupIds+"'";
        String queryGroupSQL = " select * from hrmgroup t where t.id in ( "+readerGroupIds+" )";
        DocShareService docShareService = new DocShareService();
        bb.writeLog("requestId:"+requestId+" 按群组添加权限参数先查询群组sql做快照转换:"+queryGroupSQL);
        rs.executeQuery(queryGroupSQL);
        while(rs.next()) {
            String groupId = rs.getString("id");
            String groupName = rs.getString("name");
            String groupType = rs.getString("type");  //0私人组  1公共组
            String groupMappingCode = rs.getString("mappinggroupcode");//rms映射的群组编码

            if ("华泰总部部门".equals(groupName) || "所有分公司".equals(groupName) || "所有营业部".equals(groupName)) {
                String depIds = HRResourceUtil.getDepartmentIdsByGroupName(groupName);
                bb.writeLog("requestid:" + requestId + " 按群组添加权限参数[最后转换成部门]:" + currentUser + "," + Integer.valueOf(docid) + "," + depIds + "," + allowDownload);
                docShareService.addShareForDepartment(currentUser, Integer.valueOf(docid), depIds, 1, 0, 255, false, allowDownload);
                bb.writeLog("requestid:" + requestId + " dt4附件权限 docid:" + docid + " 按群组添加权限[最后转换成部门]完成" + " depIds:" + depIds);
            } else {
                String userIds = HRResourceUtil.getUserIdsByGroupId(groupId);
                bb.writeLog("requestid:" + requestId + " 按群组添加权限参数[最后转换成人员]:" + currentUser + "," + Integer.valueOf(docid) + "," + userIds + "," + allowDownload);
                docShareService.addShareForUser(currentUser, Integer.valueOf(docid), userIds, 1, allowDownload);
                bb.writeLog("风险报告 RiskReportSendReadCmd--requestid:" + requestId + " dt4附件权限 docid:" + docid + " 按人员添加权限[最后转换成人员]完成" + " userIds:" + userIds);
            }
        }
    }


    /**
     * 判断流程是否已完成送阅
     * @param params
     * @return
     */
    public Map<String, Object> checkForm(Map<String, Object> params){
        Map<String, Object> retunData = new HashMap<>();

        try{
            BaseBean bb = new BaseBean();
            Map<String,Object> requestMap = new HashMap<>();
            String requestId = (String)params.get("requestId");
            String sydx = (String)params.get("sydx");//主表单总的送阅对象
            String sybm = (String)params.get("sybm");//送阅部门 隐藏字段
            String syry = (String)params.get("syry");//送阅人员 隐藏字段
            String syjg = (String)params.get("syjg");//送阅机构 隐藏字段
            String syqz = (String)params.get("syqz");//送阅群组 隐藏字段
            requestMap.put("requestId",requestId);
            requestMap.put("sydx",sydx);
            requestMap.put("sybm",sybm);
            requestMap.put("syry",syry);
            requestMap.put("syjg",syjg);
            requestMap.put("syqz",syqz);

            String checkMsg = "";
            Map<String, Object> allSendInfos = getHasSendRead(requestMap);
            if(allSendInfos==null||allSendInfos.get("needSendReadList")==null||((List)allSendInfos.get("needSendReadList")).size()<=0) {
                checkMsg = "所有对象均送阅完成";
                bb.writeLog("公司发文 送阅对象检查checkFormFlex requestId:"+requestId+" chackMsg:"+checkMsg);
            }else {
                List<Map<String, Object>> needSendReadList = (List)allSendInfos.get("needSendReadList");
                for(Map<String,Object> needSendObject : needSendReadList) {
                    if("user".equals((String)needSendObject.get("DataType"))) {
                        checkMsg = checkMsg+needSendObject.get("lastname")+",";
                    }else if ("dept".equals((String)needSendObject.get("DataType"))){
                        checkMsg = checkMsg+needSendObject.get("departmentname")+",";
                    }else if ("org".equals((String)needSendObject.get("DataType"))) {
                        checkMsg = checkMsg+needSendObject.get("departmentname")+",";
                    }else if ("group".equals((String)needSendObject.get("DataType"))) {
                        checkMsg = checkMsg+needSendObject.get("name")+",";
                    }
                }
                checkMsg = checkMsg.substring(0,checkMsg.length()-1);
            }


            retunData.put("status", "1");
            retunData.put("checkMsg",checkMsg);

        }catch (Exception ex){
            ex.printStackTrace();
            retunData.put("status", "-1");
            retunData.put("errMsg", ex.toString());

        }
        return retunData;
    }


    /**
     * 更新看阅记录
     * @param user
     * @param billid
     * @return
     */
    public Map<String, Object> updateKanyueState(User user, String billid){
        Map<String, Object> retunData = new HashMap<>();
        BaseBean bb = new BaseBean();

        try{
            if(user==null){
                retunData.put("flag","0");
            }
            int userid = user.getUID();

            int flag = 0;
            String sql = " select * from uf_fxbgky_dt5 where ry="+userid+" and mainid="+billid;
            bb.writeLog("sql:"+sql);
            rs.execute(sql);
            if(rs.next()){
                flag++;
            }
            bb.writeLog("flag:"+flag);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(flag == 0)
            {
                sql = " insert into uf_fxbgky_dt5(mainid,ry,sj) values("+billid+",'"+userid+"','"+sdf.format(new Date())+"')" ;
                bb.writeLog("sql:"+sql);
                boolean bool = rs.execute(sql);
                if(bool){
                    retunData.put("flag","1");
                }else{
                    retunData.put("flag","0");
                }
            }
            retunData.put("status", "1");
        }catch (Exception ex){
            ex.printStackTrace();
            retunData.put("status", "-1");
            retunData.put("errMsg", ex.toString());

        }
        return retunData;
    }


    /**
     * 看阅接口
     * @param user
     * @param num
     * @param type
     * @return
     */
    public Map<String, Object> getKanyueList(User user, int num, String type) {
        Map<String, Object> appdate = new HashMap<String, Object>();

        try{
            List<Map<String,String>> itemList = new ArrayList<Map<String,String>>();
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String workcode = resourceComInfo.getWorkcode(String.valueOf(user.getUID()));
            int total = 0;

            if(!"".equals(workcode))
            {
                PropBean pb = new PropBean();
                String oahost = pb.getPropName("OAHOST");

                String sql =" with a as( " +
                        " select t1.bt,t1.wh, t1.syqz,t1.syjg,t1.szbm,t1.ngr,h.lastname, " +
                        " t1.modedatacreatedate as fbrq,t1.modedatacreatetime as fbsj,t1.id,t1.formmodeid,m.formid, " +
                        " t1.sysyr,to_char(t1.syry) as syry,t1.sybm,t1.oldoaurl,t1.jjcd,t1.lcid, " +
                        " p.workflowname,k.createdate,k.createtime " +
                        " from uf_fxbgky t1 " +
                        " left join modeinfo m on m.id = t1.formmodeid " +
                        " left join hrmresource h on h.id = t1.ngr " +
                        " left join workflow_requestbase k on to_char(k.requestid) = t1.lcid " +
                        " left join workflow_base p on p.id = k.workflowid " +
                        " ), " ;
                int rycount = 0;
                String userids = "" ;
                String hrmwhere = "";
                String deptwhere  = "";
                String jgwhere="";
                String qzwhere="";
                HT_Util ht_util = new HT_Util();
                rs.executeQuery(" select id,departmentid from hrmresource where workcode=? and status = 1 ",workcode);
                while (rs.next())
                {
                    String id = Util.null2String(rs.getString("id"));
                    userids += userids=="" ? id : ","+id;
                    String departmentid = Util.null2String(rs.getString("departmentid"));
                    hrmwhere += hrmwhere =="" ? " instr(','||a1.syry||',',',"+id+",')>0" : " or instr(','||a1.syry||',',',"+id+",')>0";
                    deptwhere += deptwhere == "" ? " instr(','||a1.sybm||',',',"+departmentid+",')>0 " : " or instr(','||a1.sybm||',',',"+departmentid+",')>0 ";

                    String szjgid = ht_util.getszjg(id);
                    if(szjgid!=""){
                        jgwhere += jgwhere == "" ? " instr(','||a1.syjg||',',',"+szjgid+",')>0 " : " or instr(','||a1.syjg||',',',"+szjgid+",')>0 ";
                    }

                    rycount++;
                }


                if(rycount > 0){
                    if(!"".equals(userids))
                    {
                        List<String> listvalue = ht_util.getszqz(userids);
                        if(listvalue != null && listvalue.size()>0)
                        {
                            for (int i=0;i<listvalue.size();i++){
                                String value = listvalue.get(i);
                                if(value!="")
                                {
                                    qzwhere += qzwhere == "" ? " instr(','||a1.syqz||',',',"+value+",')>0 " : " or instr(','||a1.syqz||',',',"+value+",')>0 ";
                                }
                            }
                        }
                    }

                    String userSqls =   "b as( select a1.* " +
                            " from a a1 where a1.sysyr = 1 " +
                            " union all " +
                            " select a1.* from a a1 where " +hrmwhere+
                            " union all " +
                            " select a1.* from a a1 where " +deptwhere;
                    if(jgwhere!=""){
                        userSqls+=" union all " +
                                " select a1.* from a a1 where " +jgwhere;
                    }
                    if(qzwhere!=""){
                        userSqls+=" union all " +
                                " select a1.* from a a1 where " +qzwhere;
                    }
                    userSqls = userSqls +")" ;
                    sql = sql + userSqls ;

                    String sql_px = "" ;
                    if("0".equals(type))
                    {
                        sql_px =  " select w.* from (select distinct p.* from b p where exists(select 1 from uf_fxbgky_dt5 l where instr(',"+userids+",',','||l.ry||',')>0 and l.mainid = p.id) ) w order by w.fbrq desc,w.fbsj desc" ;
                    }else{
                        sql_px = " select w.* from (select distinct p.* from  b p where not exists(select 1 from uf_fxbgky_dt5 l where instr(',"+userids+",',','||l.ry||',')>0 and l.mainid = p.id) ) w order by w.fbrq desc,w.fbsj desc" ;
                    }

                    String countsql = sql + " select count(1) as total from ("+sql_px+") k ";
                    rs.execute(countsql);
                    if(rs.next()){
                        total = Util.getIntValue(rs.getString("total"));
                    }

                    String where = "";
                    if(num>=0 )
                    {
                        where  = " where rownum>=0 and rownum <"+num;
                    }

                    sql = sql + " select k.* from ("+sql_px+") k "+where;
                    System.out.println("sql:"+sql);
                    rs.execute(sql);

                    Map<String,String> itemMap = null;
                    while(rs.next())
                    {
                        String bt = Util.null2String(rs.getString("bt"));
                        String wh = Util.null2String(rs.getString("wh"));
                        String lastname = Util.null2String(rs.getString("lastname"));

                        String id = Util.null2String(rs.getString("id"));
                        String formmodeid = Util.null2String(rs.getString("formmodeid"));
                        String formid = Util.null2String(rs.getString("formid"));
                        String createdate = Util.null2String(rs.getString("fbrq"));
                        String createtime = Util.null2String(rs.getString("fbsj"));
                        String oldoaurl = Util.null2String(rs.getString("oldoaurl"));
                        String workflowname = Util.null2String(rs.getString("workflowname"));
                        String jjcd = Util.null2String(rs.getString("jjcd"));
                        String priority = "";
                        if("0".equals(jjcd)){
                            priority = "一般";
                        }else if("1".equals(jjcd)){
                            priority = "紧急";
                        }else if("2".equals(jjcd)){
                            priority = "特急";
                        }

                        itemMap = new HashMap<String,String>();
                        itemMap.put("action","");
                        itemMap.put("createDate",createdate);
                        itemMap.put("createTime",createtime);
                        itemMap.put("createrName",lastname);
                        itemMap.put("effective","");
                        itemMap.put("fromSystem","htmoa");
                        itemMap.put("priority",priority);
                        itemMap.put("referencenumber",wh);
                        itemMap.put("title",bt);
                        itemMap.put("type",workflowname);

                        itemMap.put("url",oahost+"spa/cube/index.html#/main/cube/card?type=0&modeId="+formmodeid+"&formId="+formid+"&billid="+id);
                        itemList.add(itemMap);
                    }
                }
            }

            appdate.put("dataList",itemList);
            appdate.put("success","true");
            appdate.put("moreurl","");

            appdate.put("userCode","");
            appdate.put("userName","");
            appdate.put("num",total);

        }catch (Exception e){
            bb.writeLog("e-1:"+e);
        }
        return appdate;
    }


    /**
     * 看阅页面收藏
     * @param user
     * @param billid
     * @param isCancelCollect
     * @return
     */
    public Map<String, Object> collect(User user, String billid, Integer isCancelCollect){
        Map<String, Object> retunData = new HashMap<>();
        RecordSetTrans rst = new RecordSetTrans();

        try{
            rst.setAutoCommit(false);
            String datetime = TimeUtil.getCurrentTimeString();
            int uid = user.getUID();//人员id
            //1.插入数据前删除该条数据
            String deleteData = "delete from uf_fxbgky_dt6 where ry = ? and mainid = ?";
            rst.executeUpdate(deleteData,uid,billid);
            //2.根据isCancelCollect更新数据
            String insert_sql = "";
            if (isCancelCollect == 0){ //是
                insert_sql = "insert into uf_fxbgky_dt6(mainid,ry,sfqxsc,qxsj) values(?,?,?,?)";
            }else {
                insert_sql = "insert into uf_fxbgky_dt6(mainid,ry,sfqxsc,scsj) values(?,?,?,?)";
            }
            rst.executeUpdate(insert_sql,new Object[]{billid,uid,isCancelCollect,datetime});
            bb.writeLog("获取sql语句"+insert_sql);
            retunData.put("status",1);
            retunData.put("msg","success");
            rst.commit();

            //同步门户收藏
            ResourceComInfo rc = new ResourceComInfo();
            String workcode = rc.getWorkcode(String.valueOf(uid));
            new SyncFavoriteThread(workcode,String.valueOf(billid),isCancelCollect).start();
        }catch (Exception ex){
            ex.printStackTrace();
            retunData.put("status", "-1");
            retunData.put("errMsg", ex.toString());

        }
        return retunData;
    }


    /**
     * 批量取消收藏
     * @param user
     * @param billids
     * @return
     */
    public Map<String, Object> batchCancelCollect(User user, String billids){
        Map<String, Object> retunData = new HashMap<>();
        RecordSetTrans rst = new RecordSetTrans();

        try{
            String datetime = TimeUtil.getCurrentTimeString();
            int uid = user.getUID();//人员id
            String updateSql = "update uf_fxbgky_dt6 set sfqxsc = 0,ry = ?,qxsj = ? where mainid in ("+billids+")";
            bb.writeLog("获取sql语句"+updateSql);
            rst.executeUpdate(updateSql,uid,datetime);
            retunData.put("status",1);
            retunData.put("msg","success");

            ResourceComInfo rc = new ResourceComInfo();
            String workcode = rc.getWorkcode(String.valueOf(uid));
            new SyncFavoriteThread(workcode,billids,0).start();
        }catch (Exception ex){
            ex.printStackTrace();
            retunData.put("status", "-1");
            retunData.put("errMsg", ex.toString());

        }
        return retunData;
    }


    /**
     * 看阅页面收藏状态
     * @param user
     * @param billid
     * @return
     */
    public Map<String, Object> getCollectStatus(User user, String billid){
        Map<String, Object> retunData = new HashMap<>();

        try{
            int userid = user.getUID();
            String sql = "select sfqxsc from uf_fxbgky_dt6 where ry = '"+userid+"' and mainid = '"+billid+"'";
            String isCollect = "";
            rs.executeQuery(sql);
            bb.writeLog("sql:"+sql);
            if (rs.next()) {
                isCollect = Util.null2String(rs.getString("sfqxsc"));
            }
            retunData.put("isCollect",isCollect);
            retunData.put("status", "1");
        }catch (Exception ex){
            ex.printStackTrace();
            retunData.put("status", "-1");
            retunData.put("errMsg", ex.toString());

        }
        return retunData;
    }

    /**
     * @title getDeptHistoryName
     * @author K1810015
     * @updateTime 2022/4/11 15:18
     * @Remark 风险合规看阅
     * @throws
     */
    public String getDeptHistoryName(String tablename,String requestid) {
        String value = "";
        if (StringUtils.isBlank(tablename) || StringUtils.isBlank(requestid)) {
            return value;
        }
        RecordSet rs = new RecordSet();
        try {
            String deptid="";
            String fieldid="";
            String sql = "select szbm from "+tablename+ " where requestid=?";
            bb.writeLog("看阅获取所在部门："+sql);
            rs.executeQuery(sql,requestid);
            if(rs.getCounts()<=0){
                return value;
            }
            if(rs.next()){
                deptid=Util.null2String(rs.getString("szbm"));
            }
            if(StringUtils.isBlank(deptid)){
                return  value;
            }
            sql="  select id from workflow_billfield where fieldname='szbm' and billid  in ( " +
                    "    select t.formid as formid   from workflow_base t inner join workflow_requestbase l on l.workflowid = t.id    where l.requestid="+requestid+"    )";
            bb.writeLog("看阅获取所在部门field："+sql);
            rs.execute(sql);
            if(rs.next()){
                fieldid=Util.null2String(rs.getString("id"));
            }
            if(StringUtils.isBlank(fieldid)){
                return  value;
            }
            value= WorkflowUtil.getWfHistoryDeptName(requestid,fieldid,deptid);
            if(StringUtils.isBlank(value)){
                value= getdeptname(deptid);
            }
        }catch (Exception e){

        }
        return value;
    }


    public String getdeptname(String deptid){
        try {
            String value = "";
            if (StringUtils.isBlank(deptid)) {
                return value;
            }
            String sql = "select departmentname from hrmdepartment where id=?";
            rs.executeQuery(sql, deptid);
            if (rs.getCounts() <= 0) {
                return value;
            }
            if (rs.next()) {
                value = Util.null2String(rs.getString("departmentname"));
            }
            return value;
        }catch (Exception e){
            return "";
        }
    }

}
