package activity

import (
	"errors"
	"gorm.io/gorm"
	"hongze/hongze_yb/models/tables/yb_activity"
	"hongze/hongze_yb/models/tables/yb_activity_remind"
	"hongze/hongze_yb/services/user"
	"log"
	"time"
)

type RemindCheckInfo struct {
	Specific	int		`json:"specific" description:"是否指定返回"`
	Msg			string	`json:"msg" description:"提示信息"`
	Type   		string 	`json:"type" description:"校验失败，需要让前端处理的类型，枚举值：time"`
}

// CreateRemind 新增提醒
func CreateRemind(activityId int, userInfo user.UserInfo) (err error, remindCheck RemindCheckInfo) {
	userId := int(userInfo.UserID)
	ok, msg, remindCheck := checkRemindOk(userId, activityId)
	if !ok {
		err = errors.New(msg)
		return
	}
	remindInfo := &yb_activity_remind.YbActivityRemind{
		ActivityID: uint32(activityId),
		UserID:     uint64(userId),
		CompanyID:  uint64(userInfo.CompanyID),
		RealName:   userInfo.RealName,
		Mobile:     userInfo.Mobile,
		CreateTime: time.Now(),
	}
	err = remindInfo.Create()
	if err != nil {
		log.Print(err)
		err = errors.New("设置提醒失败")
	}
	return
}

// checkRemindOk 验证是否可以新增提醒
func checkRemindOk(userId, activityId int) (ok bool, msg string, remindCheck RemindCheckInfo) {
	activity, err := yb_activity.GetOneById(activityId)
	if err == gorm.ErrRecordNotFound {
		msg = "活动信息有误"
		return
	}
	_, err = yb_activity_remind.RemindExist(userId, activityId)
	if err != gorm.ErrRecordNotFound {
		msg = "请勿重复设置提醒"
		return
	}
	// 活动时间
	nowUtime := time.Now().Unix()
	endUtime := activity.EndTime.Unix()
	if nowUtime > endUtime {
		msg = "活动已结束"
		return
	}
	nowUtime += 60 * 15
	startUtime := activity.StartTime.Unix()
	if nowUtime > startUtime {
		msg = "活动开始前十五分钟内无法设置会议提醒"
		remindCheck = RemindCheckInfo{
			Specific: 1,
			Msg: msg,
			Type: "time",
		}
		return
	}
	ok = true
	return
}

// CancelRemind 取消提醒
func CancelRemind(activityId int, userInfo user.UserInfo) (err error) {
	userId := int(userInfo.UserID)
	_, err = yb_activity.GetOneById(activityId)
	if err == gorm.ErrRecordNotFound {
		err = errors.New("活动信息有误")
		return
	}
	remindInfo, err := yb_activity_remind.RemindExist(userId, activityId)
	if err == gorm.ErrRecordNotFound {
		err = errors.New("提醒信息有误")
		return
	}
	err = yb_activity_remind.Delete(remindInfo)
	if err != nil {
		log.Print(err.Error())
		err = errors.New("取消提醒失败")
	}
	return
}
