package com.reyun.saas.mob.util;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.reyun.saas.mob.user.dao.ConfigParamMapper;
import com.reyun.saas.mob.user.domain.ConfigParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
public class SendCloudComponent {

    @Resource
    private ConfigParamMapper configParamMapper;

    /**
     * 邮件内容类型
     */
    @Value("${sendCloud.mail.content_type}")
    private String contentType;

    /**
     * 发送人邮箱
     */
    @Value("${sendCloud.mail.fromMail}")
    private String fromMail;

    /**
     * 发送邮件api
     */
    @Value("${sendCloud.mail.url}")
    private String url;

    /**
     * api用户
     */
    @Value("${sendCloud.mail.apiUser}")
    private String apiUser;

    /**
     * api的key
     */
    @Value("${sendCloud.mail.apiKey}")
    private String apiKey;

    /**
     * 是否是线上环境
     */
    @Value("${sendCloud.isPro}")
    private Boolean isPro;


    /**
     * 发送短信api
     */
    @Value("${sendCloud.sms.url}")
    private String smsUrl;

    /**
     * 发送短信用户
     */
    @Value("${sendCloud.sms.smsUser}")
    private String smsUser;

    /**
     * 发送短信秘钥
     */
    @Value("${sendCloud.sms.smsKey}")
    private String smsKey;

    /**
     * 发送短信预警模板
     */
    @Value("${sendCloud.sms.warningModel}")
    private String warningModel;

    private String fromName = "MobDNA";

    public String getWarningModel() {
        return warningModel;
    }

    public void setWarningModel(String warningModel) {
        this.warningModel = warningModel;
    }

    /**
     * 功能描述:复合邮件发送
     *
     * @param ccList           可空-抄送地址.
     * @param bccList          可空-密送地址.
     * @param content          必填-邮件的内容. 邮件格式为 text/html
     * @param subject          必填-标题
     * @param userEmailAddress 必填-收件人地址.
     * @author hanzepeng
     * @date 2021-09-26 从trackingio复制的
     */
    public boolean sendMailReuse(List<String> userEmailAddress, String subject, String content, List<String> ccList, List<String> bccList) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);
        String toEmail;
        String bcc = null;
        String cc = null;

        List<String> testUsersEamil = fillNotProEmail();
        if (testUsersEamil != null) {
            //测试环境  使用默认收件人
            toEmail = StringUtils.collectionToDelimitedString(testUsersEamil, ";");
        } else {
            //线上环境
            toEmail = userEmailAddress == null ? null : StringUtils.collectionToDelimitedString(userEmailAddress, ";");
            bcc = bccList == null ? null : StringUtils.collectionToDelimitedString(bccList, ";");
            cc = ccList == null ? null : StringUtils.collectionToDelimitedString(ccList, ";");
        }
        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER,使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", fromMail));
        params.add(new BasicNameValuePair("fromName", fromName));
        params.add(new BasicNameValuePair("to", toEmail));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));
        if (cc != null && !"".equals(cc)) {
            params.add(new BasicNameValuePair("cc", cc));
        }
        if (bcc != null && !"".equals(bcc)) {
            params.add(new BasicNameValuePair("bcc", bcc));
        }
        boolean success = false;

        httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        // 请求
        HttpResponse response = httpclient.execute(httPost);
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
            // 读取xml文档
            String result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String result1 = jsonObject.getString("result");
            success = Boolean.valueOf(result1);
            if (!success) {
                log.error(result);
                throw new Exception(result);
            }
        } else {
            log.error("邮件发送状态异常:" + toEmail);
            throw new Exception("邮件发送状态异常:" + toEmail);
        }
        httPost.releaseConnection();

        return success;
    }

    /**
     * 功能描述:多两个参数,from发件人邮箱;发件人名字
     *
     * @author hanzepeng
     * @date 2021-09-26
     */
    public boolean sendMailReuse(List<String> userEmailAddress, String subject, String content, List<String> ccList, List<String> bccList, String from, String name) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);

        String toEmail;
        String bcc = null;
        String cc = null;

        List<String> testUsersEamil = fillNotProEmail();
        if (testUsersEamil != null) {
            //测试环境  使用默认收件人
            toEmail = StringUtils.collectionToDelimitedString(testUsersEamil, ";");
        } else {
            //线上环境
            toEmail = userEmailAddress == null ? null : StringUtils.collectionToDelimitedString(userEmailAddress, ";");
            bcc = bccList == null ? null : StringUtils.collectionToDelimitedString(bccList, ";");
            cc = ccList == null ? null : StringUtils.collectionToDelimitedString(ccList, ";");
        }

        from = StringUtils.isEmpty(from) ? fromMail : from;
        name = StringUtils.isEmpty(name) ? fromName : name;

        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER,使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("fromName", name));
        params.add(new BasicNameValuePair("to", toEmail));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));
        if (cc != null && !"".equals(cc)) {
            params.add(new BasicNameValuePair("cc", cc));
        }
        if (bcc != null && !"".equals(bcc)) {
            params.add(new BasicNameValuePair("bcc", bcc));
        }
        boolean success = false;
        httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        // 请求
        HttpResponse response = httpclient.execute(httPost);
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
            // 读取xml文档
            String result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String result1 = jsonObject.getString("result");
            success = Boolean.valueOf(result1);
            if (!success) {
                log.error(result);
                throw new Exception(result);
            }
        } else {
            log.error("邮件发送状态异常:" + toEmail);
            throw new Exception("邮件发送状态异常:" + toEmail);
        }
        httPost.releaseConnection();
        return success;
    }


    private List<String> fillNotProEmail() {

        // 测试环境设置为默认的收件人

        if (isPro) {
            return null;
        }

        Example example = new Example(ConfigParam.class);
        example.and().andEqualTo("keyParam", "not_pro_user_email");
        ConfigParam configParam = configParamMapper.selectOneByExample(example);

        String testEmails = configParam.getValueParam();

        if (StringUtils.isEmpty(testEmails)) {
            testEmails = "hanzepeng@reyun.com";
        }

        List<String> emails = new ArrayList<>();

        if (!StringUtils.isEmpty(testEmails)) {
            emails.addAll(Arrays.asList(testEmails.split(",")));
        }

        // 非线上环境收件人
        return emails;

    }


    /**
     * 功能描述:发送手机短信(模板)
     * @author liyin
     * @date 2019/11/1
     */
    public boolean sendSMS(String phone,String templateId,String vars){
        String signature = DigestUtil.md5Hex(smsKey+"&phone="+phone+"&smsUser="+smsUser+"&templateId="+templateId+"&vars="+vars+"&"+smsKey);
        Map<String, Object> map = new HashMap<>();
        map.put("smsUser",smsUser);
        map.put("templateId",templateId);
        map.put("phone",phone);
        map.put("vars",vars);
        map.put("signature",signature);
        String response = HttpUtil.post("http://www.sendcloud.net/smsapi/send", map);
        JSONObject jsonResponse = JSONObject.parseObject(response);
        String statusCode = jsonResponse.get("statusCode").toString();
        if(statusCode.equals("200")){
            return true;
        }else{
            return false;
        }
    }

}