package com.qxgmat.help;

import com.alibaba.fastjson.JSONObject;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.third.sendcloud.SendCloudMail;
import com.nuliji.tools.third.sendcloud.SendCloudSms;
import com.qxgmat.data.constants.SessionKey;
import com.qxgmat.dto.SmsSessionDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * Created by GaoJie on 2017/11/3.
 */
@Service
public class MailHelp {
    private static final Logger logger = LoggerFactory.getLogger(MailHelp.class);

    private SendCloudMail mail;

    @Value("${third.sendcloud.from}")
    private String from;
    @Value("${third.sendcloud.fromName}")
    private String fromName;

    @Autowired
    private void getSms(@Value("${third.sendcloud.apiUser}") String apiUser,
                   @Value("${third.sendcloud.apiKey}") String apiKey) {
        this.mail = new SendCloudMail(apiUser, apiKey);
    }

    public boolean sendBaseMail(String email, String subject, String body, Map<String, String> params){
        // 替换模版
        body = replaceBody(body, params);
        SendCloudMail.Response response = mail.sendMail(email, subject, body, from, fromName, null);
        return response.getResult();
    }

    public boolean sendAttachMail(String email, String subject, String body, Map<String, String> params, String filePath){
        // 替换模版
        body = replaceBody(body, params);
        SendCloudMail.Response response = mail.sendMail(email, subject, body, from, fromName, new FileSystemResource(filePath));
        return response.getResult();
    }

    private String replaceBody(String body, Map<String, String> params){
        for(String key :params.keySet()){
            body = body.replaceAll("{"+key+"}", params.get(key));
        }
        return body;
    }
}