package weaver.interfaces.htsc.gwlc;

import com.alibaba.fastjson.JSONObject;
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.docs.qc969424.util.QC969424RequestBaseUtil;
import weaver.docs.qc969424.util.QC969424Util;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.hrm.company.DepartmentComInfo;

import javax.ws.rs.WebApplicationException;
import java.io.*;
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;
import java.util.zip.ZipInputStream;

public class WrokflowToOAUtil {

    /***
     *
     * @param requestid
     * @return
     */
    public String createWorkflow2OldOA(int requestid)
    {
        if(requestid < 0){
            return "";
        }
        String message = "";
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        System.out.println("createWorkflow2OldOA");
        DepartmentComInfo departmentComInfo = null;
        ResourceComInfo resourceComInfo = null;
        try{
            departmentComInfo = new DepartmentComInfo();
            resourceComInfo = new ResourceComInfo();

            PropBean propBean = new PropBean();
            String launchType = propBean.getPropName("launchType");
            System.out.println("launchType:"+launchType);
            String managerBadge = propBean.getPropName("gsfw_gzzd_managerBadge");

            String formTable = getTableByRequestid(requestid);
            System.out.println("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 lastname = "" ;
                if(!"".equals(managerBadge)){
                    String sql =" select lastname from hrmresource  \n" +
                            " where workcode='"+managerBadge+"' and belongto is null ";
                    bb.writeLog("sql:"+sql);
                    rs.execute(sql);
                    if(rs.next()){
                        lastname = Util.null2String(rs.getString("lastname"));
                    }
                }

                jsonObject.put("managerBadge",managerBadge);
                jsonObject.put("managerBadge_",lastname);


                String sql =" select t.requestname,l.ngr,h.workcode,h.departmentid,l.szbm,h.jobtitle,k.jobtitlecode,l.zwpdf,l.gzzdzwpdf,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 ;

                System.out.println("sql:"+sql);
                rs.execute(sql);
                if(rs.next()){
                    String title = Util.null2String(rs.getString("requestname"));
                    String drafterUserId = Util.null2String(rs.getString("workcode"));
                    String drafterDeptCode = departmentComInfo.getDepartmentCode(Util.null2String(rs.getString("departmentid")));
                    String drafterJobCode = Util.null2String(rs.getString("jobtitlecode"));
                    System.out.println("drafterJobCode:"+drafterJobCode);
                    String documentNumber = Util.null2String(rs.getString("wh"));
                    String zwpdf = Util.null2String(rs.getString("zwpdf"));
                    String gzzdzwpdf = Util.null2String(rs.getString("gzzdzwpdf"));
                    String fj = Util.null2String(rs.getString("fj"));
                    try{
                        getFile2SG(zwpdf,gzzdzwpdf,fj);
                    }catch (Exception e){

                    }

                    if(!"".equals(zwpdf)){
                        docList = getdocList(zwpdf,gzzdzwpdf,documentNumber);
                    }
                    System.out.println("docList:"+docList.size());

                    if(!"".equals(fj))
                    {
                        fileList = getfileList(fj);
                    }
                    System.out.println("fileList:"+fileList.size());


                    jsonObject.put("title",title);
                    jsonObject.put("drafterUserId",drafterUserId);
                    jsonObject.put("drafterDeptCode",drafterDeptCode);
                    jsonObject.put("drafterJobCode",drafterJobCode);

                    jsonObject.put("docList",docList);
                    jsonObject.put("fileList",fileList);
                    jsonObject.put("documentNumber",documentNumber);
                    jsonObject.put("launchType",launchType);

                    jsonObject.put("sourceWorkFlowNameCN",title);
                    jsonObject.put("sourceDrafterUserId",drafterUserId);
                    jsonObject.put("sourceWorkFlowNumber",requestid);
                }

                System.out.println("jsonObject:"+jsonObject.toJSONString());
                String url = propBean.getPropName("oldoaCreateWorkflowUrl");
                System.out.println("url:"+url);
                Map<String,String> headMap = new HashMap<String,String>();
                message = sendPost(url,jsonObject.toJSONString(),headMap);
                System.out.println("message:"+message);
            }
        }catch (Exception e){
            System.out.println("ecreateWorkflow2OldOA-e:"+e);
        }
        return message;
    }


