package batch_msg

import (
	"context"

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

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

func (l *GetBatchMsgListLogic) GetBatchMsgList(req *types.BatchMsgListReq) (*types.BatchMsgListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.BatchMsg
	predicates = append(predicates, batchmsg.Type(*req.Type))
	predicates = append(predicates, batchmsg.OrganizationIDEQ(organizationId))

	var ctype uint64 = 1
	if req.Ctype != nil {
		ctype = *req.Ctype
	}
	predicates = append(predicates, batchmsg.Ctype(ctype))
	if req.BatchNo != nil {
		predicates = append(predicates, batchmsg.BatchNoContains(*req.BatchNo))
	}
	if req.Fromwxid != nil {
		predicates = append(predicates, batchmsg.FromwxidContains(*req.Fromwxid))
	}
	if req.Msg != nil {
		predicates = append(predicates, batchmsg.MsgContains(*req.Msg))
	}
	if req.TaskName != nil {
		predicates = append(predicates, batchmsg.TaskNameContains(*req.TaskName))
	}
	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()),
				},
				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,
				Ctype:        &v.Ctype,
				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
}
