package contact

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent"
	"wechat-api/ent/contact"
	"wechat-api/ent/label"
	"wechat-api/ent/labelrelationship"
	"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 GetWhatsappContactListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetWhatsappContactListLogic) GetWhatsappContactList(req *types.WhatsappContactListReq) (*types.ContactListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.Contact
	predicates = append(predicates, contact.OrganizationIDEQ(organizationId))
	predicates = append(predicates, contact.Ctype(2))
	if len(req.LabelIDs) > 0 {
		predicates = append(predicates, contact.HasContactRelationshipsWith(
			labelrelationship.HasLabelsWith(
				label.IDIn(req.LabelIDs...),
			),
		))
	}
	if req.Phone != nil {
		predicates = append(predicates, contact.PhoneContains(*req.Phone))
	}
	if req.Name != nil {
		predicates = append(predicates, contact.CnameContains(*req.Name))
	}

	data, err := l.svcCtx.DB.Contact.Query().Where(predicates...).WithContactRelationships(func(query *ent.LabelRelationshipQuery) {
		query.WithLabels()
	}).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		labelRelationships := make([]types.ContactLabelList, 0)
		if v.Edges.ContactRelationships != nil {
			for _, lr := range v.Edges.ContactRelationships {
				if lr.Edges.Labels == nil {
					continue
				}
				labelRelationships = append(labelRelationships, types.ContactLabelList{
					Label: &lr.Edges.Labels.Name,
					Value: &lr.LabelID,
				})
			}
		}

		resp.Data.Data = append(resp.Data.Data,
			types.ContactInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Cc:                 &v.Cc,
				Phone:              &v.Phone,
				Status:             &v.Status,
				Nickname:           &v.Nickname,
				Markname:           &v.Markname,
				LabelRelationships: labelRelationships,
				OrganizationId:     &v.OrganizationID,
				Ctype:              &v.Ctype,
				Cname:              &v.Cname,
				Sex:                &v.Sex,
				Cage:               &v.Cage,
				Carea:              &v.Carea,
				Cbirthday:          &v.Cbirthday,
				Cbirtharea:         &v.Cbirtharea,
				CidcardNo:          &v.CidcardNo,
				Ctitle:             &v.Ctitle,
			})
	}

	return resp, nil
}
