package com.engine.htsc.cube.web;

import com.engine.common.util.ServiceUtil;
import com.engine.htsc.cube.service.LookingReadService;
import com.engine.htsc.cube.service.impl.LookingReadServiceImpl;
import com.engine.htsc.cube.task.SyncFavoriteThread;
import com.engine.htsc.doc.cmd.SendReadCmd;
import com.engine.htsc.doc.util.FileUtil;
import com.engine.workflow.util.CommonUtil;
import com.weaver.general.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.docs.docs.util.ConvertToPdfAndEncryptUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.workflow.odoc.FileEncryptionAction2;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestManager;


public class LookingReadAction {

    private  Log log = LogFactory.getLog(this.getClass());
    private LookingReadService getService(HttpServletRequest req, HttpServletResponse resp){
        User user = CommonUtil.getUserByRequest(req, resp);
        return (LookingReadService) ServiceUtil.getService(LookingReadServiceImpl.class,user);
    }

    /**
     * rms加密与原文件关系对应接口
     * @param req
     * @param response
     * @return
     */
    @GET
    @Path("/realtion")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Integer> attachmentRelation(@Context HttpServletRequest req, @Context HttpServletResponse response){
        Integer docId = Util.getIntValue(req.getParameter("docid"));
        Map<String,Integer> attenyionMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        try{
            String attentionSql = "select rmsdocid,rmsimagefileid from uf_rmsjmb where docid = ?";
            rs.executeQuery(attentionSql,new Object[]{docId});
            if (rs.next()){
                Integer rmsdocid = Util.getIntValue(rs.getString("rmsdocid"));
                Integer rmsimagefileid = Util.getIntValue(rs.getString("rmsimagefileid"));
                attenyionMap.put("rmsDocid",rmsdocid);
                attenyionMap.put("rmsimagefileid",rmsimagefileid);
            }
        }catch (Exception e){
            log.info("error request"+docId);
            e.printStackTrace();
        }
        return attenyionMap;
    }

    /**
     * rms加密与正文pdf文件关系对应接口
     * @param req
     * @param response
     * @return
     */
    @GET
    @Path("/docRealtion")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Integer> documentRelation(@Context HttpServletRequest req, @Context HttpServletResponse response){
        Integer docId = Util.getIntValue(req.getParameter("zwpdfdocid"));
        Map<String,Integer> attenyionMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        RecordSet zwRs = new RecordSet();
        try{
            String attentionSql = "select docid,rmsdocid,rmsimagefileid from uf_rmsjmb where zwpdfdocid = ?";
            rs.executeQuery(attentionSql,new Object[]{docId});
            String zwdocid = "";
            if (rs.next()){
                zwdocid = Util.null2String(rs.getString("docid"));
                Integer rmsdocid = Util.getIntValue(rs.getString("rmsdocid"));
                Integer rmsimagefileid = Util.getIntValue(rs.getString("rmsimagefileid"));
                attenyionMap.put("rmsDocid",rmsdocid);
                attenyionMap.put("rmsimagefileid",rmsimagefileid);
            }
            //获取正文imagefileid
            String imagefileidSql = "select imagefileid from docimagefile where docid = ?";
            zwRs.executeQuery(imagefileidSql,zwdocid);
            if (zwRs.next()){
                Integer imagefileid = Util.getIntValue(zwRs.getString("imagefileid"));
                attenyionMap.put("imagefileid",imagefileid);
            }
        }catch (Exception e){
            log.info("error request"+docId);
        }
        return attenyionMap;
    }

