package batch_msg

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

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

func (l *GetWhatcappBatchMsgListLogic) GetWhatcappBatchMsgList(req *types.WhatsappBatchMsgListReq) (*types.BatchMsgListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.BatchMsg
	predicates = append(predicates, batchmsg.OrganizationIDEQ(organizationId))
	predicates = append(predicates, batchmsg.Ctype(2))
	if req.BatchNo != nil {
		predicates = append(predicates, batchmsg.BatchNoContains(*req.BatchNo))
	}
	if req.Phone != nil {
		predicates = append(predicates, batchmsg.PhoneContains(*req.Phone))
	}
	if req.Msg != nil {
		predicates = append(predicates, batchmsg.MsgContains(*req.Msg))
	}
	data, err := l.svcCtx.DB.BatchMsg.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.BatchMsgInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Phone:        &v.Phone,
				Cc:           &v.Cc,
				Status:       &v.Status,
				BatchNo:      &v.BatchNo,
				TaskName:     &v.TaskName,
				Fromwxid:     &v.Fromwxid,
				Msg:          &v.Msg,
				Tag:          &v.Tag,
				Total:        &v.Total,
				Success:      &v.Success,
				Fail:         &v.Fail,
				Type:         &v.Type,
				TemplateName: &v.TemplateName,
				TemplateCode: &v.TemplateCode,
				Lang:         &v.Lang,
				StartTime:    pointy.GetUnixMilliPointer(v.StartTime.UnixMilli()),
				StopTime:     pointy.GetUnixMilliPointer(v.StopTime.UnixMilli()),
				StartTimeStr: pointy.GetPointer(v.StartTime.Format("2006-01-02 15:04:05")),
			})
	}

	return resp, nil
}
