package services

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/company"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// SendAdminMobileVerifyCode 发送用户手机验证码
func SendAdminMobileVerifyCode(source int, mobile, areaCode string) (ok bool, err error) {
	verifyCode := utils.GetRandDigit(6)
	record := new(system.AdminVerifyCodeRecord)
	record.VerifyType = system.AdminVerifyCodeRecordTypeMobile
	record.Mobile = mobile
	record.Source = source
	record.Code = verifyCode
	record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
	record.CreateTime = time.Now().Local()
	record.ModifyTime = time.Now().Local()
	if e := record.Create(); e != nil {
		err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
		return
	}
	// 获取配置好的短信模版
	smsCond := ` AND conf_key = ? `
	smsPars := make([]interface{}, 0)
	smsPars = append(smsPars, "LoginSmsTpId")
	conf := new(models.BusinessConf)
	conf, e := conf.GetItemByCondition(smsCond, smsPars)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			err = fmt.Errorf("请先配置短信模版")
			return
		}
		err = fmt.Errorf("获取短信模版失败, Err: %s", e.Error())
		return
	}

	//tplId := utils.SmsNewLoginTplId
	tplId := conf.ConfVal
	if tplId == "" {
		err = fmt.Errorf("请先配置短信模版")
		return
	}
	if areaCode == "86" {
		ok = SendSmsCode(mobile, verifyCode, tplId)
	} else {
		ok = SendSmsCodeGj(mobile, verifyCode, areaCode)
	}
	record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
	if !ok {
		record.SendStatus = system.AdminVerifyCodeRecordStatusFail
	}
	cols := []string{"SendStatus"}
	if e := record.Update(cols); e != nil {
		err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
	}
	return
}

// SendAdminEmailVerifyCode 发送用户邮箱验证码
func SendAdminEmailVerifyCode(source int, email string) (ok bool, err error) {
	verifyCode := utils.GetRandDigit(6)
	record := new(system.AdminVerifyCodeRecord)
	record.VerifyType = system.AdminVerifyCodeRecordTypeEmail
	record.Email = email
	record.Source = source
	record.Code = verifyCode
	record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
	record.CreateTime = time.Now().Local()
	record.ModifyTime = time.Now().Local()
	if e := record.Create(); e != nil {
		err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
		return
	}

	// 获取邮件配置
	authKey := "english_report_email_conf"
	emailConf, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		err = fmt.Errorf("获取群发邮件权限失败, Err: %s", e.Error())
		return
	}
	if emailConf.ConfigValue == "" {
		err = fmt.Errorf("邮件配置为空, 不可推送")
		return
	}
	conf := new(models.EnglishReportEmailConf)
	if e = json.Unmarshal([]byte(emailConf.ConfigValue), &conf); e != nil {
		err = fmt.Errorf("邮件配置有误, 不可推送")
		return
	}

	// 获取邮箱模板
	// 获取配置好的短信模版
	cond := ` AND (conf_key = ? OR conf_key = ?)`
	pars := make([]interface{}, 0)
	pars = append(pars, "LoginEmailTemplateSubject", "LoginEmailTemplateContent")
	busiConf := new(models.BusinessConf)
	emailConfList, e := busiConf.GetItemsByCondition(cond, pars, []string{"conf_key, conf_val"}, "")
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			err = fmt.Errorf("请先配置邮件模版")
			return
		}
		err = fmt.Errorf("获取邮件模版失败, Err: %s", e.Error())
		return
	}
	var emaiContent, emailSubject string
	for _, v := range emailConfList {
		if v.ConfKey == "LoginEmailTemplateContent" {
			emaiContent = v.ConfVal
		} else if v.ConfKey == "LoginEmailTemplateSubject" {
			emailSubject = v.ConfVal
		}
	}
	if emailSubject == "" {
		err = fmt.Errorf("请先配置邮件模版主题")
		return
	}
	if emaiContent == "" {
		err = fmt.Errorf("请先配置邮件模版内容")
		return
	}

	req := new(EnglishReportSendEmailRequest)
	req.Subject = emailSubject
	req.Email = email
	// todo 发信人昵称
	req.FromAlias = conf.FromAlias
	// 填充模板
	t := time.Now().Format("2006年01月02日")
	ct := emaiContent
	ct = strings.Replace(ct, "{{VERIFY_CODE}}", verifyCode, 1)
	ct = strings.Replace(ct, "{{EXPIRED_MINUTE}}", strconv.Itoa(utils.VerifyCodeExpireMinute), 1)
	ct = strings.Replace(ct, "{{DATE_TIME}}", t, 1)
	req.HtmlBody = ct

	aliEmail := new(AliyunEmail)
	o, result, e := aliEmail.SendEmail(req)
	if e != nil {
		err = fmt.Errorf("邮箱推送失败, Err: %s", e.Error())
		return
	}
	ok = o

	record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
	if !ok {
		record.SendStatus = system.AdminVerifyCodeRecordStatusFail
	}
	record.SendResult = result
	cols := []string{"SendStatus", "SendResult"}
	if e = record.Update(cols); e != nil {
		err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
	}
	return
}
