package com.engine.htsc.hthy.cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.formmode.cache.ModeComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.hrm.OrganizationSynUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

public class SendMailByMeetinglCmd extends AbstractCommonCommand<Map<String, Object>> {

    public SendMailByMeetinglCmd(Map<String, Object> params) {
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        BaseBean bb = new BaseBean();
        Map<String, Object> apimap = new HashMap<String, Object>();
        String billid = Util.null2String(params.get("billid"));
        bb.writeLog("billid:"+billid);
        String fromTo  = pb.getPropName("fromTo");
        String fromUserId  = pb.getPropName("fromUserId");
        String fromPWD  = pb.getPropName("fromPWD");
        String sjrx = "" ;
        String csrx = "" ;
        String gdwj = "" ;
        String subject = "" ;
        String text = "" ;
        String ysfj = "" ;
        String sql = " select sjrll,csrll,gdwj,yjbt,yjnr,ysfj from uf_hyyj where id="+billid;
        rs.execute(sql);
        if(rs.next()){
            sjrx = Util.null2String(rs.getString("sjrll"));
            csrx = Util.null2String(rs.getString("csrll"));
            gdwj = Util.null2String(rs.getString("gdwj"));
            subject = Util.null2String(rs.getString("yjbt"));
            text = Util.null2String(rs.getString("yjnr"));
            ysfj = Util.null2String(rs.getString("ysfj"));
        }

        //String sendTo = "yixiaochen@htzq.htsc.com.cn"; //收件人，邮箱地址，多地址时用英文逗号分隔
        //String subject = "OAxinxinx测试邮件99"; //主题，纯文本
        //String content = "OA测试邮件2222"; //内容。纯文本或html字符串。(换行用<br/>)
        //new Thread(new EmailWorkRunnable(sendTo, subject, content)).start();

        JSONArray sjrArray = new JSONArray();
        if(!"".equals(sjrx)){
            String[] sjrData = sjrx.split(",");
            for(int i=0;i<sjrData.length;i++)
            {
                sql = " select id,yx from uf_hyxx where id ="+sjrData[i];
                rs.execute(sql);
                if (rs.next()){
                    String yx = Util.null2String(rs.getString("yx"));
                    if(!sjrArray.contains(yx)){
                        sjrArray.add(yx);
                    }
                }
            }
        }

        JSONArray csrArray = new JSONArray();
        if(!"".equals(csrx)){
            String[] csrData = csrx.split(",");
            for(int i = 0;i<csrData.length;i++){
                sql = " select id,yx from uf_hyxx where id ="+csrData[i];
                rs.execute(sql);
                if (rs.next()){
                    String yx = Util.null2String(rs.getString("yx"));
                    if(!csrArray.contains(yx)){
                        csrArray.add(yx);
                    }
                }
            }
        }

        Map<String,String> headMap = new HashMap<String,String>();

        String token = getToken();
        headMap.put("JTXT-AUTH-TOKEN",token);
        headMap.put("JTXT-AUTH-TYPE","APP");
//        headMap.put("JTXT-AUTH-TOKEN","eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMTM0NzIiLCJBVVRIX1JPTEUiOiJKVFhUX1RSSVBfQURNSU4sSlRYVF9DdHJpcF9BRE1JTixKVFhUX1VTRVIsU1lQUExZX0lORk8sT1JHX0FETUlOLFNZU0FETUlOLERFUF9BRE1JTixERVBfVFJBSU5JTkdfT1JHQU5JWkVSLEdST1VQX01BTkFHRVIiLCJleHAiOjE2Mzg5OTAxMzN9.GVVc35wb7tqx23os21XxTpKq3RBtSQWrhYDFPx939e59LYsO80GrvZKksJ-Qkozfh2mb6QxHOn9BW3jPQhXYwg");
//        headMap.put("JTXT-AUTH-TYPE","USER");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("from",fromTo);
        jsonObject.put("fromUserId",fromUserId);
        jsonObject.put("fromPWD",fromPWD);
        jsonObject.put("to",sjrArray);
        jsonObject.put("cc",csrArray);
        jsonObject.put("subject",subject);
        jsonObject.put("text",text);

        bb.writeLog("jsonObject:"+jsonObject.toJSONString());
        String url = pb.getPropName("sendMail"); //"http://168.61.69.225:8080/jtxt/mail/htsc/send" ;
//        String imagefileids = "" ;
//        if(!"".equals(gdwj))
//        {
//            sql = "select *\n" +
//                    "  from (select t.id,\n" +
//                    "               k.imagefileid,\n" +
//                    "               k.imagefilename,\n" +
//                    "               k.versionid,\n" +
//                    "               row_number() over(partition by docid order by versionid desc) as xh\n" +
//                    "          from docdetail t\n" +
//                    "         inner join docimagefile k on k.docid = t.id\n" +
//                    "         where t.id in("+gdwj+"))\n" +
//                    " where xh = 1 ";
//
//            rs.execute(sql);
//            while (rs.next()){
//                String imagefileid = Util.null2String(rs.getString("imagefileid"));
//                imagefileids += imagefileids==""? imagefileid : ","+imagefileid ;
//            }
//        }


        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        if(!"".equals(gdwj))
        {
            Map<String, String> map = null;
            String[] docids = gdwj.split(",");
            for (int i = 0; i < docids.length; i++)
            {
                List<String> docList = new ArrayList<String>();
                sql = "  select *\n" +
                        "  from (select t.id,\n" +
                        "               k.imagefileid,\n" +
                        "               k.imagefilename,\n" +
                        "               k.versionid,\n" +
                        "               row_number() over(partition by docid order by versionid desc) as xh\n" +
                        "          from docdetail t\n" +
                        "         inner join docimagefile k on k.docid = t.id\n" +
                        "         where t.id in(" + docids[i] + "))\n" +
                        "  where xh = 1 ";

                rs.execute(sql);
                while (rs.next()) {
                    String imagefileid = Util.null2String(rs.getString("imagefileid"));
                    docList.add(imagefileid);
                }
                for (String imagefileid : docList)
                {
                    sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in(" + imagefileid + ")";
                    bb.writeLog(sql);
                    rs.execute(sql);
                    while (rs.next()) {
                        String imageFileName = Util.null2String(rs.getString("realname"));
                        bb.writeLog("imageFileName1:" + imageFileName);
                        if (imageFileName.equals("")) {
                            imageFileName = Util.null2String(rs.getString("imageFileName"));
                        }
                        String fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                        String iszip = Util.null2String(rs.getString("isZip"));

                        map = new HashMap<String, String>();
                        map.put("imageFileName", imageFileName);
                        map.put("fileRealPath", fileRealPath);
                        map.put("iszip", iszip);
                        list.add(map);
                    }
                }
            }
        }

        if(!"".equals(ysfj)){

            Map<String, String> map = null;
            String[] docids = ysfj.split(",");
            for (int i = 0; i < docids.length; i++)
            {
                List<String> docList = new ArrayList<String>();
                sql = "  select *\n" +
                        "  from (select t.id,\n" +
                        "               k.imagefileid,\n" +
                        "               k.imagefilename,\n" +
                        "               k.versionid,\n" +
                        "               row_number() over(partition by docid order by versionid desc) as xh\n" +
                        "          from docdetail t\n" +
                        "         inner join docimagefile k on k.docid = t.id\n" +
                        "         where t.id in(" + docids[i] + "))\n" +
                        "  where xh = 1 ";

                rs.execute(sql);
                while (rs.next()) {
                    String imagefileid = Util.null2String(rs.getString("imagefileid"));
                    docList.add(imagefileid);
                }
                for (String imagefileid : docList)
                {
                    sql = " select t1.imageFileId,t1.imageFileName,t1.imageFileType,t1.imageFileUsed,t1.fileRealPath,t1.isZip,t1.isencrypt,t1.filesize,t1.downloads,t1.miniimgpath,t1.imgsize,t1.isFTP,t1.FTPConfigId,t1.isaesencrypt,t1.aescode,t1.tokenKey,t1.storageStatus,t1.comefrom,t2.imagefilename as realname  from ImageFile t1 left join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.imagefileid in(" + imagefileid + ")";
                    bb.writeLog(sql);
                    rs.execute(sql);
                    while (rs.next()) {
                        String imageFileName = Util.null2String(rs.getString("realname"));
                        bb.writeLog("imageFileName1:" + imageFileName);
                        if (imageFileName.equals("")) {
                            imageFileName = Util.null2String(rs.getString("imageFileName"));
                        }
                        String fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                        String iszip = Util.null2String(rs.getString("isZip"));

                        map = new HashMap<String, String>();
                        map.put("imageFileName", imageFileName);
                        map.put("fileRealPath", fileRealPath);
                        map.put("iszip", iszip);
                        list.add(map);
                    }
                }
            }
        }

        // String msg = sendPost(url,jsonObject.toJSONString(),headMap);
//    Map<String,String> postmap = new HashMap<String,String>();
//    postmap.put("mailRequest",jsonObject.toJSONString());
//    FileItemFactory factory = new DiskFileItemFactory(16, null);
//    FileItem item = factory.createItem("97096409-4917-41ea-8018-cab341f79b0f.zip", "text/plain", true, "97096409-4917-41ea-8018-cab341f79b0f.zip");
//    File newfile = new File("/app/ecology/filesystem/202111/P/97096409-4917-41ea-8018-cab341f79b0f.zip");
//    int bytesRead = 0;
//    byte[] buffer = new byte[8192];
//    try {
//        FileInputStream fis = new FileInputStream(newfile);
//        OutputStream os = item.getOutputStream();
//        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
//            os.write(buffer, 0, bytesRead);
//        }
//        os.close();
//        fis.close();
//    } catch (IOException e) {
//        e.printStackTrace();
//    }

        String code = "0" ;
        Map<String,String> param = new HashMap<String,String>();
        param.put("mailRequest",jsonObject.toJSONString());
        try{
            String res = sendPost(url,param,headMap,list);
            bb.writeLog("res:"+res);
            if(!"".equals(res)){
                JSONObject codeJson = JSONObject.parseObject(res);
                if(codeJson.containsKey("code")){
                    code = codeJson.getString("code");
                    if("1".equals(code)){
                        sql = " update uf_hyyj set sffyj ='0',fssj=to_char(sysdate,'yyyy-mm-dd hh24:mi') where id="+billid;
                        bb.writeLog("sql:"+sql);
                        boolean flag = rs.executeUpdate(sql);
                        if(!flag){
                            code = "-5";
                        }else{
                            ModeComInfo modeCache = new ModeComInfo();
                            modeCache.removeCache();

                        }
                    }
                }
            }

        }catch (Exception e){
            bb.writeLog("e2:"+e);
            code = "-5";
        }

        apimap.put("code",code);
        return apimap;
    }