    /**
     * 部门发文和党工团发文 rms加密 定稿
     * @param req
     * @param response
     * @return
     */
    @GET
    @Path("/fileEncryption")
    @Produces({MediaType.APPLICATION_JSON})
    public void fileEncryption(@Context HttpServletRequest req, @Context HttpServletResponse response){
        try{
            RecordSet rs = new RecordSet();
            Integer requestid = Util.getIntValue(req.getParameter("requestid"));
            RequestService requestService = new RequestService();
            RequestManager requestManager = new RequestManager();
            String tablename = "formtable_main_";
            String tableSql = "select formid from workflow_base where id = " +
                    "(select workflowid from workflow_requestbase where requestid = "+requestid+")";
            rs.execute(tableSql);
            if (rs.next()){
                int formid = Math.abs(Util.getIntValue(rs.getString("formid")));
                tablename = tablename+formid;
            }
            requestManager.setBilltablename(tablename);
            RequestInfo requestInfo = requestService.getRequest(requestid);
            requestInfo.setRequestManager(requestManager);
            log.info("表名"+requestInfo.getRequestManager().getBillTableName());
            new FileEncryptionAction2().execute(requestInfo);
            log.info("加密成功"+requestid);
        }catch (Exception e){
            log.info("加密失败");
            e.printStackTrace();
        }
    }

    /**
     * 部门发文和党工团发文  定稿后更新建模表zwpdf字段(注意:接口定稿时未调用,接口作废)
     * @param req
     * @param response
     * @return
     */
    @GET
    @Path("/updateDocPdf")
    @Produces({MediaType.APPLICATION_JSON})
    public void updateDocPdf(@Context HttpServletRequest req, @Context HttpServletResponse response){
        try{
            RecordSet rs = new RecordSet();
            String zwpdf_docid = Util.null2String(req.getParameter("zwpdf"));
            String requestid = Util.null2String(req.getParameter("requestid"));
            String sql = "select COUNT(1) as sl from UF_GWKY  where requestid = '"+requestid+"'";
            rs.execute(sql);
            rs.next();
            if(Util.getIntValue(rs.getString("sl"))>0) {
                String updateSql = "update uf_gwky set zwpdf = ? where requestid = ?";
                boolean flag = rs.executeUpdate(updateSql, new Object[]{zwpdf_docid, requestid});
                if (flag) {
                    log.info("建模pdf更新成功");
                    addDocShareInvoke(requestid, zwpdf_docid);

                    //uf_gwky_dt7更新数据
                    uodateDocinfo(requestid,zwpdf_docid);
                }
            }
        }catch (Exception e){
            log.info("建模pdf更新失败");
            e.printStackTrace();
        }
    }

    /**
     *  重新定稿pdf后刷新泛微docshare文档权限
     * @param requestId
     * @param zwpdf_docid
     */
    public void addDocShareInvoke(String requestId, String zwpdf_docid) {
        log.info("requestId:"+requestId+" WPS重新定稿后正文PDF:"+zwpdf_docid+" 开始调用DocShare服务");
        RecordSet rs = new RecordSet();
        String mainTableName = "";
        //根据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});
        if(rs.next()){
            mainTableName = rs.getString("tablename");
            log.info("requestId:"+requestId+" WPS重新定稿后对应的流程表单的表名为:"+mainTableName);
        }
        String querySQL = " select * from uf_gwky t where t.lcid = ? ";
        rs.executeQuery(querySQL, new Object[]{requestId});
        if(rs.next()){
            String syry_db = Util.null2String(rs.getString("syry"));
            String sybm_db = Util.null2String(rs.getString("sybm"));
            String syjg_db = Util.null2String(rs.getString("syjg"));
            String syqz_db = Util.null2String(rs.getString("syqz"));
            log.info("requestId::"+requestId+" WPS重新定稿后获取数据库已送阅权限记录 syry_db:"+syry_db+" sybm_db:"+sybm_db+" syjg_db:"+syjg_db+" syqz_db:"+syqz_db);
            SendReadCmd sendReadCmd = new SendReadCmd();
            sendReadCmd.doSaveShareDoc(mainTableName, "1", syry_db, sybm_db, syqz_db, syjg_db, requestId, null);
            log.info("requestId:"+requestId+" WPS重新定稿后正文PDF:"+zwpdf_docid+" 调用DocShare服务完成");
        }
    }


