package logic

import (
	"context"
	"time"

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

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

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

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

func (l *AcquirerStudentTotalLogic) AcquirerStudentTotal() (*types.Response, error) {
	// todo: add your logic here and delete this line
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	sqlTotalByCheck := `
				SELECT
    					count(*) total ,check_state
				FROM
   						 i2bill_mkt_part_time_user
				WHERE
						 del_flag = 0
						and user_id = ?
				GROUP BY   check_state`

	sqlTotalByToDay := `
				SELECT
    					count(*) total
				FROM
   						 i2bill_mkt_part_time_user
				WHERE
						 del_flag = 0
						and user_id = ?
						and  create_time  between ? and ?`

	totalByCheck, err := l.svcCtx.DB.NewSession().SQL(sqlTotalByCheck, userId).Query().List()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	timeNow := time.Now()
	start := time.Date(timeNow.Year(), timeNow.Month(), timeNow.Day(), 0, 0, 0, 0, time.Local)
	end := start.Add(24*60*60*time.Second - 1*time.Second)
	totalDay, err := l.svcCtx.DB.NewSession().SQL(sqlTotalByToDay, userId, start, end).Query().List()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	var target int64
	l.svcCtx.DB.Table("i2bill_mkt_part_time_user").Select("target").Where("user_id = ? and del_flag = 0", userId).Get(&target)
	var res = make(map[string]interface{})
	var invalide, untreated, valide int64
	for _, t := range totalByCheck {
		switch t["check_state"].(int64) {
		case 54, 56, 59:
			untreated += t["total"].(int64)
		case 57:
			valide += t["total"].(int64)
		case 58:
			invalide += t["total"].(int64)
		}
	}
	res["invalide"] = invalide
	res["untreated"] = untreated
	res["valide"] = valide
	res["today_total"] = totalDay[0]["total"]
	res["target"] = target
	return &types.Response{200, "", res}, nil
}
