package UsageDetail

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/predicate"
	"wechat-api/ent/usagedetail"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/zeromicro/go-zero/core/logx"
)

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

func NewGetUsageDetailListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageDetailListLogic {
	return &GetUsageDetailListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetUsageDetailListLogic) GetUsageDetailList(req *types.UsageDetailListReq) (resp *types.UsageDetailListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)

	var predicates []predicate.UsageDetail

	if !isAdmin {
		predicates = append(predicates, usagedetail.OrganizationIDEQ(organizationId))
	}
	predicates = append(predicates, usagedetail.BotID(*req.BotId))

	data, err := l.svcCtx.DB.UsageDetail.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp = &types.UsageDetailListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		app := "未知"
		if v.App == 1 {
			app = "智能回复"
		} else if v.App == 2 {
			app = "AI角色-优化问题"
		} else if v.App == 3 {
			app = "AI角色-回复"
		} else if v.App == 4 {
			app = "SOP-节点判断"
		} else if v.App == 5 {
			app = "SOP-节点判断"
		}
		request := v.Request
		if v.App == 2 {
			request = "问题优化"
		} else if v.App == 4 {
			request = "节点判断"
		}
		resp.Data.Data = append(resp.Data.Data,
			types.UsageDetailInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:           &v.Status,
				Type:             &v.Type,
				BotId:            &v.BotID,
				ReceiverId:       &v.ReceiverID,
				App:              &app,
				SessionId:        &v.SessionID,
				Request:          &request,
				Response:         &v.Response,
				TotalTokens:      &v.TotalTokens,
				PromptTokens:     &v.PromptTokens,
				CompletionTokens: &v.CompletionTokens,
				OrganizationId:   &v.OrganizationID,
			})
	}

	return resp, nil
	//return nil, nil
}