    /**
     * 部门发文和党工团发文 rms解密 取消定稿 rms附件字段清空
     * @param req
     * @param response
     * @return
     */
    @GET
    @Path("/fileDecryption")
    @Produces({MediaType.APPLICATION_JSON})
    public void fileDecryption(@Context HttpServletRequest req, @Context HttpServletResponse response){
        try{
            RecordSet rs = new RecordSet();
            Integer requestid = Util.getIntValue(req.getParameter("requestid"));
            //RequestService requestService = new RequestService();
            //RequestInfo requestInfo = requestService.getRequest(requestid);
            //String tablename = requestInfo.getRequestManager().getBillTableName();
            //1.清空建模表数据
            String rmsSql = "delete from uf_rmsjmb where requestid = ?";
            boolean flag = rs.executeUpdate(rmsSql, new Object[]{requestid});
            if (flag){
                log.info("rms建模数据删除成功");
            }
            //2.清空主表rms附件字段(每次加密时候会更新)
            log.info("解密成功"+requestid);
        }catch (Exception e) {
            log.info("解密失败");
            e.printStackTrace();
        }
    }

    /**
     * 看阅页面收藏记录
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/collect")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Object> isCancelCollect(@Context HttpServletRequest request,
                                              @Context HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        RecordSetTrans rst = new RecordSetTrans();
        try{
            rst.setAutoCommit(false);
            User user = HrmUserVarify.getUser(request,response);
            String operatedate = TimeUtil.getCurrentDateString();
            String operatetime = TimeUtil.getOnlyCurrentTimeString();
            String datetime = operatedate+" "+operatetime;
            log.info("系统时间"+datetime);
            int uid = user.getUID();//人员id
            Integer billid = Util.getIntValue(request.getParameter("billid"));
            Integer isCancelCollect = Util.getIntValue(request.getParameter("isCancelCollect"));//是否取消收藏，0是1否
            //1.插入数据前删除该条数据
            String deleteData = "delete from uf_gwky_dt6 where ry = ? and mainid = ?";
            rst.executeUpdate(deleteData,uid,billid);
            //2.根据isCancelCollect更新数据
            String insertDatas = "";
            if (isCancelCollect == 0){ //是
                insertDatas = "insert into uf_gwky_dt6(mainid,ry,sfqxsc,qxsj) values(?,?,?,?)";
            }else {
                insertDatas = "insert into uf_gwky_dt6(mainid,ry,sfqxsc,scsj) values(?,?,?,?)";
            }
            rst.executeUpdate(insertDatas,new Object[]{billid,uid,isCancelCollect,datetime});
            log.info("获取sql语句"+insertDatas);
            map.put("status",1);
            map.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 e){
            rst.rollback();
            map.put("status",-1);
            map.put("msg","fail");
            e.printStackTrace();

        }
        return map;
    }

    /**
     * 批量取消收藏
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("batchCancelCollect")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Object> batchCancelCollect(@Context HttpServletRequest request,
                                                 @Context HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        RecordSetTrans rs = new RecordSetTrans();
        try{
            String billids = Util.null2String(request.getParameter("billids"));
            User user = HrmUserVarify.getUser(request,response);
            String operatedate = TimeUtil.getCurrentDateString();
            String operatetime = TimeUtil.getOnlyCurrentTimeString();
            String datetime = operatedate+" "+operatetime;
            log.info("系统时间"+datetime);
            int uid = user.getUID();//人员id
            if ("".equals(billids)){//数据为空时返回
                return map;
            }
            String updateSql = "update uf_gwky_dt6 set sfqxsc = 0,ry = ?,qxsj = ? where mainid in ("+billids+")";
            log.info("获取sql语句"+updateSql);
            rs.executeUpdate(updateSql,uid,datetime);
            map.put("status",1);
            map.put("msg","success");

            ResourceComInfo rc = new ResourceComInfo();
            String workcode = rc.getWorkcode(String.valueOf(uid));
            new SyncFavoriteThread(workcode,billids,0).start();

        }catch (Exception e){
            map.put("status",-1);
            map.put("msg","fail");
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 看阅页面收藏状态
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/getCollectStatus")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Object> collectStatus(@Context HttpServletRequest request,
                                            @Context HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        RecordSet rs = new RecordSet();
        try{
            User user = HrmUserVarify.getUser(request,response);
            int uid = user.getUID();
            Integer billid = Util.getIntValue(request.getParameter("billid"));
            String getCollectStatus = "select sfqxsc from uf_gwky_dt6 where ry = ? and mainid = ?";
            String isCollect = "";
            rs.executeQuery(getCollectStatus,uid,billid);
            if (rs.next()) {
                isCollect = Util.null2String(rs.getString("sfqxsc"));
            }
            map.put("isCollect",isCollect);
            map.put("status",1);
            map.put("msg","success");
        }catch (Exception e){
            map.put("status",-1);
            map.put("msg","fail");
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 公文看阅页面pdf加密
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/encryptPdf")
    @Produces({MediaType.APPLICATION_JSON})
    public Map<String,Object> convertToPdfAndEncrypt(@Context HttpServletRequest request,
                                                     @Context HttpServletResponse response,
                                                     @QueryParam("docid") String docid){
        Map<String,Object> map = new HashMap<>();
        RecordSet rs = new RecordSet();
        RecordSet recordSet = new RecordSet();
        BaseBean bb = new BaseBean();
        try{
            User user = HrmUserVarify.getUser(request,response);
            PropBean pb = new PropBean();
            bb.writeLog("公文看阅pdf下载加密:"+docid);
            String newDocid = "";
            rs.executeQuery("select jmhpdf from uf_gwky where zwpdf = ?",docid);
            if (rs.next()){
                newDocid = Util.null2String(rs.getString("jmhpdf"));
            }
            if (StringUtils.isNotBlank(newDocid) && !"-1".equals(newDocid)){
                bb.infoLog("pdf加密文件已存在:",newDocid);
            }else {
                int directory = Integer.parseInt(pb.getPropName("DIRECTORY"));
                bb.writeLog("DIRECTORY",directory);
                ConvertToPdfAndEncryptUtil convertToPdfAndEncryptUtil = new ConvertToPdfAndEncryptUtil();
                newDocid = convertToPdfAndEncryptUtil.convertPdf(docid, user, directory);
                bb.infoLog("pdf加密:",directory+"--"+newDocid);
                //更新公文看阅表
                recordSet.executeUpdate("update uf_gwky set jmhpdf = ? where zwpdf = ?",newDocid,docid);
            }
            rs.executeQuery("select imagefileid from docimagefile where docid = ?",newDocid);
            if (rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                map.put("imagefileid",imagefileid);
            }

            map.put("newDocid",newDocid);
            map.put("status",1);
            map.put("msg","success");
        }catch (Exception e){
            map.put("status",-1);
            map.put("msg","fail");
            e.printStackTrace();
        }
        return map;
    }

    /**
     *  定稿后执行 将uf_gwky的zwpdf信息更新到uf_gwky_dt7
     * @param requestId
     * @param wjid
     */
    public void uodateDocinfo(String requestId,String wjid) {
        //将uf_gwky的zwpdf信息存入uf_gwky_dt7
        RecordSet rs = new RecordSet();
        com.weaver.general.BaseBean bb = new com.weaver.general.BaseBean();

        String mainId = "";
        String mainIdSQL = " select t.id from uf_gwky t where t.lcid =  '"+requestId+"'";
        rs.executeQuery(mainIdSQL);
        if(rs.next()) {
            mainId = rs.getString("id");
            bb.writeLog("公司发文 insertDocinfo  requestid:"+requestId+" 看阅主记录的序列为:"+mainId);
        }

        String fjid = FileUtil.getFjid(wjid);
        String fileid = FileUtil.getFileid(fjid);
        String batchInsertSQL3 = "update UF_GWKY_DT7 set wjid = ?,fjid = ?, FILEID = ? where  MAINID = ?";

        rs.executeUpdate(batchInsertSQL3,wjid,fjid,fileid,mainId);
        rs.next();
        bb.writeLog("公司发文 insertDocinfo--dt7保存  requestid:"+requestId+"插入建模dt7记录sql打印:"+batchInsertSQL3);
    }



}
