package Msg

import (
	"context"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/batchmsg"

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

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

func (l *GetMsgListLogic) GetMsgList(req *types.MsgListReq) (*types.MsgListResp, error) {
	var predicates []predicate.Msg
	batchMsg, err := l.svcCtx.DB.BatchMsg.Query().Where(batchmsg.IDEQ(*req.BatchId)).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errorx.NewInvalidArgumentError("群发消息不存在")
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	predicates = append(predicates, msg.BatchNo(batchMsg.BatchNo))
	if req.Status != nil {
		predicates = append(predicates, msg.StatusEQ(*req.Status))
	}
	if req.Toid != nil {
		predicates = append(predicates, msg.ToidContains(*req.Toid))
	}
	data, err := l.svcCtx.DB.Msg.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.MsgInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:   &v.Status,
				Fromwxid: &v.Fromwxid,
				Toid:     &v.Toid,
				Msgtype:  &v.Msgtype,
				Msg:      &v.Msg,
				BatchNo:  &v.BatchNo,
			})
	}

	return resp, nil
}