    /***
     *
     * @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;
    }

    /***
     *
     * @param zwpdf
     * @param gzzdzwpdf
     * @param documentNumber
     * @return
     */
    public List<Map<String,String>> getdocList(String zwpdf,String gzzdzwpdf,String documentNumber)
    {
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;
        try{
            RecordSet rs = new RecordSet();
            BaseBean bb = new BaseBean();
            System.out.println("getdocList:");
            PropBean propBean = new PropBean();
            String systemCode = propBean.getPropName("systemCode");
            System.out.println("systemCode:"+systemCode);

            String sql =" select f.imagefilename,d.fileid from DocImageFile f\n" +
                    " left join imagefile d on f.imagefileid = d.imagefileid\n" +
                    " where f.docid in ("+zwpdf+") and versionid IN(select max(versionid) from DocImageFile where docid in("+zwpdf+") ) " ;

            System.out.println("sql:"+sql);
            rs.execute(sql);
            while (rs.next()){

                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String fileid = Util.null2String(rs.getString("fileid"));

                System.out.println("imagefilename:"+imagefilename);
                System.out.println("fileid:"+fileid);

                String filetype = imagefilename.substring(imagefilename.lastIndexOf(".")+1);
                System.out.println("filetype:"+filetype);
                if("".equals(filetype)){
                    filetype = "pdf";
                }
                System.out.println("filetype:"+filetype);
                String filename = documentNumber+"_正文."+filetype;
                System.out.println("filename:"+filename);

                map = new HashMap<String,String>();
                map.put("fileId",fileid);
                map.put("fileName",filename);
                map.put("systemCode",systemCode);
                list.add(map);
            }
            if(!"".equals(gzzdzwpdf))
            {
                String[] gzzdzwpdfids = gzzdzwpdf.split(",");
                for(int i=0;i<gzzdzwpdfids.length;i++)
                {
                    String gzzdzwpdfid = gzzdzwpdfids[i];
                    sql =   " select f.imagefilename,d.fileid from DocImageFile f\n" +
                            " left join imagefile d on f.imagefileid = d.imagefileid\n" +
                            " where f.docid in("+gzzdzwpdfid+") and versionid IN(select max(versionid) from DocImageFile where docid in("+gzzdzwpdfid+") ) " ;
                    System.out.println("sql:"+sql);
                    rs.execute(sql);
                    while (rs.next()){

                        String imagefilename = Util.null2String(rs.getString("imagefilename"));
                        String fileid = Util.null2String(rs.getString("fileid"));

                        System.out.println("imagefilename:"+imagefilename);
                        System.out.println("fileid:"+fileid);

                        String filename = imagefilename;
                        System.out.println("filename:"+filename);

                        map = new HashMap<String,String>();
                        map.put("fileId",fileid);
                        map.put("fileName",filename);
                        map.put("systemCode",systemCode);
                        list.add(map);
                    }
                }
            }
        }catch (Exception e){
            System.out.println("e:"+e);
        }
        return list;
    }


