package batch_msg

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

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

func (l *GetWhatcappBatchMsgHistoryLogic) GetWhatcappBatchMsgHistory(req *types.WhatsappBatchMsgHistoryReq) (*types.WhatsappBatchMsgHistoryResp, error) {
	resp := types.WhatsappBatchMsgHistoryResp{}

	batch_msg, err := l.svcCtx.DB.BatchMsg.Query().Where(batchmsg.ID(req.Id)).First(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var predicates []predicate.Msg
	predicates = append(predicates, msg.BatchNo(batch_msg.BatchNo))

	if req.Status != nil {
		predicates = append(predicates, msg.StatusEQ(*req.Status))
	}
	if req.Phone != nil {
		predicates = append(predicates, msg.PhoneContains(*req.Phone))
	}

	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.Data.Total = data.PageDetails.Total

	index := (req.Page - 1) * (req.PageSize)
	for seg, value := range data.List {
		index += uint64(seg)
		resp.Data.Data = append(resp.Data.Data, types.HistoryInfo{
			Index:    &index,
			BatchNo:  &value.BatchNo,
			From:     &value.Fromwxid,
			To:       &value.Toid,
			SendTime: pointy.GetPointer(value.CreatedAt.UnixMilli()),
			Cc:       &value.Cc,
			Phone:    &value.Phone,
			Status:   &value.Status,
		})
	}

	return &resp, nil
}
