package acquirer_student

import (
	"context"
	"git.i2edu.net/i2/i2-bill-erp/utils"
	"net/http"
	"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(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	r.ParseForm()
	totalSta := r.Form.Get("create_time_sta")
	totalEnd := r.Form.Get("create_time_end")
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	if totalEnd != "" {
		end, err := time.Parse("2006-01-02", totalEnd)
		if err != nil {
			return &types.Response{500, err.Error(), nil}, nil
		}
		totalEnd = end.Add(time.Second*24*60*60 - 1*time.Second).Format("2006-01-02 15:04:05")

	}
	totalParams := make(map[string]interface{})
	totalParams["create_time_sta"] = totalSta
	totalParams["create_time_end"] = totalEnd
	totalParams["user_id"] = userId
	totalParams["group_by"] = "check_state"

	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)
	todayParams := make(map[string]interface{})
	todayParams["create_time_sta"] = start
	todayParams["create_time_end"] = end
	todayParams["user_id"] = userId

	totalByCheck, err := utils.AllSearch(l.svcCtx.DB, "i2bill_acquirer_student", "total_check", "i2bill_acquirer_student", totalParams)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}

	totalDay, err := utils.AllSearch(l.svcCtx.DB, "i2bill_acquirer_student", "total_check", "i2bill_acquirer_student", todayParams)
	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, repeat 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)
		case 55:
			repeat += t["total"].(int64)
		default:
			untreated += t["total"].(int64)
		}
	}
	res["invalide"] = invalide
	res["untreated"] = untreated
	res["valide"] = valide
	res["today_total"] = totalDay[0]["total"]
	res["target"] = target
	res["repeat"] = repeat
	return &types.Response{200, "", res}, nil
}
