package xunji_service

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/predicate"
	"wechat-api/ent/xunjiservice"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *GetXunjiServiceListLogic) GetXunjiServiceList(req *types.XunjiServiceListReq) (*types.XunjiServiceListResp, error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)

	var predicates []predicate.XunjiService

	if isAdmin {
		if req.XunjiID != nil && *req.XunjiID > 0 {
			predicates = append(predicates, xunjiservice.XunjiID(*req.XunjiID))
		}
	} else {
		if req.XunjiID == nil || *req.XunjiID <= 0 {
			return nil, errorx.NewInvalidArgumentError("父ID不能为空")
		}
		predicates = append(predicates, xunjiservice.XunjiID(*req.XunjiID))
	}
	data, err := l.svcCtx.DB.XunjiService.Query().Where(predicates...).WithAgent().Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		var agent types.AgentInfo
		if v.Edges.Agent != nil {
			agent = types.AgentInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.AgentID,
					CreatedAt: pointy.GetPointer(v.Edges.Agent.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.Edges.Agent.UpdatedAt.UnixMilli()),
				},
				Name:       &v.Edges.Agent.Name,
				Role:       &v.Edges.Agent.Role,
				Status:     &v.Edges.Agent.Status,
				Background: &v.Edges.Agent.Background,
				Examples:   &v.Edges.Agent.Examples,
			}
		}

		resp.Data.Data = append(resp.Data.Data,
			types.XunjiServiceInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:         &v.Status,
				XunjiId:        &v.XunjiID,
				AgentId:        &v.AgentID,
				AgentInfo:      &agent,
				OrganizationId: &v.OrganizationID,
				Wxid:           &v.Wxid,
				ApiBase:        &v.APIBase,
				ApiKey:         &v.APIKey,
			})
	}

	return resp, nil
}
