package com.engine.htsc.riskReport.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.VersionIdUpdate;
import weaver.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.util.UploadDocUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.wps.officed.AcceptRevision;
import weaver.wps.officed.ConvertToPdf;

import javax.ws.rs.WebApplicationException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

public class RiskReportService extends Service {

    /**
     * 获得强制送阅部门
     * @return
     */
    public Map<String,Object> getDefaultDept(){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();
        String ecologyContentPath = GCONST.getContextPath();
        try {
            JSONArray specialobj = new JSONArray();

            DepartmentComInfo departInfo = new DepartmentComInfo();
            String sybmstr = "";//送阅部门
            String sql = "select id from hrmdepartment where departmentcode = 'ZZ323310'";//风险管理部
            rs.executeQuery(sql);
            if(rs.next()){
                sybmstr = Util.null2String(rs.getString("id"));
            }

            List<String> valueList = new ArrayList<>();
            String[] children = new String[0];

            //1.部门
            if (!"".equals(sybmstr)) {
                JSONObject deptJson = new JSONObject();
                //送阅读部门拆分
                String[] sybmarr = sybmstr.split(",");
                for(String sybm : sybmarr) {
                    String sybmname = departInfo.getDepartmentName(sybm);//送阅部门名称
                    String repalceSql = "select h.id,h.lastname,h.workcode,h.pinyinlastname," +
                            " h.subcompanyid1,t.supdepid from hrmresource h,hrmdepartment t " +
                            " where h.departmentid=t.id and h.departmentid='" + sybm + "' " +
                            " and h.status <= 3 order by h.dsporder";
                    rs.executeQuery(repalceSql);
                    JSONArray users = new JSONArray();
                    String ids = "";
                    String subcompanyid1 = "";
                    String supdepid = "";
                    while (rs.next()) {
                        String[] displayKeys = {"lastnamespan", "workcodespan", "departmentidspan", "jobtitlespan"};
                        String id = Util.null2String(rs.getString("id"));
                        valueList.add(id);
                        String lastname = Util.null2String(rs.getString("lastname"));
                        String workcode = Util.null2String(rs.getString("workcode"));
                        subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
                        String pinyinlastname = Util.null2String(rs.getString("pinyinlastname"));
                        supdepid = Util.null2String(rs.getString("supdepid"));
                        ids += ids == "" ? id + "" : "," + id;
                        JSONObject userJson = new JSONObject();
                        userJson.put("departmentid", sybm);
                        userJson.put("departmentidspan", sybm);
                        userJson.put("departmentname", sybm);
                        userJson.put("displayKeys", displayKeys);
                        userJson.put("icon", ecologyContentPath+"/messager/usericon/" + workcode + "/" + workcode + ".jpg");
                        userJson.put("id", id);
                        userJson.put("jobtitlename", getJob(id));
                        userJson.put("jobtitlespan", getJob(id));
                        userJson.put("lastname", lastname);
                        userJson.put("lastnamespan", lastname);
                        userJson.put("nodeid", "resource_" + id + "x");
                        userJson.put("pinyinlastname", pinyinlastname);
                        userJson.put("subcompanyid", subcompanyid1);
                        userJson.put("subcompanyname", "华泰集团");
                        userJson.put("supsubcompanyid", "0");
                        userJson.put("supsubcompanyname", "");
                        userJson.put("type", "resource");
                        userJson.put("workcodespan", workcode);
                        users.add(userJson);
                    }
                    deptJson.put("children", children);
                    deptJson.put("crmNames", "");
                    deptJson.put("icon", "/images/treeimages/subCopany_Colse_wev8.gif");
                    deptJson.put("id", sybm);
                    deptJson.put("isLeaf", false);
                    deptJson.put("isParent", "true");
                    deptJson.put("lastname", sybmname);
                    deptJson.put("name", sybmname);
                    deptJson.put("nocheck", "Y");
                    deptJson.put("nodeid", "dept_" + sybm + "x");
                    deptJson.put("treeKey", "wea0-com_1x-subcom_" + subcompanyid1 + "x-dept_" + supdepid + "x-dept_" + sybm + "x");
                    deptJson.put("type", "dept");
                    deptJson.put("users", users);
                    specialobj.add(deptJson);
                }
            }

            String value = StringUtils.join(valueList, ",");
            resultMap.put("value",value);
            resultMap.put("specialobj", specialobj );
            resultMap.put("api_status",true);
        }catch (Exception e) {
            resultMap.put("api_status",false);
            resultMap.put("api_errormsg", "catch exception : " + e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    public static String getJob(String id) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select s.jobtitlename from hrmresource h,hrmjobtitles s where h.jobtitle =s.id and h.id='" + id + "'" );
        String jobtitlename = "";
        if (rs.next()) {
            jobtitlename = Util.null2String( rs.getString( "jobtitlename" ) );
        }
        return jobtitlename;
    }

    /**
     * 风险报告正文转换为pdf(清稿)
     * @param requestid
     * @return
     */
    public String docConvertToPdf(String requestid) {
        RecordSetTrans rst = new RecordSetTrans();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        try {
            rst.setAutoCommit(false);
            String tablename = JAVATools.getMaintable(requestid);
            String detailTable = tablename+"_dt4";
            bb.writeLog("docConvertToPdf start:"+requestid);

            //1.获取规章制度正文字段及相关权限
            int id = -1;
            String zw = "";
            String zwpdf = "";
            String gzzdzw = "";
            String gzzdzwpdf = "";
            rs.executeQuery("select id,zw,zwpdf,gzzdzw,gzzdzwpdf from "+tablename+" where requestid = ?",requestid);
            if (rs.next()){
                id = Util.getIntValue(rs.getString("id"));
                zw = Util.null2String(rs.getString("zw"));
                zwpdf = Util.null2String(rs.getString("zwpdf"));
                gzzdzw = Util.null2String(rs.getString("gzzdzw"));
                gzzdzwpdf = Util.null2String(rs.getString("gzzdzwpdf"));
            }

            if (StringUtils.isNotEmpty(zw)){
                int newdocid = convertToPdf(zw,detailTable,id);
                bb.writeLog("zw-newdocid:"+newdocid);

                //9.删除明细表4脏数据
                if (StringUtils.isNotEmpty(zwpdf)){
                    rst.executeUpdate("delete from "+detailTable+" where wdid = ?",zwpdf);
                }

                //10.更新主表规章制度正文pdf字段
                rst.executeUpdate("update "+tablename+" set zwpdf = ? where requestid = ?",new Object[]{newdocid,requestid});
            }

            if (StringUtils.isNotEmpty(gzzdzw)){
                List<String> newDocidList = new ArrayList<>();
                for (String oldDocid : gzzdzw.split(",")){
                    int newdocid = convertToPdf(oldDocid,detailTable,id);
                    bb.writeLog("gzzdzw-newdocid:"+newdocid);
                    newDocidList.add(String.valueOf(newdocid));
                }

                //9.删除明细表4脏数据
                if (StringUtils.isNotEmpty(gzzdzwpdf)){
                    for (String docidforPdf:gzzdzwpdf.split(",")) {
                        rst.executeUpdate("delete from "+detailTable+" where wdid = ?",docidforPdf);
                    }
                }

                //10.更新主表规章制度正文pdf字段
                String newGzzdzwpdf = StringUtils.join(newDocidList, ",");
                rst.executeUpdate("update "+tablename+" set gzzdzwpdf = ? where requestid = ?",new Object[]{newGzzdzwpdf,requestid});
            }

            rst.commit();

        }catch (Exception e){
            rst.rollback();
            e.printStackTrace();
        }
        return Action.SUCCESS;
    }

    private int convertToPdf(String oldDocid, String detailTable, int id){
        RecordSetTrans rst = new RecordSetTrans();
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        try{
            //2.根据原docid获取imagefileid
            rs.executeQuery("select imagefileid,imagefilename from docimagefile where" +
                    " docid = ? and versionid = (select max(versionid) from docimagefile where docid = ?)",new Object[]{oldDocid,oldDocid});
            int oldImageFileid = -1;
            String oldImagefilename = "";
            if (rs.next()){
                oldImageFileid = Util.getIntValue(rs.getString("imagefileid"));
                oldImagefilename = Util.null2String(rs.getString("imagefilename"));
            }
            bb.writeLog("原文件docid:"+oldDocid+";原文件imagefileid:"+oldImageFileid+";名称"+oldImagefilename);

            String fileTyle=oldImagefilename.substring(oldImagefilename.lastIndexOf(".")+1,oldImagefilename.length());
            Map<String,Object> paramsMap=new HashMap<>();
            paramsMap.put("doctype",fileTyle);
            //正文imagefileId
            paramsMap.put("imagefileId",oldImageFileid);
            paramsMap.put("fileName",oldImagefilename);
            //套红前取消痕迹
            AcceptRevision acceptRevision=new AcceptRevision();
            int newimagefileid= Util.getIntValue(acceptRevision.acceptRevisions(paramsMap));
            bb.writeLog("文档中心清稿newImagefileid:"+newimagefileid);

            //3.调用wps接口完成原文件的清稿和转pdf功能
            ConvertToPdf convertToPdf = new ConvertToPdf();
            int newImageFileid = convertToPdf.getDownloadPDFUrl(newimagefileid,oldImagefilename, false);
            bb.writeLog("转完pdf后新imagefileid:"+newImageFileid);

            //4.根据新imagefileid 关联docdetail docimageFile表
            int maincategory = -1;
            int subcategory = -1;
            int seccategory = -1;
            String docextendname = "pdf" ;
            String imagefilename = "";
            String docfiletype = "5";
            String doccreaterid ="";
            String doctype = "1";
            String filerealpath = "";
            String iszip = "";

            rs.executeQuery("select imagefilename,filerealpath,iszip from ImageFile where imagefileid = ?",newImageFileid);
            if(rs.next()){
                imagefilename = Util.null2String(rs.getString("imagefilename"));
                filerealpath = Util.null2String(rs.getString("filerealpath"));
                iszip = Util.null2String(rs.getString("iszip"));

            }

            rs.executeQuery("select maincategory,subcategory,seccategory,doccreaterid from docdetail where id=?",oldDocid);
            if (rs.next()) {
                maincategory = Util.getIntValue(rs.getString("maincategory"));
                subcategory = Util.getIntValue(rs.getString("subcategory"));
                seccategory = Util.getIntValue(rs.getString("seccategory"));
                doccreaterid = Util.null2String(rs.getString("doccreaterid"));
            }

            //5.docdetail生成数据
            String content = "";
            String pubtime = TimeUtil.getCurrentDateString();
            int newdocid = new UploadDocUtil().createDoc(imagefilename,content,
                    Util.getIntValue(doccreaterid),pubtime,maincategory,subcategory,seccategory,
                    Util.getIntValue(doctype),docextendname,"");
            DocImageManager dm = new DocImageManager();
            VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

            int versionid = versionIdUpdate.getVersionNewId();
            String sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,isextfile,imagefielsize,docfiletype,versionid)"+
                    " values("+dm.getNextDocImageFileId()+","+newdocid+","+newImageFileid+",'"+imagefilename+"','0','0','1','0','"+docfiletype+"',"+versionid+")";
            rst.executeUpdate(sql);

            //6.更新附件个数
            rst.executeUpdate("update docdetail set accessorycount = (select count(1) from DocImageFile where docid = ?) where id = ?",new  Object[]{newdocid,newdocid});

            //7.插入流程明细表4数据
            String detail_four_sql = "insert into "+detailTable+" (mainid,wdid,fjid,bt,yxck,yxxz,sflzlc,zwfj,sfyy,lcgd,sfgzzdzw) " +
                    " select  "+id+","+newdocid+","+newImageFileid+",'"+imagefilename+"',yxck,yxxz,sflzlc,zwfj,sfyy,lcgd,"+1+" from "+detailTable+" where wdid = "+oldDocid+"";
            bb.writeLog("批量插入sql明细表4=="+detail_four_sql);
            rst.executeUpdate(detail_four_sql);

            //8.上传网关
            callbackgateway(newImageFileid,imagefilename,filerealpath,iszip);

            return newdocid;
        }catch (Exception e){
            rst.rollback();
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 上传网关
     * @param imagefileid
     * @param imagefilename
     * @param realfilepath
     */
    private void  callbackgateway(int imagefileid,String imagefilename,String realfilepath,String iszip){

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        CloseableHttpResponse clresponse=null;
        InputStream inputStream = null;
        ZipInputStream zipInputStream = null;
        try{
            String upload = QC969424Util.getPV("upload");
            String systemNo = QC969424Util.getPV("systemNo");
            String url = upload+"/"+systemNo;
            QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();
            if (realfilepath != null && !realfilepath.equals(""))
            {
                File file = new File(realfilepath);
                if(!file.exists())
                {
                    throw  new WebApplicationException(404);
                }
                if (iszip.equals("1")) {
                    zipInputStream = new ZipInputStream(new FileInputStream(file));
                    if (zipInputStream.getNextEntry() != null) {
                        inputStream = new BufferedInputStream(zipInputStream);
                    }
                } else {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                }

                clresponse= qc.doUpload(url,imagefilename,inputStream);
                int statusCode = clresponse.getStatusLine().getStatusCode();
                if(statusCode == 200)
                {
                    String res = EntityUtils.toString(clresponse.getEntity());
                    if(!"".equals(res)){
                        String sql = " update imagefile set fileid=? where imagefileid=?";
                        rs.executeUpdate(sql,new Object[]{res,imagefileid});
                    }
                }
                zipInputStream.close();
                inputStream.close();;
                //释放链接
                clresponse.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream !=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(clresponse !=null){
                    clresponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