    /***
     *
     * @param docid
     * @return
     */
    public List<Map<String,String>> getfileList(String docid)
    {

        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");
            System.out.println("systemCode:"+systemCode);

            String sql =" select w.* from ( \n" +
                    " select t.imagefilename,h.fileid,row_number() over(partition by t.docid order by t.versionid desc) as px,t.versionid\n" +
                    " from docimagefile t \n" +
                    " left join imagefile h on h.imagefileid = t.imagefileid\n" +
                    " where t.docid in(" + docid + ") \n" +
                    " ) w where w.px = 1 " ;

            //String sql = "select imagefilename,fileid from IMAGEFILE_DOC where docid in("+docid+")";
            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("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();

        System.out.println("sendPost");
        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) -> {
                System.out.println("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) {
            System.out.println("sendPost-e:"+e);
            e.printStackTrace();
        }
        System.out.println("body:"+body);
        return body;
    }


    /****
     *
     * @param url
     * @param param
     */
    public String sendPost(String url,String param) {
        BaseBean bb = new BaseBean();
        System.out.println("url:"+url);
        System.out.println("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;
                }
                System.out.println("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";
    }


    /***
     *
     * @param zwpdf
     * @param gzzdzwpdf
     */
    public void getFile2SG(String zwpdf,String gzzdzwpdf,String docid)
    {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        try {
            Map<String,Object> map = null;
            String sql =" select f.imagefilename,d.fileid,d.imagefileid,d.filerealpath,d.iszip from DocImageFile f\n" +
                    " left join imagefile d on f.imagefileid = d.imagefileid\n" +
                    " where f.docid in (" + zwpdf + ") and versionid IN(select max(versionid) from DocImageFile where docid in(" + zwpdf + ") ) ";
            System.out.println("sql:" + sql);
            rs.execute(sql);
            while (rs.next()) {
                String fileid = Util.null2String(rs.getString("fileid"));
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String filerealpath = Util.null2String(rs.getString("filerealpath"));
                String iszip = Util.null2String(rs.getString("iszip"));

                if("".equals(fileid)){
                    map = new HashMap<String,Object>();
                    map.put("imagefileid",imagefileid);
                    map.put("imagefilename",imagefilename);
                    map.put("filerealpath",filerealpath);
                    map.put("iszip",iszip);
                    list.add(map);
                }
            }
            System.out.println("list:"+list.size());
            if (!"".equals(gzzdzwpdf))
            {
                String[] gzzdzwpdfids = gzzdzwpdf.split(",");
                for (int i = 0; i < gzzdzwpdfids.length; i++) {
                    String gzzdzwpdfid = gzzdzwpdfids[i];
                    sql = " select f.imagefilename,d.fileid,d.imagefileid,d.filerealpath,d.iszip from DocImageFile f\n" +
                            " left join imagefile d on f.imagefileid = d.imagefileid\n" +
                            " where f.docid in(" + gzzdzwpdfid + ") and versionid IN(select max(versionid) from DocImageFile where docid in(" + gzzdzwpdfid + ") ) ";
                    System.out.println("sql:" + sql);

                    rs.execute(sql);
                    while (rs.next()) {
                        String fileid = Util.null2String(rs.getString("fileid"));
                        String imagefileid = Util.null2String(rs.getString("imagefileid"));
                        String imagefilename = Util.null2String(rs.getString("imagefilename"));
                        String filerealpath = Util.null2String(rs.getString("filerealpath"));
                        String iszip = Util.null2String(rs.getString("iszip"));

                        if("".equals(fileid)){
                            map = new HashMap<String,Object>();
                            map.put("imagefileid",imagefileid);
                            map.put("imagefilename",imagefilename);
                            map.put("filerealpath",filerealpath);
                            map.put("iszip",iszip);
                            list.add(map);
                        }
                    }
                }
            }
            System.out.println("list:"+list.size());
            sql=" select w.* from ( \n" +
                    " select t.imagefilename,h.fileid,h.imagefileid,h.filerealpath,h.iszip,row_number() over(partition by t.docid order by t.versionid desc) as px,t.versionid\n" +
                    " from docimagefile t \n" +
                    " left join imagefile h on h.imagefileid = t.imagefileid\n" +
                    " where t.docid in(" + docid + ") \n" +
                    " ) w where w.px = 1 " ;
            System.out.println("sql3:"+sql);
            rs.execute(sql);
            while (rs.next()){
                String fileid = Util.null2String(rs.getString("fileid"));
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String filerealpath = Util.null2String(rs.getString("filerealpath"));
                String iszip = Util.null2String(rs.getString("iszip"));

                if("".equals(fileid)){
                    map = new HashMap<String,Object>();
                    map.put("imagefileid",imagefileid);
                    map.put("imagefilename",imagefilename);
                    map.put("filerealpath",filerealpath);
                    map.put("iszip",iszip);
                    list.add(map);
                }
            }
        }catch (Exception e){

        }
        System.out.println("list:"+list.size());

        if(list !=null && list.size() > 0)
        {
            for(int i=0;i<list.size();i++)
            {
                Map<String,Object> datamap = list.get(i);
                String imagefileid = Util.null2String(datamap.get("imagefileid")) ;
                String imagefilename = Util.null2String(datamap.get("imagefilename")) ;
                String filerealpath = Util.null2String(datamap.get("filerealpath")) ;
                String iszip = Util.null2String(datamap.get("iszip")) ;
                uploadFile2SG(imagefileid,imagefilename,filerealpath,iszip);
            }
        }
    }

    /***
     *
     */
    public void uploadFile2SG(String imagefileid,String imagefilename,String filerealpath,String iszip){

        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        System.out.println("uploadFile2SG");
        InputStream inputStream = null;
        CloseableHttpResponse clresponse=null;
        try{
            String upload = QC969424Util.getPV("upload");
            String systemNo = QC969424Util.getPV("systemNo");
            String url = upload+"/"+systemNo;
            System.out.println("url:"+url);
            System.out.println("imagefilename:"+imagefilename);
            System.out.println("filerealpath:"+filerealpath);
            QC969424RequestBaseUtil qc = new QC969424RequestBaseUtil();

            File file = new File(filerealpath);
            if(!file.exists())
            {
                throw  new WebApplicationException(404);
            }
            if (iszip.equals("1"))
            {
                ZipInputStream 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);
            System.out.println("clresponse:"+clresponse);

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


    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");
        int requestid = 3638665;
        WrokflowToOAUtil WrokflowToOAUtil = new WrokflowToOAUtil();
        WrokflowToOAUtil.createWorkflow2OldOA(requestid);


    }

}

