package admin_notification

import (
	"context"
	"time"

	"xingfucha-server/app/main/api/internal/svc"
	"xingfucha-server/app/main/api/internal/types"
	"xingfucha-server/common/xerr"

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

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

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

func (l *AdminGetNotificationListLogic) AdminGetNotificationList(req *types.AdminGetNotificationListReq) (resp *types.AdminGetNotificationListResp, err error) {
	builder := l.svcCtx.GlobalNotificationsModel.SelectBuilder()
	if req.Title != nil {
		builder = builder.Where("title LIKE ?", "%"+*req.Title+"%")
	}
	if req.NotificationPage != nil {
		builder = builder.Where("notification_page = ?", *req.NotificationPage)
	}
	if req.Status != nil {
		builder = builder.Where("status = ?", *req.Status)
	}
	if req.StartDate != nil {
		if t, err := time.Parse("2006-01-02", *req.StartDate); err == nil {
			builder = builder.Where("start_date >= ?", t)
		}
	}
	if req.EndDate != nil {
		if t, err := time.Parse("2006-01-02", *req.EndDate); err == nil {
			builder = builder.Where("end_date <= ?", t)
		}
	}
	list, total, err := l.svcCtx.GlobalNotificationsModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询通知列表失败, err: %v, req: %+v", err, req)
	}
	items := make([]types.NotificationListItem, 0, len(list))
	for _, n := range list {
		item := types.NotificationListItem{
			Id:               n.Id,
			Title:            n.Title,
			NotificationPage: n.NotificationPage,
			Content:          n.Content,
			StartDate:        "",
			StartTime:        n.StartTime,
			EndDate:          "",
			EndTime:          n.EndTime,
			Status:           n.Status,
			CreateTime:       n.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:       n.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		if n.StartDate.Valid {
			item.StartDate = n.StartDate.Time.Format("2006-01-02")
		}
		if n.EndDate.Valid {
			item.EndDate = n.EndDate.Time.Format("2006-01-02")
		}
		items = append(items, item)
	}
	resp = &types.AdminGetNotificationListResp{
		Total: total,
		Items: items,
	}
	return resp, nil
}
