package acquirer_student

import (
	"context"
	"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"
	"strconv"
	"time"

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

type AcquirerStudentAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *AcquirerStudentAddLogic) AcquirerStudentAdd(req types.EnrollAddReq) (*types.Response, error) {
	// todo: add your logic here and delete this line
	sign := req.Sign
	if sign == "" {
		return &types.Response{500, "二维码已失效", nil}, nil
	}
	userId, err := strconv.ParseInt(sign, 10, 64)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	//是否有权限收单
	erpUser, err := model.GetAcquirePermInfo(userId, l.svcCtx.Transformer, l.svcCtx.DB, l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, "二维码已失效", nil}, nil
	}
	if erpUser == nil || erpUser.UserId == "" {
		return &types.Response{500, "二维码已失效", nil}, nil
	}
	//去重
	stu, err := l.svcCtx.DB.SQL("select * from i2bill_acquirer_student where stu_phone = ?  and DATE_FORMAT(create_time,'%Y-%m-%d') = ? ", req.StuPhone, time.Now().Format("2006-01-02")).Query().List()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if len(stu) > 0 {
		return &types.Response{500, "你今天已提交过信息，感谢你的填写", nil}, nil
	}
	bean := new(model.I2billAcquirerStudentXorm)
	bean.AgeGroup = int64(req.AgeGroup)
	bean.StuPhone = req.StuPhone
	bean.Address = req.Address
	bean.UserId = userId
	//加入part信息
	partUser, err := model.GetPartTimeXormByUserId(userId, l.svcCtx.DB)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	bean.PartTimeUserId = partUser.Id
	//获取渠道收单信息
	acquirerInfo, err := model.GetAcquirerMktQr(userId, l.svcCtx.DB)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	if acquirerInfo.Id == 0 || acquirerInfo.Role != erpUser.Role {
		return &types.Response{500, "二维码已失效", nil}, nil
	}
	bean.LoadSchId = acquirerInfo.SchoolId
	bean.MkId = erpUser.UserId
	bean.NetworkDetailId = acquirerInfo.NetworkDetailId
	bean.QuaoYji = acquirerInfo.QuaoYji
	bean.MaType = acquirerInfo.MaType
	bean.CallType = acquirerInfo.CallType
	bean.ActiveId = acquirerInfo.ActivityId
	bean.DelFlag = 0
	bean.CheckState = 54
	bean.StuName = req.StuName
	bean.StuLinkPerson = req.StuLinkPerson
	bean.SchId = int64(req.SchId)
	bean.CreateTime = time.Now()
	_, err = l.svcCtx.DB.Insert(bean)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	return &types.Response{200, "", nil}, nil
}
