package label

import (
	"context"
	"fmt"
	"wechat-api/ent"

	"wechat-api/ent/label"
	"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 GetLabelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func convertContactToContactInfo(label *ent.Contact) types.ContactInfo {
	return types.ContactInfo{
		BaseIDInfo: types.BaseIDInfo{
			Id:        &label.ID,
			CreatedAt: pointy.GetPointer(label.CreatedAt.UnixMilli()),
			UpdatedAt: pointy.GetPointer(label.UpdatedAt.UnixMilli()),
		},
		Status:    &label.Status,
		WxWxid:    &label.WxWxid,
		Type:      &label.Type,
		Wxid:      &label.Wxid,
		Account:   &label.Account,
		Nickname:  &label.Nickname,
		Markname:  &label.Markname,
		Headimg:   &label.Headimg,
		Sex:       &label.Sex,
		Starrole:  &label.Starrole,
		Dontseeit: &label.Dontseeit,
		Dontseeme: &label.Dontseeme,
		Lag:       &label.Lag,
		Gid:       &label.Gid,
		Gname:     &label.Gname,
		V3:        &label.V3,
	}
}

func (l *GetLabelListLogic) GetLabelList(req *types.LabelListReq) (*types.LabelListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)
	fmt.Printf("---------------isAdmin----------------: %+v\n\n", isAdmin)
	var predicates []predicate.Label
	predicates = append(predicates, label.OrganizationIDEQ(organizationId))
	if req.Type != nil {
		predicates = append(predicates, label.TypeEQ(*req.Type))
	}
	if req.Name != nil {
		predicates = append(predicates, label.NameContains(*req.Name))
	}
	if req.From != nil {
		predicates = append(predicates, label.FromEQ(*req.From))
	}
	if req.Mode != nil {
		predicates = append(predicates, label.ModeEQ(*req.Mode))
	}
	data, err := l.svcCtx.DB.Label.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.LabelInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:     &v.Status,
				Type:       &v.Type,
				Name:       &v.Name,
				From:       &v.From,
				Mode:       &v.Mode,
				Conditions: &v.Conditions,
			})
	}

	return resp, nil
}
