package admin_notification

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

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

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

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

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

func (l *AdminUpdateNotificationLogic) AdminUpdateNotification(req *types.AdminUpdateNotificationReq) (resp *types.AdminUpdateNotificationResp, err error) {
	notification, err := l.svcCtx.GlobalNotificationsModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查找通知失败, err: %v, id: %d", err, req.Id)
	}
	if req.StartDate != nil {
		startDate, _ := time.Parse("2006-01-02", *req.StartDate)
		notification.StartDate = sql.NullTime{Time: startDate, Valid: true}
	}
	if req.EndDate != nil {
		endDate, _ := time.Parse("2006-01-02", *req.EndDate)
		notification.EndDate = sql.NullTime{Time: endDate, Valid: true}
	}
	if req.Title != nil {
		notification.Title = *req.Title
	}
	if req.Content != nil {
		notification.Content = *req.Content
	}
	if req.NotificationPage != nil {
		notification.NotificationPage = *req.NotificationPage
	}
	if req.StartTime != nil {
		notification.StartTime = *req.StartTime
	}
	if req.EndTime != nil {
		notification.EndTime = *req.EndTime
	}
	if req.Status != nil {
		notification.Status = *req.Status
	}
	_, err = l.svcCtx.GlobalNotificationsModel.Update(l.ctx, nil, notification)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新通知失败, err: %v, req: %+v", err, req)
	}
	return &types.AdminUpdateNotificationResp{Success: true}, nil
}
