package service

import (
	"fmt"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
	"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
	protocol "openapi/pkg/domain"
	"openapi/pkg/infrastructure/sms"
	"openapi/pkg/infrastructure/sms/yunpian"
	"strings"
)

// SmsCode 发送短信验证码
func SmsCode(header *protocol.RequestHeader, request *protocol.SmsCodeRequest) (rsp interface{}, err error) {
	code := common.RandomStringWithChars(6, protocol.Nums)
	var smsSvr sms.ISmsService = &yunpian.YPSmsService{}
	content := fmt.Sprintf("【买买买信息科技】%v(手机验证码,请完成验证),如非本人操作,请忽略本短信", code)
	// save log to db
	log.Debug(fmt.Sprintf("【sms】 smscode phone:%v code:%v", request.Phone, code))
	// save to redis
	if err = redis.Set(smsRedisKey(request.Phone), code, sms.DefaultSmsCodeTimeOut); err != nil {
		logError(err)
		err = protocol.NewCustomMessage(1001, "请求超时,请检查手机号是否正确或网络连接状态")
		return nil, err
	}
	if err = smsSvr.Send(&sms.Options{Phone: request.Phone, SendType: sms.SendSingle, Content: content}); err != nil {
		logError(err)
		err = protocol.NewCustomMessage(1001, "请求超时,请检查手机号是否正确或网络连接状态")
		return nil, err
	}
	return
}

// CheckSmsCode 检查短信验证码
func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCodeRequest) (rsp interface{}, err error) {
	var value string
	if value, err = redis.Get(smsRedisKey(request.Phone)); err != nil || len(value) == 0 {
		logError(err)
		err = protocol.NewCustomMessage(1004, "验证码已失效")
		return nil, err
	}
	if !strings.EqualFold(value, request.Code) {
		err = protocol.NewCustomMessage(1004, "验证码错误,重新输入")
		return nil, err
	}
	redis.Del(smsRedisKey(request.Phone))
	return
}

// SendSmsNotice 发送短信通知
func SendSmsNotice(header *protocol.RequestHeader, request *protocol.SendSmsNoticeRequest) (rsp interface{}, err error) {
	var smsSvr sms.ISmsService = &yunpian.YPSmsService{}
	options := sms.NewOptions(
		sms.WithPhone(request.Phone),
		sms.WithSendType(sms.SendSingleByTpl),
		sms.WithTpl(request.TplId, request.TplValues),
	)
	err = smsSvr.Send(options)
	return
}

func logError(err error) {
	log.Error(fmt.Sprintf("【sms】 %v", err.Error()))
}

func smsRedisKey(phone string) string {
	return strings.Join([]string{"sms", "smscode", phone}, ":")
}