package weaver.interfaces.htsc.GlobatTools;

import com.alibaba.fastjson.JSONObject;
import com.api.formmode.cache.ModeComInfo;
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.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

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

/**
 * @author xf
 * @version 1.0.0
 * @ClassName HtSendMail.java
 * @createTime 2021年11月15日 15:00:00
 */
public class HtSendMail {

    public static boolean sendemail(Map<String,Object> map){
        PropBean propBean= new PropBean();
        JSONObject jsonObject = new JSONObject();

        String url = propBean.getPropName("sendMail");
        String fromTo=propBean.getPropName("email.formto");
        String fromUserId=propBean.getPropName("email.fromUserId");
        String fromPWD= propBean.getPropName("email.fromPWD");
        jsonObject.put("from",fromTo);
        jsonObject.put("fromUserId",fromUserId);
        jsonObject.put("fromPWD",fromPWD);
       // String sjrArray= Util.null2String(map.get("sjrArray"));
        String csrArray=Util.null2String(map.get("csrArray"));
        String subject=Util.null2String(map.get("subject"));
        String text=Util.null2String(map.get("text"));
        jsonObject.put("to",map.get("sjrArray"));
        jsonObject.put("cc",csrArray);
        jsonObject.put("subject",subject);
        jsonObject.put("text",text);
        try{

            Map<String,String> token= new HTUtil().getAppHeader();
            Map<String,String> param = new HashMap<String,String>();
            param.put("mailRequest",jsonObject.toJSONString());

            String res = sendPost(url,param,token,"");
            JAVATools.SetCmdwritelog("htemail_res:"+res);
            if(!"".equals(res)){
                JSONObject codeJson = JSONObject.parseObject(res);
                if(codeJson.containsKey("code")){
                    String code = codeJson.getString("code");

                }
            }
        }catch (Exception e){
            JAVATools.SetCmdwritelog("htemail_error",e.getMessage());
            return false;
        }
        return true;
    }

    public static String sendPost(String url,  Map<String,String> params,Map<String,String> headsMap, String imagefileid)
    {

        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);
            }
        }

        if(!"".equals(imagefileid))
        {
            RecordSet rs = new RecordSet();
//            String iszip = "";
//            String imageFileName = "";
//            String fileRealPath = "";

            List<Map<String,String>> list  = new ArrayList<Map<String,String>>();
            Map<String,String> map = null;

            String 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:"+imagefileid);
                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);
            }

            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:"+imagefileid);

                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;
    }



}
