package acquirer

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"
	"git.i2edu.net/i2/i2-bill-api/model"

	"git.i2edu.net/i2/go-zero/core/logx"
	"git.i2edu.net/i2/go-zero/core/stores/sqlc"
)

type EnrollLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	UserId     int64
	SessionKey string
}

func NewEnrollLogic(ctx context.Context, svcCtx *svc.ServiceContext) EnrollLogic {
	return EnrollLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EnrollLogic) Enroll(req types.EnrollRequest) (*types.Response, error) {
	var stu model.I2billAcquirerStudent
	var qrScence struct {
		UserId    int64     `json:"userId"`
		Timestamp time.Time `json:"timestamp"`
		Type      string    `json:"type"`
	}
	err := l.svcCtx.Wechat.GetQrParams(svc.QrcodeJzPrefix, req.Scene, &qrScence)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	}
	err = l.svcCtx.SqlConn.QueryRowPartial(&stu, fmt.Sprintf("select %s from i2bill_acquirer_student where `user_id`=? and `stu_phone`=? limit 1", model.I2billAcquirerStudentRows), qrScence.UserId, req.ContactPhone)
	if err != sqlc.ErrNotFound && err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	} else if stu.Id > 0 {
		return &types.Response{Code: 500, Msg: "已录入成功, 请勿重复操作", Data: nil}, nil
	} else {
		stu.UserId = sql.NullInt64{Int64: qrScence.UserId, Valid: true}
		stu.StuPhone = sql.NullString{String: req.ContactPhone, Valid: true}
		_, err := l.svcCtx.I2billAcquirerStudentModel.Insert(stu)
		if err != nil {
			logx.Error(err.Error())
			return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
		}
	}
	return &types.Response{}, nil
}
