
package weaver.interfaces.htsc.gwlc;

import com.alibaba.fastjson.JSONObject;
import jxl.read.biff.Record;
import net.qiyuesuo.sdk.bean.company.Department;
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.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.workflow.WorkflowCreateHandler;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.util.UploadDocUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class sendNewSignet {

    /***
     *
     * @param requestid
     * @return
     */
    public boolean createFwToOldSignet(int requestid,int detailid,  String Signetdetailid,String requestname) {
        System.out.println("开始执行自动触发用印登记单");
        boolean flag = false;
        if (requestid < 0) {
            return flag;
        }
        String message = "";
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        WorkflowCreateHandler workflowCreateHandler = new WorkflowCreateHandler();
        UploadDocUtil uploadDocUtil=new UploadDocUtil();
        DepartmentComInfo departmentComInfo = null;
        try {
            departmentComInfo = new DepartmentComInfo();
            PropBean propBean = new PropBean();
            //获取主表名称
            String formTable = getTableByRequestid(requestid);
            String detailtable = formTable + "_dt" + detailid;
            bb.writeLog("<br/>formTable:" + formTable);
            if (!"".equals(formTable)) {
                List<Map<String, String>> docList = new ArrayList<Map<String, String>>();
                List<Map<String, String>> fileList = new ArrayList<Map<String, String>>(); //用印文件选择
                JSONObject jsonObject = new JSONObject();
                String zwpdf = "";
                String fjid = "";
                String yz = "";
                String ngr="";
                String szbm="";
                String szjg="";
                String lxfs="";
                String jjcd="";
                String ngrq="";
                String fs="";
                String newdocid="";
                String newimagefileid="";
                String imagefilename="";
                String realfilepath="";
                String wh="";
                String sql ="";

                String GW_GZZDTYPE=Util.null2String(propBean.getPropName("GW_GZZDTYPE"));
                String gzddnumber=Util.null2String(JAVATools.getmainunnumber(Util.null2String(requestid)));
                if(!"".equals(GW_GZZDTYPE)&&!"".equals(gzddnumber)&&GW_GZZDTYPE.indexOf(gzddnumber)>=0){
                    sql=" select t.wh, t.ngr,t.fs,t.szbm,t.szjg,t.lxfs,t.jjcd,t.ngrq , t.yz, t.zwpdf," +
                            " (select wm_concat_old(wdid) from " + detailtable + "  where sfyy='1' and sflzlc=1   and  mainid=t.id and  (fjpdflx is null or fjpdflx!='1' ) ) as fjid " +
                            " from " + formTable + " t " +
                            " where sfcwgz=0 and requestid='" + requestid + "'";
                }else{
                    sql=" select t.wh, t.ngr,t.fs,t.szbm,t.szjg,t.lxfs,t.jjcd,t.ngrq , t.yz, t.zwpdf," +
                            " (select wm_concat_old(wdid) from " + detailtable + "  where sfyy='1' and sflzlc=1  and  mainid=t.id) as fjid " +
                            " from " + formTable + " t " +
                            " where sfcwgz=0 and requestid='" + requestid + "'";
                }



                bb.writeLog("【自动触发用印单】sql:" + sql);
                bb.writeLog("【自动触发用印单】获取流程主表信息sql，主表表单是:" + formTable);
                System.out.println(sql);
                rs.execute(sql);
                if(rs.getCounts()<=0){
                    return  true;
                }
                if (rs.next()) {
                    yz = Util.null2String(rs.getString("yz"));
                    zwpdf = Util.null2String(rs.getString("zwpdf"));
                    fjid = Util.null2String(rs.getString("fjid"));
                    ngr=Util.null2String(rs.getString("ngr"));
                    szbm=Util.null2String(rs.getString("szbm"));
                    szjg=Util.null2String(rs.getString("szjg"));
                    lxfs=Util.null2String(rs.getString("lxfs"));
                    jjcd=Util.null2String(rs.getString("jjcd"));
                    ngrq=Util.null2String(rs.getString("ngrq"));
                    fs=Util.null2String(rs.getString("fs"));
                    wh=Util.null2String(rs.getString("wh"));
                }

                if(!"".equals(GW_GZZDTYPE)&&!"".equals(gzddnumber)&&GW_GZZDTYPE.indexOf(gzddnumber)>=0)
                {
                    Map<String,String> gzzdparams=new HashMap<>();
                    gzzdparams.put("fj",fjid);
                    gzzdparams.put("detailtable",detailtable);
                    gzzdparams.put("tablename",formTable);
                    gzzdparams.put("requestid",Util.null2String(requestid));

                    fjid=distctgzdffj(gzzdparams);
                }

                    if(!"".equals(zwpdf)){
                    JAVATools.SetCmdwritelog("附件转正文开始","request:"+requestid);
                   Map<String,String> mapzw= uploadDocUtil.zwpdftofupload(zwpdf,wh);
                    newdocid=mapzw.get("newdocid");
                    newimagefileid=mapzw.get("newimagefileid");
                    imagefilename=mapzw.get("imagefilename");
                    realfilepath=mapzw.get("realfilepath");
                }
                String filedistinct = filedistinct(newdocid, fjid);
                if ("".equals(ngr)||"".equals(yz) || "".equals(filedistinct)) {
                    return false;
                }

                User usr=new User(Util.getIntValue(ngr));
                Map<String, String> mapstr = new HashMap<>();
                mapstr.put("yz", yz);
                mapstr.put("yywj", filedistinct);
                mapstr.put("sfsdfq","1");
                mapstr.put("lclxbh","yydjb");
                mapstr.put("ngr",ngr);
                mapstr.put("gllc",Util.null2String(requestid));
                mapstr.put("szbm",szbm);
                mapstr.put("szjg",szjg);
                mapstr.put("lxfs",lxfs);
                mapstr.put("hjcd",jjcd);
                mapstr.put("ngsj",ngrq);
                mapstr.put("lylx",JAVATools.getmainunnumber(Util.null2String(requestid)));
                List<Map<String, String>> detaiMaplist = new ArrayList<>();
                for (String value : filedistinct.split(",")) {
                    Map<String, String> detailmap = new HashMap<>();
                    detailmap.put("wjmc", value);
                    if(value.equals(newdocid)){
                        detailmap.put("sfzw","1");
                    }else{
                        detailmap.put("sfzw","0");
                    }
                    detailmap.put("wjly", "0");
                    detailmap.put("fwdyfs", fs);
                    detailmap.put("wlyyfs", fs);
                    detailmap.put("dsmdy", "1");

                    detaiMaplist.add(detailmap);
                }
                String tgtfw_workflownum = new PropBean().getPropName("yydjd_workflownum");
                String workflowid = getWorkflowid(tgtfw_workflownum);
                String requestName = requestname+"--"+workflowCreateHandler.bulidWorkflowTitle(workflowid, Util.null2String(usr.getUID()));
                requestName= requestName.replace("用印登记单","用印单");
                String yydjdmainrequestid=  workflowCreateHandler.WorkflowCreateByRequestMap(Util.null2String(usr.getUID()), workflowid, requestName, "0", mapstr,Signetdetailid,detaiMaplist);

               String tableunnumber=JAVATools.getmainunnumber(Util.null2String(requestid));
                String yydjd_workflowshow = new PropBean().getPropName("yydjd_workflowshow");
                JAVATools.SetCmdwritelog("用印判断：","tableunnumber:"+tableunnumber+"  yydjd_workflowshow:"+yydjd_workflowshow);
               if(!"".equals(tableunnumber) && !"".equals(yydjd_workflowshow)){
                   if(yydjd_workflowshow.indexOf(tableunnumber)>=0){
                       UpdateflowLInkdSign(formTable,Util.null2String(requestid),yydjdmainrequestid);

                   }
               }
                flag=true;
            }
        } catch (Exception e) {

        }
return  flag;
    }


    public void UpdateflowLInkdSign(String Tablename,String requestid,String yydjdmainrequestid){
        RecordSet rs=new RecordSet();
        String sqlseelct="select gllc from "+Tablename+" where requestid='"+requestid+"'";
       String gllcStr="";
        rs.execute(sqlseelct);
        if(rs.next()){
            gllcStr=Util.null2String(rs.getString("gllc"));
        }
        String sql="";
        if("".equals(gllcStr)){
            sql="update "+Tablename+" set gllc=?  where requestid="+requestid;
        }else{
            sql="update "+Tablename+" set gllc=gllc||','||?  where requestid="+requestid;
        }

      JAVATools.SetCmdwritelog("主表增加当前的用印登记单:"+requestid,sql+"@params:"+yydjdmainrequestid);
        rs.executeQuery(sql,yydjdmainrequestid);
    }


    public String getWorkflowid(String unnumber){
        RecordSet rs = new RecordSet();
        String sql="select id from workflow_base t where t.unnumber='"+unnumber+"'";
        rs.execute(sql);
        String value="";
        if(rs.next()){
            value=Util.null2String(rs.getString("id"));
        }
        return  value;
    }

    public String filedistinct(String a,String b){
        String value="";
        if("".equals(a)&& "".equals(b)){
            return value;
        }
        if("".equals(a)){
            value=b;
        }else if("".equals(b)){
            value=a;
        }else{
            value=a+","+b;
        }
        return value;
    }


    /***
     *
     * @return
     */
    public String getTableByRequestid(int requestid){
        RecordSet rs = new RecordSet();
        String formid = "formtable_main_" ;

        String sql =" select abs(t.formid) as formid \n" +
                " from workflow_base t\n" +
                " inner join workflow_requestbase l on l.workflowid = t.id\n" +
                " where l.requestid="+requestid+"" ;
        rs.execute(sql);
        if(rs.next()){
            formid = formid+Util.getIntValues(rs.getString("formid"));
        }
        return formid;
    }



    public String distctgzdffj(Map<String,String> map){
         UploadDocUtil uploadDocUtil=new UploadDocUtil();
         List<String> list=new ArrayList<>();
         String fj=Util.null2String(map.get("fj"));
         String detailtable=Util.null2String(map.get("detailtable"));
         String tablename=Util.null2String(map.get("tablename"));
         String requestid=Util.null2String(map.get("requestid"));
             if("".equals(fj)){
                return "";
             }
           String sql="select wdid,sfgzzdzw from {0} where  wdid in ({1})  and mainid in (select id from {2} where requestid ={3})";
            sql= MessageFormat.format(sql,detailtable,fj,tablename,requestid);
            JAVATools.SetCmdwritelog("规章制度正文查询"+sql);
            RecordSet rs=new RecordSet();
            rs.executeQuery(sql);
            if(rs.getCounts()<=0){
                return "";
            }
            while(rs.next()){
                String wdid=Util.null2String(rs.getString("wdid"));
                String sfgzzdzw=Util.null2String(rs.getString("sfgzzdzw"));
                if(!"1".equals(sfgzzdzw)){
                    list.add(wdid);
                }else{
                    //将正文类型的附件转为附件类型
                    Map<String,String> mapzw= uploadDocUtil.pdftofupload(wdid);
                    String newid= Util.null2String(mapzw.get("newdocid"));
                    JAVATools.SetCmdwritelog("规章制度文件转化","new"+newid+" old"+wdid);
                    if(!"".equals(newid)){
                        list.add(newid);
                    }
                }
            }
        return  list.stream().distinct().collect(Collectors.joining(","));
    }
}