    /***
     *
     * @param url
     * @param params
     * @param headsMap
     * @param list
     * @return
     */
    public String sendPost(String url,  Map<String,String> params,Map<String,String> headsMap, List<Map<String, String>> list)
    {
        BaseBean bb = new BaseBean();
        JSONObject jsonObject = new JSONObject();
        String result = "" ;
        InputStream inputstream = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        if (headsMap != null && !headsMap.isEmpty()) {  //http的header
            headsMap.forEach((key, value) -> {
                System.out.println("key:"+key+" value:"+value);
                httppost.addHeader(key, value);
            });
        }

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (params != null && !params.isEmpty())  //Text 入参数
        {
            // 编码参数
            for (Map.Entry<String, String> k : params.entrySet())
            {
                ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
                StringBody stringBody = new StringBody(k.getValue(),contentType);
                //StringBody valueBody = new StringBody(k.getValue(),Charset.forName(CHARSET));
                builder.addPart(k.getKey(),stringBody);
            }
        }


        builder.setMode(HttpMultipartMode.RFC6532);
        builder.setCharset(Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);


        if(list !=null && list.size() >0)
        {
            for(int i=0;i<list.size();i++)
            {
                Map<String,String> dataMap = list.get(i);
                String imageFileName = Util.null2String(dataMap.get("imageFileName"));
                String fileRealPath = Util.null2String(dataMap.get("fileRealPath"));
                String iszip = Util.null2String(dataMap.get("iszip"));
                try {
                    if (iszip.equals("1")) {
                        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(fileRealPath));
                        if (zipInputStream.getNextEntry() != null) {
                            inputstream = new BufferedInputStream(zipInputStream);
                        }
                    } else {
                        inputstream = new BufferedInputStream(new FileInputStream(fileRealPath));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                bb.writeLog("imageFileName2:"+imageFileName);

                builder.addBinaryBody(
                        "files",
                        inputstream,
                        ContentType.APPLICATION_OCTET_STREAM,
                        imageFileName
                );
            }
        }


        HttpEntity entity = builder.build();
        httppost.setEntity(entity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                entity = response.getEntity();
                if (entity != null)
                {
                    try {
                        inputstream = entity.getContent();

                        //转换为字节输入流
                        BufferedReader br = new BufferedReader(new InputStreamReader(inputstream, Consts.UTF_8));
                        String body = null;
                        while ((body = br.readLine()) != null)
                        {
                            result += body;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    bb.writeLog("result:"+result);
                    if(!"".equals(result)){
                        jsonObject = JSONObject.parseObject(result);

                    }
                }
            }else{
                jsonObject.put("code","-1");
                jsonObject.put("message","URL请求失败");
                return jsonObject.toJSONString();
            }
            inputstream.close();

        } catch (IOException e) {
            e.printStackTrace();
            jsonObject.put("code","-2");
            jsonObject.put("message","URL请求失败");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code","-3");
            jsonObject.put("message","URL请求失败");

        }finally {
            if(inputstream !=null){
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }



    public static void main(String[] args) {
        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");
        Map<String, Object> params=new HashMap<>();
        params.put("billid","115");

        SendMailByMeetinglCmd ItlxlcLdspInfoCmd = new SendMailByMeetinglCmd(params);
        CommandContext ceshi= new CommandContext(null,null);
        ItlxlcLdspInfoCmd.execute(ceshi);

    }


    public String getToken()
    {
        OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
        String appId = "WEAVER";
        String secretKey = "Admin@123" ;
        String accessToken = "" ;
        PropBean pb = new PropBean();
        String orgToken = pb.getPropName("orgToken");
        String url = orgToken+appId+"/"+secretKey;
        Map<String,String> headsMap = new HashMap<String,String>();
        String str = OrganizationSynUtil.sendPost(url,"",headsMap);
        BaseBean bb = new BaseBean();
        bb.writeLog("str:"+str);
        if(!"".equals(str)){
            JSONObject jsonObject = JSONObject.parseObject(str);
            bb.writeLog("jsonObject:"+jsonObject.toJSONString());
            accessToken = Util.null2String(jsonObject.get("accessToken"));
        }
        return accessToken;
    }

}
