package Wx

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

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

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

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

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

func (l *GetSelectWxListLogic) GetSelectWxList(req *types.WxSelectListReq) (resp *types.WxSelectListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var predicates []predicate.Wx
	var ctype uint64 = 1
	if req.Ctype != nil && *req.Ctype > 0 {
		ctype = *req.Ctype
	}
	predicates = append(predicates, wx.Ctype(ctype))
	if !isAdmin {
		predicates = append(predicates, wx.OrganizationIDEQ(organizationId))
	} else {
		if req.OrganizationId != nil && *req.OrganizationId != 0 {
			predicates = append(predicates, wx.OrganizationIDEQ(*req.OrganizationId))
		}
	}
	data, err := l.svcCtx.DB.Wx.Query().Where(predicates...).Order(ent.Desc(wx.FieldOrganizationID)).All(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp = &types.WxSelectListResp{}
	resp.Msg = errormsg.Success

	for _, v := range data {
		wxid := v.Wxid
		if !strings.HasPrefix(wxid, "temp-") {
			resp.Data = append(resp.Data,
				types.WxSelectListInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id: &v.ID,
					},
					Wxid:     &wxid,
					Nickname: &v.Nickname,
					Ctype:    &v.Ctype,
				})
		}
	}

	return resp, nil
}
