package weaver.interfaces.htsc.gwlc;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.qiyuesuo.sdk.bean.company.Department;
import net.sf.cglib.asm.$ClassWriter;
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.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;

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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WrokflowOATooldSignet {

    /***
     *
     * @param requestid
     * @return
     */
    public String createFwToOldSignet(int requestid, int detailid, User usr)
    {
        if(requestid < 0){
            return "";
        }
        String message = "";
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();


        // response.getWriter().write("createFwToOldSignet");
        DepartmentComInfo departmentComInfo = null;
        try{
            departmentComInfo = new DepartmentComInfo();

            PropBean propBean = new PropBean();
            String launchType = propBean.getPropName("launchType");
            bb.writeLog("<br/>launchType:"+launchType);
            //获取主表名称
            String formTable = getTableByRequestid(requestid);
            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 sql =" select  t.requestname,l.sfcwgz,l.fs,l.gllc,( select operatedate||' '||operatetime from workflow_currentoperator  where id =(select min(id) from workflow_currentoperator  where   requestid = t.requestid ))as datetime,(select workflowname from workflow_base where id=t.workflowid)as workflowname,lcbh,l.yz,l.ngr,h.workcode,h.departmentid,l.szbm,h.jobtitle,k.jobtitlecode,l.zw,l.zwpdf,l.fj,t.requestid,l.wh\n" +
                        " from workflow_requestbase t\n" +
                        " inner join "+formTable+" l on l.requestid = t.requestid\n" +
                        " left join hrmresource h on h.id = l.ngr\n" +
                        " left join hrmjobtitles k on k.id = h.jobtitle\n" +
                        " where t.requestid = " + requestid ;

                bb.writeLog("<br/>sql:"+sql);
                bb.writeLog("<br/>走到了获取主流程的了，主表表单是:"+formTable);
                rs.execute(sql);
                if(rs.next()){

                    String title = Util.null2String(rs.getString("requestname"));
                    String zwpdf = Util.null2String(rs.getString("zwpdf"));
                    String zwvalue = Util.null2String(rs.getString("zw"));
                    String workflowname=Util.null2String(rs.getString("workflowname"));
                    String lcbh = Util.null2String(rs.getString("lcbh"));
                    String drafterUserId = Util.null2String(rs.getString("workcode"));
                    String sourceDraftDate=Util.null2String(rs.getString("datetime"));
                    String submitId=Util.null2String(rs.getString("workcode"));
                    String submitDeptCode=Util.null2String(rs.getString("jobtitlecode"));
                    //String department=  ;
                    if(usr!=null&&usr.getLoginid()!=""){
                        submitId=usr.getLoginid();
                        Department department=new Department();
                        submitDeptCode=departmentComInfo.getDepartmentCode(Util.null2String(usr.getUserDepartment()));
                    }



                    String drafterDeptCode = departmentComInfo.getDepartmentCode(Util.null2String(rs.getString("departmentid")));
                    String drafterJobCode = Util.null2String(rs.getString("jobtitlecode"));
                    String yzidlist=Util.null2String(rs.getString("yz"));
                    String fs="";
                     fs=Util.null2String(rs.getString("fs"));
                    List<String> yzvaluelist=new ArrayList<>();
                    String Otherworkflowlist=Util.null2String(rs.getString("gllc"));
                    String Otherlist="";
                    bb.writeLog("<br/>drafterJobCode:"+drafterJobCode);
                    bb.writeLog("<br/>docList:"+docList.size());

                    String fj = Util.null2String(rs.getString("fj"));

                    if(!"".equals(yzidlist)){
                        bb.writeLog("<br/>开始执行之前！！！！");
                        if(getyzValue(yzidlist).size()>0){
                            bb.writeLog("<br/>开始执行之后！！！！"+getyzValue(yzidlist).size());
                            if(getyzValue(yzidlist).size()>0){
                                yzvaluelist = getyzValue(yzidlist);
                                //   response.getWriter().write("<br/>yzvaluelist:"+yzvaluelist);
                            }

                        }
                    }



                    if(!"".equals(fj))
                    {
                        fileList = getfileList(fj,formTable,detailid,fs);
                    }

                    if (yzidlist.split(",").length>=1&&zwvalue!=""){
                        getdocList(zwvalue,fs,fileList);
                    }

                    bb.writeLog("<br/>测试有没有走到filelist这一步骤");
                    bb.writeLog("<br/>fileList:"+fileList.size());
                    String documentNumber = Util.null2String(rs.getString("wh"));
                    jsonObject.put("title",title);    //标题
                    jsonObject.put("drafterUserId",drafterUserId); //拟稿人工号
                    jsonObject.put("drafterDeptCode",drafterDeptCode); //拟稿人部门编号
                    jsonObject.put("drafterJobCode",drafterJobCode); //拟稿人岗位编号
                    jsonObject.put("submitId",drafterUserId); //提交人工号
                    jsonObject.put("submitDeptCode",submitDeptCode);   //提交岗位编号
                    // jsonObject.put("remark","");
                    jsonObject.put("sourceWorkflowNameCN",workflowname);  //源流程名称(中文)
                    jsonObject.put("sourceWorkflowName","");  //源流程名称(ew)
                //    jsonObject.put("sourceWorkFlowNumber",Util.null2String(requestid)); //源流程实例ID
                    jsonObject.put("sourceWorkFlowNum",lcbh);//源流程编号
                    jsonObject.put("sourceDraftDate",sourceDraftDate);//源流程发起时间
                    jsonObject.put("sourceWorkFlowStatus",1); //源流程办结状态1办结 0启用中
                    jsonObject.put("sourceEnable",1); //源流程是否启用 1：起用，0未起用
                    jsonObject.put("launchType",launchType); //印章来源
                    jsonObject.put("sealnameList",yzvaluelist); //印章选择
                    List<Map<String,String>> listvalue= new ArrayList<Map<String,String>>();

                   if(Otherworkflowlist!="") {
                       Otherworkflowlist = String.valueOf(requestid)+","+Otherworkflowlist;
                   }else{
                       Otherworkflowlist=String.valueOf(requestid);
                   }
                        List<Map<String,String>> listflowlist= getworkflowlist(Otherworkflowlist);
                        if(listflowlist.size()>0) {
                            jsonObject.put("releationWorkFlows",listflowlist);
                        }/*else {
                            // jsonObject.put("releationWorkFlows",listvalue);
                        }*/
                   /* }else{
                        // jsonObject.put("releationWorkFlows",listvalue);
                    }*/

                    jsonObject.put("fileList",fileList); //用印文件
                }


                if(fileList==null||fileList.size()<=0){
                    message="filelistisnull";
                    return message ;
                }
             //   response.getWriter().write("<br/>获取json11文件");
               // response.getWriter().write("<br/>"+jsonObject.toJSONString());
               // message=jsonObject.toJSONString();
                String url = propBean.getPropName("oldoatoWorkflowUrlSigenet");
                bb.writeLog("url:"+url);
                bb.writeLog("jsonObject.toJSONString():"+jsonObject.toJSONString());
                Map<String,String> headMap = new HashMap<String,String>();
                bb.writeLog("<br/>开始发送请求");

             //   url="http://168.61.10.179:7006//HTSC_OA/spring/Yongyindengjidan/autoLaunch";

                message = sendPost(url,jsonObject.toJSONString(),headMap);
                bb.writeLog("<br/>请求结束");
                bb.writeLog("reponse:"+message);
            }
        }catch (Exception e){

        }
        return message;
    }

    /***
     *
     * @return
     */
    public List<Map<String,String>>  getworkflowlist(String requestids) {
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        PropBean propBean = new PropBean();
        Map<String,String> map = null;
        BaseBean bb=new BaseBean();
        bb.writeLog("走到了获取其他附件的地方");
        bb.writeLog("其他附件的主键："+requestids);

        RecordSet rs = new RecordSet();

        String title="";
        String workFlowId="";
        String workFlowNum="";
        String url="";
        url= propBean.getPropName("OAlocalhostvalue");
        String sql =" select * from workflow_requestbase " +
                "where requestid in ("+requestids+")" ;
        bb.writeLog("其他附件的sql："+sql);
        rs.execute(sql);
        if(rs.next()){
            String fileid="";
            String imagefilename="";
            map = new HashMap<String,String>();
            title=Util.null2String(rs.getString("requestname"));
            workFlowId=Util.null2String(rs.getString("requestid"));
            url+=workFlowId;
            map.put("title",title);
            //map.put("workFlowId",workFlowId);
          //  map.put("workFlowNum",workFlowNum);
            map.put("url",url);
            list.add(map);

        }
        return list;
    }

    /***
     *
     * @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 List<String> getyzValue(String id){
        List<String> listvalue=new ArrayList<String>();
        //这一步获取印章内容
        BaseBean bb=new BaseBean();
        bb.writeLog("走到了印章的步骤");
        bb.writeLog("印章的主键id"+id);
        try {
            RecordSet rs = new RecordSet();
            String sql = "select yzmc from uf_yinzhang where id in ("+id+")";
            bb.writeLog("印章的sql："+sql);
           rs.execute(sql);
            bb.writeLog("印章的sql第2次："+sql);
                while (rs.next()){
                    bb.writeLog("印章的sql第三次1："+rs);
                    try{
                        if(rs.getString("yzmc")!=null){
                            bb.writeLog("印章的yzmc字段是否为空："+rs.getString("yzmc"));
                            String imagefilename = Util.null2String(rs.getString("yzmc"));
                            listvalue.add(imagefilename);
                        }

                    }catch (Exception exox){
                        bb.writeLog("印章的问题12"+exox.getMessage());
                    }




                }




        }catch (Exception exo){

        }
        bb.writeLog("印章环节结束！！！！"+listvalue.size());
    return listvalue;

    }


    /***
     *
     * @param
     * @return
     */
    public List<Map<String,String>> getdocList(String zwid,String fs,List<Map<String,String>> list)
    {
       // List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;

        try{
            RecordSet rs = new RecordSet();
            BaseBean bb = new BaseBean();

            PropBean propBean = new PropBean();
            String systemCode = propBean.getPropName("systemCode");
            bb.writeLog("systemCode:"+systemCode);

            if(zwid==""){
                return null;
            }

            //String sql = "select imagefilename,fileid from IMAGEFILE_DOC where docid in("+docid+")";
            String sql=" select dif.imagefilename,idc.fileid from IMAGEFILE_DOC  idc join   DocImageFile dif on idc.imagefileid=dif.imagefileid " +
                    "    where idc. docid='"+zwid+"'  and  rownum=1 " +
                    " order by versionid desc ";
            bb.writeLog("这个是附件的sql:"+sql);
            rs.execute(sql);
            while (rs.next()){
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String fileid = Util.null2String(rs.getString("fileid"));

                map = new HashMap<String,String>();
                map.put("fileId",fileid);
                map.put("fileName",imagefilename);
                map.put("copies",fs);
                map.put("systemCode",systemCode);
                list.add(map);
            }
        }catch (Exception e){

        }
        return list;
    }


    /***
     *
     * @param docid
     * @return
     */
    public List<Map<String,String>> getfileList(String docid,String mainid,int detailid,String fs)
    {
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;

        try{
            RecordSet rs = new RecordSet();
            BaseBean bb = new BaseBean();
            bb.writeLog("这个是附件docid："+docid+"mainid:"+mainid+"detailid:"+detailid
            );
            PropBean propBean = new PropBean();
            String systemCode = propBean.getPropName("systemCode");
            bb.writeLog("systemCode:"+systemCode);

            if(docid==""||mainid==""){
                return null;
            }

            //String sql = "select imagefilename,fileid from IMAGEFILE_DOC where docid in("+docid+")";
            String sql="    select f.imagefilename,d.FILEID from DocImageFile f left join imagefile d on f.imagefileid = d.imagefileid where f.docid in     (  select wdid from "+mainid+"_dt"+detailid +
                    "    where  sfyy=1 and wdid in  ("+docid+"))";
            bb.writeLog("这个是附件的sql:"+sql);
            rs.execute(sql);
            while (rs.next()){
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String fileid = Util.null2String(rs.getString("fileid"));

                map = new HashMap<String,String>();
                map.put("fileId",fileid);
                map.put("fileName",imagefilename);
                map.put("copies",fs);
                map.put("systemCode",systemCode);
                list.add(map);
            }
        }catch (Exception e){

        }
        return list;
    }


    /***
     *
     * @param url
     * @param params
     * @param headsMap
     * @return
     */
    public String sendPost(String url, String params,Map<String,String> headsMap)
    {
        BaseBean bb = new BaseBean();
        String body = "";
        String encoding = "UTF-8";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);


        //设置参数到请求对象中
        StringEntity strEntity = new StringEntity(params,encoding);//解决中文乱码问题
        strEntity.setContentEncoding(encoding);
        strEntity.setContentType("application/json");
        httpPost.setEntity(strEntity);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                bb.writeLog("key:"+key+" value:"+value);
                httpPost.addHeader(key, value);
            });
        }
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            bb.writeLog("sendPost-e:"+e);
            e.printStackTrace();
        }
        return body;
    }


    /****
     *
     * @param url
     * @param param
     */
    public String sendPost(String url,String param) {
        BaseBean bb = new BaseBean();
        bb.writeLog("url:"+url);
        bb.writeLog("param:"+param);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            if (conn.getResponseCode() == 200) {
                BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                String output;
                while ((output = responseBuffer.readLine()) != null) {
                    result += output;
                }
                bb.writeLog("result:"+result);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /***
     *
     * @param jsonObject
     * @return
     */
    public String insertDetail(JSONObject jsonObject){

        return "1";
    }



}
