package weaver.interfaces.htsc.workflow.odoc;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StopWatch;
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.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.util.UploadDocUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.wps.doccenter.convert.DocTypeConvert;
import weaver.wps.doccenter.impl.ConvertDocToOfd;
import weaver.wps.doccenter.utils.Tools;
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.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipInputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 公司发文规章制度正文 定稿节点后 doc转pdf 并
 * 写入权限到看阅页面
 * 12/06
 */
public class DocConvertToPdfAction extends BaseBean implements Action {

    private Log log = LogFactory.getLog(this.getClass());
    private String tablename; //主表名
    private Integer id; //流程主键
    private String gzzdzw; //规章制度正文字段
    private String gzzdzwpdf; //规章制度正文pdf字段
    private String gzzdzwofd; //规章制度正文ofd字段
    private String requestid; //requestid
    private User user;
    private BaseBean bb = new BaseBean();

    @Override
    public String execute(RequestInfo requestInfo) {
        RecordSet rs = new RecordSet();
        try {
            tablename = requestInfo.getRequestManager().getBillTableName();
            user = requestInfo.getRequestManager().getUser();
            String detail = tablename+"_dt4";
            requestid = requestInfo.getRequestid();
            log.info("DocConvertToPdfAction开始执行:"+requestid);
            List<String> gzzdzwpdfList = new ArrayList<>();//规章制度正文pdf集合
            List<String> gzzdzwofdList = new ArrayList<>();//规章制度正文ofd集合


            //1.获取gzzdzw字段信息
            rs.executeQuery("select id,gzzdzw,gzzdzwpdf,gzzdzwofd from "+tablename+" where requestid = ?",requestid);
            rs.next();
            id = Util.getIntValue(rs.getString("id"));
            gzzdzw = Util.null2String(rs.getString("gzzdzw"));
            gzzdzwpdf = Util.null2String(rs.getString("gzzdzwpdf"));
            gzzdzwofd = Util.null2String(rs.getString("gzzdzwofd"));

            //2.多次执行删除明细表4脏数据
            if (StringUtils.isNotBlank(gzzdzwpdf)){
                String[] split = gzzdzwpdf.split(",");
                String[] split1 = gzzdzwofd.split(",");
                String[] both = ArrayUtils.addAll(split, split1);
                //Arrays.toString(需去中括号)
                for (String docidforPdf : both) {
                    rs.executeUpdate("delete from "+detail+" where wdid = ?",docidforPdf);
                }
            }

            if (StringUtils.isNotBlank(gzzdzw)){
                String[] splitArray = gzzdzw.split(",");
                for (String oldDocid : splitArray){
                    log.info("oldDocid:"+oldDocid);
                    Map<String,String> paramPdf = new HashMap<>();
                    Map<String,String> paramOfd = new HashMap<>();

                    paramPdf.put("old_docid",oldDocid);
                    paramOfd.put("old_docid",oldDocid);
                    //3.调用wps接口完成原文件的清稿和转pdf功能
                    //4.调用文档中台接口完成原文件清稿和转ofd功能
                    paramPdf.put("type","0");
                    paramOfd.put("type","1");
                    //调用线程完成
                    Callable pdfCallable = () -> generateFile(paramPdf);

                    ExecutorService executorService = Executors.newCachedThreadPool();
                    FutureTask futureTask = new FutureTask(
                            pdfCallable);

                    StopWatch sw = new StopWatch("接口调用耗时分析");
                    sw.start("pdf耗时");
                    executorService.submit(futureTask);
                    sw.stop();
                    log.info("接口调用耗时汇总" + sw.prettyPrint());


                    //获取返回结果
                    String pdf_docid = (String) futureTask.get();
                    log.info("返回结果 pdf_docid:"+pdf_docid);

                    gzzdzwpdfList.add(pdf_docid);

                }

                //5.更新主表规章制度正文pdf和ofd字段
                String newGzzdzwpdf = StringUtils.join(gzzdzwpdfList, ",");
                String newGzzdzwofd = StringUtils.join(gzzdzwofdList, ",");
                rs.executeUpdate("update "+tablename+" set gzzdzwpdf = ?," +
                        "gzzdzwofd = ? where requestid = ?",new Object[]{newGzzdzwpdf,newGzzdzwofd,requestid});
            }

        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent("DocConvertToPdfAction执行失败");
        }
        return Action.SUCCESS;
    }

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

        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();
                log.info("gateway statusCode:"+statusCode);
                if(statusCode == 200)
                {
                    String res = EntityUtils.toString(clresponse.getEntity());
                    log.info("gateway result:"+res);
                    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();
            }
        }
    }

    /**
     * 文件生成及目录关联
     * @param params
     * @return
     */
    public String generateFile(Map<String,String> params){
        Integer newdocid = null;
        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();

        try {
            Integer old_imagefileid = null;
            String old_imagefilename = "";
            String detail = tablename+"_dt4";
            int old_docid = Integer.parseInt(params.get("old_docid"));
            String type = params.get("type"); //0是转pdf 1是转ofd
            rs.executeQuery("select a.IMAGEFILEID,a.IMAGEFILENAME,b.VERSIONID from IMAGEFILE a ,DOCIMAGEFILE b where\n" +
                    "a.IMAGEFILEID = b.IMAGEFILEID and b.DOCID = ? order by VERSIONID desc",old_docid);
            if (rs.next()) {
                old_imagefileid = Util.getIntValue(rs.getString("IMAGEFILEID"));
                old_imagefilename = Util.null2String(rs.getString("IMAGEFILENAME"));
            }
            bb.writeLog("generateFile docid:"+old_docid+" imagefileid:" +old_imagefileid+ " imagefilename:"+old_imagefilename);
            bb.writeLog("type:"+type);

            Integer imagefileid = null;

            if (!"0".equals(type)) {
                ConvertDocToOfd convertDocToOfd = new ConvertDocToOfd();
                imagefileid = convertDocToOfd.convertToOfd(old_imagefileid, old_imagefilename, false);
                this.bb.writeLog("ofd imagefileid:" + imagefileid);
            }else {
                String old_imagefilenamepdf = (!Tools.isEmptyOrNull(old_imagefilename) && old_imagefilename.contains(".") ? old_imagefilename.substring(0, old_imagefilename.lastIndexOf(".")) : old_imagefilename) + ".pdf";
                HashMap pdfmap = new HashMap();
                pdfmap.put("imagefileid", old_imagefileid + "");
                pdfmap.put("fromMould", "ecology");
                pdfmap.put("fileName", old_imagefilename);
                pdfmap.put("targetFileFormat", "PDF");
                pdfmap.put("targetFilename", old_imagefilenamepdf);
                DocTypeConvert docTypeConvert = new DocTypeConvert(this.user);
                imagefileid = docTypeConvert.convertDocType(pdfmap);
                bb.writeLog("pdf imagefileid:" + imagefileid);
            }



            int maincategory = -1;
            int subcategory = -1;
            int seccategory = -1;
            String docextendname = "" ;
            String imagefilename = "";
            String docfiletype = "2"; // 附件
            String doccreaterid ="";
            String doctype = "";
            String filerealpath = "";
            String iszip = "";

            rs.executeQuery("select imagefilename,imagefiletype,filesize,filerealpath,iszip from ImageFile where imagefileid = ?",imagefileid);
            if(rs.next()){
                imagefilename = Util.null2String(rs.getString("imagefilename"));
                docextendname = imagefilename.substring(imagefilename.lastIndexOf(".") + 1);
                filerealpath = Util.null2String(rs.getString("filerealpath"));
                iszip = Util.null2String(rs.getString("iszip"));
            }

            rs.executeQuery("select maincategory,subcategory,seccategory,doccreaterid,doctype from docdetail " +
                    " where id=?",old_docid);
            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"));
                doctype = Util.null2String(rs.getString("doctype"));
            }

            //1.docdetail生成数据
            String content = "";
            String pubtime = TimeUtil.getCurrentDateString();
            String operatetime = TimeUtil.getOnlyCurrentTimeString();
            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,operateuserid,operatedate,operatetime)"+
                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
            rst.executeUpdate(sql,new Object[]{dm.getNextDocImageFileId(),newdocid,imagefileid,imagefilename,
                    0,0,1,0,docfiletype,versionid,doccreaterid,pubtime,operatetime});

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

            //3.插入流程明细表4数据
            String detail_four_sql = "insert into "+detail+" (mainid,wdid,fjid,bt,yxck,yxxz,sflzlc,zwfj,sfyy,lcgd,sfgzzdzw) " +
                    " select  "+id+","+newdocid+","+imagefileid+",'"+imagefilename+"',yxck,yxxz,sflzlc,zwfj,sfyy,lcgd,"+1+" from "+detail+" where wdid = "+old_docid+"";
            log.info("批量插入sql明细表4=="+detail_four_sql);
            rst.executeUpdate(detail_four_sql);

            rst.commit();

            //4.上传网关
            callbackgateway(imagefileid,imagefilename,filerealpath,iszip);

        }catch (Exception e) {
            rst.rollback();
            e.getMessage();
            e.printStackTrace();
        }
        return String.valueOf(newdocid);
    }
}

