package wxcard

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/wxcard"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetWxCardListLogic) GetWxCardList(req *types.WxCardListReq) (*types.WxCardListResp, error) {
	var predicates []predicate.WxCard

	if req.Name != nil && *req.Name != "" {
		predicates = append(predicates, wxcard.NameContains(*req.Name))
	}

	data, err := l.svcCtx.DB.WxCard.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.WxCardListResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
	}

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data, types.WxCardInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &v.ID,
				CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			},
			Name:            &v.Name,
			Avatar:          &v.Avatar,
			Logo:            &v.Logo,
			Company:         &v.Company,
			Address:         &v.Address,
			Phone:           &v.Phone,
			OfficialAccount: &v.OfficialAccount,
			WechatAccount:   &v.WechatAccount,
			Email:           &v.Email,
			Intro:           &v.Intro,
			ApiBase:         &v.APIBase,
			ApiKey:          &v.APIKey,
			AiInfo:          &v.AiInfo,
		})
	}

	return resp, nil
}
