package emailhelper

import (
	"errors"
	"fmt"
	"go-admin/config"
	"go-admin/pkg/utility"
	"regexp"
	"sync"

	log "github.com/go-admin-team/go-admin-core/logger"
	"github.com/mailjet/mailjet-apiv3-go"
	"go.uber.org/zap"

	"gopkg.in/gomail.v2"
)

var (
	cacheEmail = make(map[string]*gomail.Dialer)
	mu         = sync.RWMutex{}
)

// getGoMailIn 邮件连接池
func getGoMailIn(key string) *gomail.Dialer {
	mu.RLock()
	defer mu.RUnlock()

	item, ok := cacheEmail[key]
	if ok {
		return item
	}

	return nil
}

// CheckIsEmail 检测是否是邮箱
func CheckIsEmail(email string) bool {
	if email == `` {
		return false
	}
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` // 匹配电子邮箱
	reg := regexp.MustCompile(pattern)

	return reg.MatchString(email)
}

// SendFrontedEmail 发送邮件
func SendFrontedEmail(toEmail string, code string, subject, body string) error {
	// 邮箱配置
	from := config.ExtConfig.EmailConfig.MailFrom         // 发送者邮箱
	password := config.ExtConfig.EmailConfig.MailSmtpPass // Gmail 密码或应用专用密码
	to := toEmail                                         // 收件人邮箱
	smtpHost := config.ExtConfig.EmailConfig.MailSmtpHost // Gmail SMTP 服务器
	smtpPort := config.ExtConfig.EmailConfig.MailSmtpPort // SMTP 端口

	m := gomail.NewMessage()
	m.SetHeader("From", from)       // 发件人
	m.SetHeader("To", to)           // 收件人
	m.SetHeader("Subject", subject) // 邮件主题
	m.SetBody("text/html", body)    // 邮件内容（纯文本）

	// 设置 SMTP 服务器信息
	d := gomail.NewDialer(smtpHost, utility.StringToInt(smtpPort), from, password)

	// 发送邮件
	if err := d.DialAndSend(m); err != nil {
		log.Error("发送邮件失败: %v", err)
		return err
	}
	return nil
}

// SendNoticeEmail 发送通知邮件
func SendNoticeEmail(toEmail string, chain string, symbol string, pair string) error {
	// 邮箱配置
	from := config.ExtConfig.EmailConfig.MailFrom         // 发送者邮箱
	password := config.ExtConfig.EmailConfig.MailSmtpPass // Gmail 密码或应用专用密码
	to := toEmail                                         // 收件人邮箱
	smtpHost := config.ExtConfig.EmailConfig.MailSmtpHost // Gmail SMTP 服务器
	smtpPort := config.ExtConfig.EmailConfig.MailSmtpPort // SMTP 端口

	//from = "daichaodsy@163.com"
	//password = "QCKTZWTREARMGDZN"
	//smtpPort = "465"
	//smtpHost = "smtp.163.com"
	//link := fmt.Sprintf("%s/verify?email=%s&verify_code=%s&type=register", config.ExtConfig.Domain, toEmail, code)
	// 创建邮件消息
	subject := "新币发布通知"
	body := fmt.Sprintf("<h1>代币发布</h1><p> 区块链信息: %s <p> 交易对: %s </p> <p> 合约地址: %s </p> </p>", chain, symbol, pair)

	m := gomail.NewMessage()
	m.SetHeader("From", from)       // 发件人
	m.SetHeader("To", to)           // 收件人
	m.SetHeader("Subject", subject) // 邮件主题
	m.SetBody("text/html", body)    // 邮件内容（纯文本）

	// 设置 SMTP 服务器信息
	d := gomail.NewDialer(smtpHost, utility.StringToInt(smtpPort), from, password)

	// 发送邮件
	if err := d.DialAndSend(m); err != nil {
		log.Error("发送邮件失败: %v", err)
		return err
	}
	return nil
}

// SendEmail 发送邮件
//func SendEmail(send config.EmailSend) (string, bool) {
//	m := gomail.NewMessage()
//	m.SetHeader("From", m.FormatAddress(send.From, send.Username)) // 这里等软件名字定下来以后使用多语言配置具体名称
//	m.SetHeader("To", send.To)                                     // "bob@example.com", "cora@example.com")
//	// m.SetAddressHeader("Cc", "dan@example.com", "Dan")
//	m.SetHeader("Subject", send.Subject)
//	m.SetBody("text/html", send.Content) // "Hello <b>Bob</b> and <i>Cora</i>!")
//	// m.Attach("/home/Alex/lolcat.jpg")
//	key := send.Server + send.From
//	gmailClient := getGoMailIn(key)
//	if gmailClient == nil {
//		mu.Lock()
//		d := gomail.NewDialer(send.Server, send.Port, send.From, send.Secret)
//		d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
//		cacheEmail[key] = d
//		mu.Unlock()
//		gmailClient = d
//	}
//
//	// Send the email to Bob, Cora and Dan.
//	if err := gmailClient.DialAndSend(m); err != nil {
//		log.Error("d.DialAndSend", zap.Error(err))
//		return "发送失败", false
//	}
//
//	return "", true
//}

var (
	apiKeyPublic  = "00d2889da90d5d90767bf04dc1bdc6fa"
	apiKeyPrivate = "f68cd84cd88b7e2aabce79c878a77e97"
)

func MailJetSend(receive string, code string) error {
	mailjetClient := mailjet.NewMailjetClient(apiKeyPublic, apiKeyPrivate) //"00d2889da90d5d90767bf04dc1bdc6fa", "f68cd84cd88b7e2aabce79c878a77e97")
	messagesInfo := []mailjet.InfoMessagesV31{
		{
			From: &mailjet.RecipientV31{
				Email: "email@tokex.shop",
				Name:  "Tokex",
			},
			To: &mailjet.RecipientsV31{
				mailjet.RecipientV31{
					Email: receive,
					Name:  "",
				},
			},
			Subject:  "【Tokex】邮箱验证码",
			TextPart: "您的邮箱验证码为：" + code,
			// HTMLPart: "<h3>欢迎注册登录我们的服务，您的验证码为：1234567</h3><br />May the delivery force be with you!",
			// CustomID: "AppGettingStartedTest",
			// TemplateID: 1234,
		},
	}
	messages := mailjet.MessagesV31{Info: messagesInfo}
	res, err := mailjetClient.SendMailV31(&messages)
	if err != nil {
		log.Error("MailJetSend", zap.Error(err))
		return err
	}

	// fmt.Printf("Data: %+v\n", res)
	if res.ResultsV31[0].Status != "success" {
		log.Error("发送失败", zap.Any("resilt", res))
		return errors.New("发送失败")
	}

	return nil
}

func MailJetSendMsg(receive string, subject, textPart string) error {
	mailjetClient := mailjet.NewMailjetClient(apiKeyPublic, apiKeyPrivate) //"00d2889da90d5d90767bf04dc1bdc6fa", "f68cd84cd88b7e2aabce79c878a77e97")
	messagesInfo := []mailjet.InfoMessagesV31{
		{
			From: &mailjet.RecipientV31{
				Email: "email@tokex.shop",
				Name:  "Tokex",
			},
			To: &mailjet.RecipientsV31{
				mailjet.RecipientV31{
					Email: receive,
					Name:  "",
				},
			},
			Subject:  subject,
			TextPart: textPart,
		},
	}
	messages := mailjet.MessagesV31{Info: messagesInfo}
	res, err := mailjetClient.SendMailV31(&messages)
	if err != nil {
		log.Error("MailJetSend", zap.Error(err))
		return err
	}

	// fmt.Printf("Data: %+v\n", res)
	if res.ResultsV31[0].Status != "success" {
		log.Error("发送失败", zap.Any("resilt", res))
		return errors.New("发送失败")
	}

	return nil
}
