package handler

import (
	"fmt"
	"youngee_b_api/consts"
	"youngee_b_api/model/http_model"
	"youngee_b_api/service"
	"youngee_b_api/util"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

// WrapSendCodeHandler
// @BasePath /
// SendCode godoc
// @Summary sendCode 发送验证码
// @Schemes
// @Description 发送验证码，每次发送到邮箱
// @Accept json
// @Produce json
// @Param req body http_model.SendCodeRequest true "发送验证码请求参数结构体"
// @Success 200 {object} http_model.CommonResponse{data=http_model.SendCodeData} "发送验证码请求相应结构体"
// @Router /sendCode [post]
func WrapSendCodeHandler(ctx *gin.Context) {
	handler := newSendCodeHandler(ctx)
	baseRun(handler)
}

func newSendCodeHandler(ctx *gin.Context) *SendCodeHandler {
	return &SendCodeHandler{
		req:  http_model.NewSendCodeRequest(),
		resp: http_model.NewSendCodeResponse(),
		ctx:  ctx,
	}
}

type SendCodeHandler struct {
	req  *http_model.SendCodeRequest
	resp *http_model.CommonResponse
	ctx  *gin.Context
}

func (h *SendCodeHandler) getRequest() interface{} {
	return h.req
}
func (h *SendCodeHandler) getContext() *gin.Context {
	return h.ctx
}
func (h *SendCodeHandler) getResponse() interface{} {
	return h.resp
}
func (h *SendCodeHandler) run() {
	data := http_model.SendCodeRequest{}
	data = *h.req
	// 1. 生成验证码
	vcode := service.SendCode.GetCode(h.ctx)
	// 2. 发送验证码
	fmt.Println(vcode)
	err := service.SendCode.SendCode(h.ctx, data.Phone, vcode)
	if err != nil {
		logrus.Errorf("[SendeCodeHandler] call SetSession err:%+v\n", err)
		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
		log.Info("SendeCode fail,req:%+v", h.req)
		return
	}
	// if data.Email == "login" {
	// 	// 根据手机号查询邮箱
	// 	email, err := service.SendCode.GetEmailByPhone(h.ctx, data.Phone)
	// 	if err != nil {
	// 		logrus.Errorf("[SendeCodeHandler] call SetSession err:%+v\n", err)
	// 		if email != "" {
	// 			util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "账号不存在")
	// 		} else {
	// 			util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
	// 		}
	// 		log.Info("SendeCode fail,req:%+v", h.req)
	// 		return
	// 	}
	// 	subject := "Youngee验证码"
	// 	service.SMTPMailServiceIstance.SendHtmlMail(email, subject, vcode)
	// } else {
	// 	subject := "Youngee验证码"
	// 	service.SMTPMailServiceIstance.SendHtmlMail(data.Email, subject, vcode)
	// }

	// 3. {phone:code}存到redis
	err = service.SendCode.SetSession(h.ctx, data.Phone, vcode)
	if err != nil {
		logrus.Errorf("[SendeCodeHandler] call SetSession err:%+v\n", err)
		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
		log.Info("SendeCode fail,req:%+v", h.req)
		return
	}
	h.resp.Message = "验证码发送成功，请注意查收"
	h.resp.Status = 200
}
func (h *SendCodeHandler) checkParam() error {
	return nil
}
