package notice

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"net/smtp"
	"net/url"
	"strings"
)

func SendEmailBySMTP(user, host, port, pass, subject, email, content string, html bool) error {
	auth := smtp.PlainAuth("", user, pass, host)

	contentType := "Content-Type:text/plain;charset=UTF-8"
	if html {
		contentType = "Content-Type:text/html;charset=UTF-8"
	}

	msg := []byte("To: " + email + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + content)

	to := strings.Split(email, ";")

	return smtp.SendMail(strings.Join([]string{host, port}, ":"), auth, user, to, msg)
}

func SendEmailBySendCloud(uri, apiUser, apiKey, from, fromName, subject, email, content string, html bool) error {
	params := url.Values{
		"apiUser":  strings.Split(apiUser, ";"),
		"apiKey":   strings.Split(apiKey, ";"),
		"from":     strings.Split(from, ";"),
		"fromName": strings.Split(fromName, ";"),
		"to":       strings.Split(email, ";"), //to此时为地址列表
		"subject":  []string{subject},
	}

	if html {
		params["html"] = []string{content}
	} else {
		params["plain"] = []string{content}
	}

	postBody := bytes.NewBufferString(params.Encode())
	respHandle, err := http.Post(uri, "application/x-www-form-urlencoded", postBody)
	if err != nil {
		return err
	}
	defer respHandle.Body.Close()

	bodyByte, err := ioutil.ReadAll(respHandle.Body)
	if err != nil {
		return err
	}

	// 返回数据格式
	//{
	//	"result": true,
	//	"statusCode": 200,
	//	"message": "请求成功",
	//	"info": {
	//		"emailIdList": ["1530103894330_100557_12907_2084.sc-10_9_63_161-inbound0$15135172753@163.com"]
	//	}
	//}
	resp := &struct {
		Result     bool   `json:"result"`
		StatusCode int    `json:"statusCode"`
		Message    string `json:"message"`
		Info       struct {
			EmailIdList []string `json:"emailIdList"`
		} `json:"info"`
	}{}

	if err := json.Unmarshal(bodyByte, resp); err != nil {
		return err
	}

	if resp.Result == true && resp.StatusCode == http.StatusOK {
		return nil
	} else {
		return errors.New(" email send failed.")
	}
}
