package english_report

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/company"
	"eta/eta_mobile/services"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

// EnglishReportEmailController 英文研报邮箱/英文客户联系人
type EnglishReportEmailController struct {
	controllers.BaseAuthController
}

// List
// @Title 英文研报邮箱列表
// @Description 英文研报邮箱列表
// @Param   CompanyId	query	int		false	"客户ID"
// @Param   Keywords	query	string	false	"关键词:联系人名称/邮箱地址"
// @Param   SortType	query	int		false	"点击量排序方式:1-倒序;2-正序"
// @Param   SortParam	query	int		false	"排序字段:1-点击量;2-点击时间 3-用户状态"
// @Param   ListParam   query   int  	false   "筛选字段参数,用来筛选的字段, 枚举值:1:正式 、 2:临时 、 3:终止 、4:正式+临时 "
// @Success 200 {object} models.EnglishReportEmailPageListResp
// @router /email/list [get]
func (this *EnglishReportEmailController) List() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	companyId, _ := this.GetInt("CompanyId", 0)
	keywords := this.GetString("Keywords", "")
	sortType, _ := this.GetInt("SortType", 1)
	sortParam, _ := this.GetInt("SortParam", 1)
	listParam, _ := this.GetInt("ListParam", 1)

	var cond, order string
	var pars []interface{}
	if companyId > 0 {
		cond += ` AND a.company_id = ?`
		pars = append(pars, companyId)
	}
	if keywords != "" {
		k := "%" + keywords + "%"
		cond += ` AND (a.name LIKE ? OR a.email LIKE ?)`
		pars = append(pars, k, k)
	}

	sortParamArr := []int{1, 2, 3}
	sortTypeArr := []int{1, 2}
	if utils.InArrayByInt(sortParamArr, sortParam) && utils.InArrayByInt(sortTypeArr, sortType) {
		pMap := map[int]string{1: "a.view_total", 2: "a.last_view_time", 3: "a.enabled"}
		tMap := map[int]string{1: "DESC", 2: "ASC"}
		order = fmt.Sprintf(` ORDER BY %s %s`, pMap[sortParam], tMap[sortType])
	}

	if listParam == 1 {
		cond += ` AND a.status = 1`
	}
	if listParam == 2 {
		cond += ` AND a.status = 2`
	}
	if listParam == 3 {
		cond += ` AND a.status = 3`
	}
	if listParam == 4 {
		cond += ` AND (a.status = 1 OR a.status = 2)`
	}
	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, e := models.GetEnglishReportEmailPageList(cond, pars, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取邮箱列表失败, Err: " + e.Error()
		return
	}

	respList := make([]*models.EnglishReportEmailResp, 0)
	for i := range list {
		item := &models.EnglishReportEmailResp{
			Id:                  list[i].Id,
			Name:                list[i].Name,
			Email:               list[i].Email,
			Mobile:              list[i].Mobile,
			CountryCode:         list[i].CountryCode,
			BusinessCardUrl:     list[i].BusinessCardUrl,
			AdminName:           list[i].AdminName,
			CreateTime:          list[i].CreateTime.Format(utils.FormatDateTime),
			ViewTotal:           list[i].ViewTotal,
			Enabled:             list[i].Enabled,
			CompanyName:         list[i].CompanyName,
			RegisterCompanyName: list[i].RegisterCompanyName,
			RegisterTime:        list[i].RegisterTime.Format(utils.FormatDateTime),
		}
		if item.RegisterTime == "0001-01-01 00:00:00" {
			item.RegisterTime = ""
		}
		respList = append(respList, item)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.EnglishReportEmailPageListResp{
		Paging: page,
		List:   respList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Send
// @Title 群发推送
// @Description 群发推送
// @Param	request  body  models.EnglishReportEmailSaveReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /email/send [post]
func (this *EnglishReportEmailController) Send() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req models.EnglishReportEmailSendReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.ReportId <= 0 {
		br.Msg = "请选择报告"
		return
	}
	if req.Theme == "" {
		br.Msg = "请输入邮件主题"
		return
	}
	//prefixTheme := "【HI China Macro and Commodity】"
	//if !strings.Contains(req.Theme, prefixTheme) {
	//	req.Theme = prefixTheme + req.Theme
	//}
	runeThe := []rune(req.Theme)
	if len(runeThe) > 100 {
		br.Msg = "邮件主题不可超过100字符"
		return
	}

	// 获取报告信息
	reportInfo, e := models.GetEnglishReportItemById(req.ReportId)
	if e != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "获取报告信息失败, Err: " + e.Error()
		return
	}
	if reportInfo.EmailState != 0 {
		br.Msg = "请勿重复发送"
		br.ErrMsg = fmt.Sprintf("报告群发邮件状态有误, 当前状态: %d", reportInfo.EmailState)
		return
	}
	if reportInfo.State != 2 {
		br.Msg = "报告未发布"
		br.ErrMsg = fmt.Sprintf("报告状态有误, 当前状态: %d", reportInfo.State)
		return
	}
	if reportInfo.Title == "" {
		br.Msg = "报告标题有误"
		br.ErrMsg = "报告标题为空, 不可推送"
		return
	}
	if reportInfo.Content == `` {
		br.Msg = "报告内容有误"
		br.ErrMsg = "报告内容为空, 不可推送"
		return
	}

	// 获取邮件配置
	conf := new(models.EnglishReportEmailConf)
	authKey := "english_report_email_conf"
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "无权操作"
		br.ErrMsg = "获取群发邮件权限失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "无权操作"
		br.ErrMsg = "群发邮件配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &conf); e != nil {
		br.Msg = "无权操作"
		br.ErrMsg = "群发邮件配置有误"
		return
	}
	authArr := strings.Split(conf.SendAuthGroup, ",")
	if !utils.InArrayByStr(authArr, sysUser.RoleTypeCode) {
		br.Msg = "无权操作"
		return
	}

	// 指定品种的客户
	sendCompanyIds := make([]int, 0)
	if len(req.EnPermissions) > 0 {
		companyIds, e := models.GetEnglishCompanyIdsByEnPermissionIds(req.EnPermissions)
		if e != nil {
			br.Msg = "推送失败"
			br.ErrMsg = "获取指定品种的客户IDs失败, Err: " + e.Error()
			return
		}
		sendCompanyIds = companyIds
	}
	// 指定收件人列表
	sendEmailIds := make([]int, 0)
	if req.EmailIds != "" {
		emailIdArr := strings.Split(req.EmailIds, ",")
		if len(emailIdArr) == 0 {
			br.Msg = "指定收件人列表有误"
			br.ErrMsg = fmt.Sprintf("收件人列表为空, 收件人IDs: %s", req.EmailIds)
			return
		}
		for _, m := range emailIdArr {
			v, _ := strconv.Atoi(m)
			sendEmailIds = append(sendEmailIds, v)
		}
	}
	if len(sendCompanyIds) == 0 && len(sendEmailIds) == 0 {
		br.Msg = "收件人列表为空(或收件人账号被禁用)"
		br.ErrMsg = "收件人列表为空, 不可推送"
		return
	}
	emailCond := " AND enabled = 1 AND status <> 3"
	emailPars := make([]interface{}, 0)
	if len(sendCompanyIds) > 0 && len(sendEmailIds) > 0 {
		emailCond += ` AND (company_id IN (` + utils.GetOrmInReplace(len(sendCompanyIds)) + `) OR id IN (` + utils.GetOrmInReplace(len(sendEmailIds)) + `))`
		emailPars = append(emailPars, sendCompanyIds)
		emailPars = append(emailPars, sendEmailIds)
	}
	if len(sendCompanyIds) > 0 && len(sendEmailIds) == 0 {
		emailCond += ` AND company_id IN (` + utils.GetOrmInReplace(len(sendCompanyIds)) + `)`
		emailPars = append(emailPars, sendCompanyIds)
	}
	if len(sendCompanyIds) == 0 && len(sendEmailIds) > 0 {
		emailCond += ` AND id IN (` + utils.GetOrmInReplace(len(sendEmailIds)) + `)`
		emailPars = append(emailPars, sendEmailIds)
	}

	emails, e := models.GetEnglishReportEmailList(emailCond, emailPars, "")
	if e != nil {
		br.Msg = "获取收件人列表失败"
		br.ErrMsg = "获取收件人列表失败, Err: " + e.Error()
		return
	}
	if len(emails) == 0 {
		br.Msg = "收件人列表为空(或收件人账号被禁用)"
		br.ErrMsg = "收件人列表为空, 不可推送"
		return
	}

	// 获取模板
	confKey := "english_report_email_tmp"
	confTmp, e := company.GetConfigDetailByCode(confKey)
	if e != nil {
		br.Msg = "获取邮件模板失败"
		br.ErrMsg = "获取邮件模板失败, Err: " + e.Error()
		return
	}
	if confTmp.ConfigValue == `` {
		br.Msg = "邮件模板有误"
		br.ErrMsg = "邮件模板为空, 不可推送"
		return
	}

	// 同一篇报告避免重复推送给同一个邮件
	var cond string
	var pars []interface{}
	cond += ` AND report_id = ? AND send_status = 1 AND report_type = 0`
	pars = append(pars, req.ReportId)
	logs, e := models.GetEnglishReportEmailLogList(cond, pars)
	if e != nil {
		br.Msg = "推送失败"
		br.ErrMsg = "获取邮件发送日志列表失败, Err: " + e.Error()
		return
	}
	repeatMap := make(map[int]bool, 0)
	for i := range logs {
		if logs[i].SendStatus == 1 {
			repeatMap[logs[i].EmailId] = true
		}
	}

	// 推送信息
	nowTime := time.Now().Local()
	sendData := make([]*services.EnglishReportSendEmailRequest, 0)
	logData := make([]*models.EnglishReportEmailLog, 0)
	for i := range emails {
		if repeatMap[emails[i].Id] {
			continue
		}

		r := new(services.EnglishReportSendEmailRequest)
		r.ReportId = reportInfo.Id
		r.EmailId = emails[i].Id
		r.Email = strings.Replace(emails[i].Email, " ", "", -1)
		r.Subject = req.Theme
		r.FromAlias = conf.FromAlias

		// 获取报告Overview部分
		if reportInfo.Overview == "" {
			br.Msg = "报告Overview部分不可为空"
			return
		}
		overview := reportInfo.Overview

		// 填充模板
		t := reportInfo.PublishTime.Format("02/01/2006")
		l := fmt.Sprintf(utils.EnglishShareUrl+"/report/detail?code=%s", reportInfo.ReportCode)
		ct := confTmp.ConfigValue
		ct = strings.Replace(ct, "{{REPORT_TITLE}}", reportInfo.Title, 1)
		ct = strings.Replace(ct, "{{REPORT_ABSTRACT}}", reportInfo.Abstract, 1)
		ct = strings.Replace(ct, "{{REPORT_CONTENT}}", overview, 1)
		ct = strings.Replace(ct, "{{REPORT_SHARE_LINK}}", l, 1)
		ct = strings.Replace(ct, "{{REPORT_TIME}}", t, 1)
		r.HtmlBody = ct
		r.ReportTitle = reportInfo.Title
		r.ReportAbstract = reportInfo.Abstract
		r.ReportContent = overview
		r.ReportShareLink = l
		r.ReportTime = t
		sendData = append(sendData, r)

		// 日志
		logData = append(logData, &models.EnglishReportEmailLog{
			ReportId:   reportInfo.Id,
			EmailId:    emails[i].Id,
			Email:      emails[i].Email,
			Source:     models.EnglishReportEmailLogSourceAli,
			SendStatus: models.EnglishReportEmailLogStatusIng,
			CreateTime: nowTime,
		})
	}
	if len(sendData) == 0 {
		br.Msg = "无邮件可推送"
		return
	}

	// 写入日志
	emailLog := new(models.EnglishReportEmailLog)
	if e = emailLog.InsertMulti(logData); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "批量写入群发邮件日志失败, Err: " + e.Error()
		return
	}

	// 修改推送状态
	updateCols := []string{"EmailState", "ModifyTime"}
	reportInfo.EmailState = 1
	reportInfo.ModifyTime = time.Now().Local()
	if e = reportInfo.Update(updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新推送状态失败, Err: " + e.Error()
		return
	}

	// 群发邮件
	go func() {
		services.BatchSendAliEnglishReportEmail(sendData)
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// LogList
// @Title 邮件群发日志列表
// @Description 邮件群发日志列表
// @Param   ReportId  query  int  true  "报告ID"
// @Param   ReportType  query  int  true  "类型:0英文研报,1英文线上路演"
// @Param   SendStatus  query  int  false  "发送状态:-1-已发送;0-发送失败;1-发送成功"
// @Param   Keywords	query	string	false	"关键词:邮箱"
// @Success 200 {object} models.EnglishReportEmailLogPageListResp
// @router /email/log_list [get]
func (this *EnglishReportEmailController) LogList() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	reportId, _ := this.GetInt("ReportId", 0)
	if reportId <= 0 {
		br.Msg = "参数有误"
		return
	}

	reportType, _ := this.GetInt("ReportType", 0)
	keywords := this.GetString("Keywords", "")

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var cond string
	var pars []interface{}
	cond += ` AND report_id = ? AND report_type = ?`
	pars = append(pars, reportId, reportType)
	// 推送状态
	status := this.GetString("SendStatus", "")
	if status != "" {
		statusInt, e := strconv.Atoi(status)
		if e != nil {
			br.Msg = "状态类型有误"
			return
		}
		cond += ` AND send_status = ?`
		pars = append(pars, statusInt)
	}
	// 关键词
	if keywords != "" {
		k := fmt.Sprint("%", keywords, "%")
		cond += ` AND email LIKE ? `
		pars = append(pars, k)
	}

	total, list, e := models.GetEnglishReportEmailLogPageList(cond, pars, "", startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取邮箱列表失败, Err: " + e.Error()
		return
	}

	respList := make([]*models.EnglishReportEmailLogPageList, 0)
	for i := range list {
		v := new(models.EnglishReportEmailLogPageList)
		// 推送结果
		v.ResultMsg = "发送成功"
		if list[i].ErrMsg != "" {
			v.ResultMsg = list[i].ErrMsg
		}
		v.SendId = list[i].Id
		v.ReportId = list[i].ReportId
		v.EmailId = list[i].EmailId
		v.Email = list[i].Email
		v.SendStatus = list[i].SendStatus
		v.Source = list[i].Source
		v.CreateTime = list[i].CreateTime.Format(utils.FormatDateTime)
		respList = append(respList, v)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.EnglishReportEmailLogPageListResp{
		Paging: page,
		List:   respList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Resend
// @Title 重新推送
// @Description 群发推送
// @Param	request  body  models.EnglishReportEmailResendReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /email/resend [post]
func (this *EnglishReportEmailController) Resend() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req models.EnglishReportEmailResendReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.ReportId <= 0 {
		br.Msg = "请选择报告"
		return
	}

	// 获取报告信息
	reportInfo, e := models.GetEnglishReportItemById(req.ReportId)
	if e != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "获取报告信息失败, Err: " + e.Error()
		return
	}
	if reportInfo.State != 2 {
		br.Msg = "报告未发布"
		br.ErrMsg = fmt.Sprintf("报告状态有误, 当前状态: %d", reportInfo.State)
		return
	}
	if reportInfo.Title == "" {
		br.Msg = "报告标题有误"
		br.ErrMsg = "报告标题为空, 不可推送"
		return
	}
	if reportInfo.Content == `` {
		br.Msg = "报告内容有误"
		br.ErrMsg = "报告内容为空, 不可推送"
		return
	}
	if reportInfo.Abstract == `` {
		br.Msg = "报告摘要为空"
		br.ErrMsg = "报告摘要为空, 不可推送"
		return
	}
	if reportInfo.Overview == "" {
		br.Msg = "报告Overview部分不可为空"
		br.ErrMsg = "报告Overview为空, 不可推送"
		return
	}
	// 重新发送超过100字符直接截取
	theme := reportInfo.Abstract
	runeAbs := []rune(reportInfo.Abstract)
	runeThe := make([]rune, 0)
	if len(runeAbs) > 100 {
		runeThe = runeAbs[:100]
		theme = string(runeThe)
	}

	// 获取邮件配置
	conf := new(models.EnglishReportEmailConf)
	authKey := "english_report_email_conf"
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "无权操作"
		br.ErrMsg = "获取群发邮件权限失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "无权操作"
		br.ErrMsg = "群发邮件配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &conf); e != nil {
		br.Msg = "无权操作"
		br.ErrMsg = "群发邮件配置有误"
		return
	}
	authArr := strings.Split(conf.SendAuthGroup, ",")
	if !utils.InArrayByStr(authArr, sysUser.RoleTypeCode) {
		br.Msg = "无权操作"
		return
	}

	// 获取模板
	confKey := "english_report_email_tmp"
	confTmp, e := company.GetConfigDetailByCode(confKey)
	if e != nil {
		br.Msg = "获取邮件模板失败"
		br.ErrMsg = "获取邮件模板失败, Err: " + e.Error()
		return
	}
	if confTmp.ConfigValue == `` {
		br.Msg = "邮件模板有误"
		br.ErrMsg = "邮件模板为空, 不可推送"
		return
	}

	// 获取发送失败的日志
	emailIds := make([]int, 0)
	emails := make([]*models.EnglishReportEmail, 0)
	logIds := make([]int, 0)
	if req.SendId > 0 {
		logItem, e := models.GetEnglishReportEmailLogById(req.SendId)
		if e != nil {
			br.Msg = "发送失败"
			br.ErrMsg = "获取原邮件推送日志失败, Err: " + e.Error()
			return
		}
		emailIds = append(emailIds, logItem.EmailId)
		logIds = append(logIds, logItem.Id)
	} else {
		var logCond string
		var logPars []interface{}
		logCond += ` AND report_id = ? AND send_status = 0 AND report_type=0`
		logPars = append(logPars, req.ReportId)
		logList, e := models.GetEnglishReportEmailLogList(logCond, logPars)
		if e != nil {
			br.Msg = "发送失败"
			br.ErrMsg = "获取原邮件推送日志列表失败, Err: " + e.Error()
			return
		}
		for i := range logList {
			emailIds = append(emailIds, logList[i].EmailId)
			logIds = append(logIds, logList[i].Id)
		}
	}

	// 获取收件人列表
	// 注: 此处不从失败日志中取email, 因为有可能是地址有误导致的推送失败
	if len(emailIds) > 0 {
		var emailCond string
		var emailPars []interface{}
		emailCond += ` AND id IN (` + utils.GetOrmInReplace(len(emailIds)) + `) and enabled = 1 `
		emailPars = append(emailPars, emailIds)
		em, e := models.GetEnglishReportEmailList(emailCond, emailPars, "")
		if e != nil {
			br.Msg = "获取收件人列表失败"
			br.ErrMsg = "获取收件人列表失败, Err: " + e.Error()
			return
		}
		emails = em
	}
	if len(emails) == 0 {
		br.Msg = "无邮件可推送"
		return
	}

	// 推送信息
	nowTime := time.Now().Local()
	sendData := make([]*services.EnglishReportSendEmailRequest, 0)
	logData := make([]*models.EnglishReportEmailLog, 0)
	for i := range emails {
		r := new(services.EnglishReportSendEmailRequest)
		r.ReportId = reportInfo.Id
		r.EmailId = emails[i].Id
		r.Email = strings.Replace(emails[i].Email, " ", "", -1)
		r.Subject = theme
		r.FromAlias = conf.FromAlias
		// 填充模板
		t := reportInfo.PublishTime.Format("02/01/2006")
		l := fmt.Sprintf(utils.EnglishShareUrl+"/report/detail?code=%s", reportInfo.ReportCode)
		ct := confTmp.ConfigValue
		ct = strings.Replace(ct, "{{REPORT_TITLE}}", reportInfo.Title, 1)
		ct = strings.Replace(ct, "{{REPORT_ABSTRACT}}", reportInfo.Abstract, 1)
		ct = strings.Replace(ct, "{{REPORT_CONTENT}}", reportInfo.Overview, 1)
		ct = strings.Replace(ct, "{{REPORT_SHARE_LINK}}", l, 1)
		ct = strings.Replace(ct, "{{REPORT_TIME}}", t, 1)
		r.HtmlBody = ct
		r.ReportTitle = reportInfo.Title
		r.ReportAbstract = reportInfo.Abstract
		r.ReportContent = reportInfo.Overview
		r.ReportShareLink = l
		r.ReportTime = t
		sendData = append(sendData, r)

		// 日志
		logData = append(logData, &models.EnglishReportEmailLog{
			ReportId:   reportInfo.Id,
			EmailId:    emails[i].Id,
			Email:      emails[i].Email,
			Source:     models.EnglishReportEmailLogSourceAli,
			SendStatus: models.EnglishReportEmailLogStatusIng,
			CreateTime: nowTime,
		})
	}

	// 标记原有日志为已删除
	if len(logIds) > 0 {
		if e = models.DeleteEnglishReportEmailLogByIds(logIds); e != nil {
			br.Msg = "发送失败"
			br.ErrMsg = "删除原邮件日志失败, Err: " + e.Error()
			return
		}
	}

	// 写入新的日志
	emailLog := new(models.EnglishReportEmailLog)
	if e = emailLog.InsertMulti(logData); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "批量写入群发邮件日志失败, Err: " + e.Error()
		return
	}

	// 群发邮件
	go func() {
		services.BatchSendAliEnglishReportEmail(sendData)
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}