package admin_notification

import (
	"context"
	"database/sql"
	"time"

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

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

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

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

func (l *AdminCreateNotificationLogic) AdminCreateNotification(req *types.AdminCreateNotificationReq) (resp *types.AdminCreateNotificationResp, err error) {
	startDate, _ := time.Parse("2006-01-02", req.StartDate)
	endDate, _ := time.Parse("2006-01-02", req.EndDate)
	data := &model.GlobalNotifications{
		Title:            req.Title,
		Content:          req.Content,
		NotificationPage: req.NotificationPage,
		StartDate:        sql.NullTime{Time: startDate, Valid: req.StartDate != ""},
		EndDate:          sql.NullTime{Time: endDate, Valid: req.EndDate != ""},
		StartTime:        req.StartTime,
		EndTime:          req.EndTime,
		Status:           req.Status,
	}
	result, err := l.svcCtx.GlobalNotificationsModel.Insert(l.ctx, nil, data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建通知失败, err: %v, req: %+v", err, req)
	}
	id, _ := result.LastInsertId()
	return &types.AdminCreateNotificationResp{Id: id}, nil
}
