package xunji

import (
	"context"

	"wechat-api/ent/xunji"
	"wechat-api/ent/predicate"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

    "github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetXunjiListLogic) GetXunjiList(req *types.XunjiListReq) (*types.XunjiListResp, error) {
	var predicates []predicate.Xunji
	if req.AppKey != nil {
		predicates = append(predicates, xunji.AppKeyContains(*req.AppKey))
	}
	if req.AppSecret != nil {
		predicates = append(predicates, xunji.AppSecretContains(*req.AppSecret))
	}
	if req.Token != nil {
		predicates = append(predicates, xunji.TokenContains(*req.Token))
	}
	data, err := l.svcCtx.DB.Xunji.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
		types.XunjiInfo{
			BaseIDInfo:    types.BaseIDInfo{
				Id:          &v.ID,
				CreatedAt:    pointy.GetPointer(v.CreatedAt.UnixMilli()),
				UpdatedAt:    pointy.GetPointer(v.UpdatedAt.UnixMilli()),
            },
			Status:	&v.Status,
			AppKey:	&v.AppKey,
			AppSecret:	&v.AppSecret,
			Token:	&v.Token,
			EncodingKey:	&v.EncodingKey,
			AgentId:	&v.AgentID,
			OrganizationId:	&v.OrganizationID,
			Wxid:	&v.Wxid,
			ApiBase:	&v.APIBase,
			ApiKey:	&v.APIKey,
		})
	}

	return resp, nil
}
