package services

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/utils"
	"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
	}

	tplId := utils.SmsNewLoginTplId
	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
	}

	// 获取邮箱模板
	confKey := "admin_verify_code_email_tmp"
	confTmp, e := company.GetConfigDetailByCode(confKey)
	if e != nil {
		err = fmt.Errorf("获取邮件模板失败, Err: %s", e.Error())
		return
	}
	if confTmp.ConfigValue == `` {
		err = fmt.Errorf("邮件模板为空, 不可推送")
		return
	}

	req := new(EnglishReportSendEmailRequest)
	req.Subject = "弘则研究登录验证"
	req.Email = email
	req.FromAlias = conf.FromAlias
	// 填充模板
	t := time.Now().Format("2006年01月02日")
	ct := confTmp.ConfigValue
	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
}
