package contact

import (
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/contact"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetContactSimpleListLogic) GetContactSimpleList(req *types.ContactListReq) (*types.ContactSimpleListResp, error) {
	var predicates []predicate.Contact

	var ctype uint64 = 1
	if req.Ctype != nil {
		ctype = *req.Ctype
	}
	predicates = append(predicates, contact.Ctype(ctype))

	if req.WxWxid != nil {
		predicates = append(predicates, contact.WxWxidContains(*req.WxWxid))
	}
	if req.Wxid != nil {
		predicates = append(predicates, contact.WxidContains(*req.Wxid))
	}
	if req.Account != nil {
		predicates = append(predicates, contact.AccountContains(*req.Account))
	}
	if req.Nickname != nil {
		predicates = append(predicates, contact.NicknameContains(*req.Nickname))
	}
	if req.Type != nil {
		predicates = append(predicates, contact.TypeEQ(*req.Type))
	} else {
		predicates = append(predicates, contact.Or(contact.TypeEQ(1), contact.TypeEQ(2)))
	}

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

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

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

	for _, v := range data.List {
		var nickname string
		if v.Markname != "" {
			nickname = fmt.Sprintf("%s(%s)", v.Nickname, v.Markname)
		} else {
			nickname = v.Nickname
		}
		resp.Data.Data = append(resp.Data.Data,
			types.ContactSimpleInfo{
				Wxid:     &v.Wxid,
				Nickname: &nickname,
			})
	}

	return resp, nil
}
