package handler

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

	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"

	"github.com/gin-gonic/gin"
)

func WrapRegisterHandler(ctx *gin.Context) {
	handler := newRegisterHandler(ctx)
	baseRun(handler)
}

func newRegisterHandler(ctx *gin.Context) *RegisterHandler {
	return &RegisterHandler{
		req:  http_model.NewRegisterRequest(),
		resp: http_model.NewRegisterResponse(),
		ctx:  ctx,
	}
}

type RegisterHandler struct {
	req  *http_model.RegisterRequest
	resp *http_model.CommonResponse
	ctx  *gin.Context
}

func (h *RegisterHandler) getRequest() interface{} {
	return h.req
}
func (h *RegisterHandler) getContext() *gin.Context {
	return h.ctx
}
func (h *RegisterHandler) getResponse() interface{} {
	return h.resp
}
func (h *RegisterHandler) run() {
	data := http_model.RegisterRequest{}
	data = *h.req
	message, err := service.Register.AuthRegister(h.ctx, data.Phone, data.Code)
	if err != nil {
		logrus.Errorf("[RegisterHandler] call AuthRegister err:%+v\n", err)
		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
		log.Info("Register fail,req:%+v", h.req)
		return
	} else if message == "" {
		// 3. 先后在user表和enterprise表中增加账号信息
		res, err := service.Enterprise.CreateEnterpriseUser(h.ctx, data)
		if err != nil {
			logrus.Errorf("[RegisterHandler] call CreateEnterpriseUser err:%+v\n", err)
			util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, "")
			log.Info("Register fail,req:%+v", h.req)
			return
		}
		h.resp.Message = "注册成功"
		// 4. 返回ok
		h.resp.Data = res
	} else {
		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, message)
		return
	}
}

func (h *RegisterHandler) checkParam() error {
	return nil
}
