package notify

import (
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)

// 执行定时任务检查是否发送短信通知
var taskSmsNotify *notifySms

// 检查并发送短信通知
func RunTaskSmsNotify() {
	taskSmsNotify = &notifySms{}
	taskSmsNotify.init()
	taskSmsNotify.regist(notifyStaffAssess{})
	taskSmsNotify.regist(notifySummaryEvaluation{})
	taskSmsNotify.regist(notifyConfirmEvaluationScore{})
	taskSmsNotify.runTask()
}

// 每日自评短信通知 ,预创建待发送的短信消息
func AddNotifyStaffAssess(param *domain.StaffAssess) {

	newNotify := notifyStaffAssess{}
	newSms := newNotify.makeNotify(param)
	if newSms == nil {
		return
	}
	taskSmsNotify.addTask(newSms)
}

// 周期自评短信通知 ,预创建待发送的短信消息
func AddNotifySummaryEvaluation(param *domain.SummaryEvaluation) {
	newNotify := notifySummaryEvaluation{}
	newSms := newNotify.makeNotify(param)
	if newSms == nil {
		return
	}
	taskSmsNotify.addTask(newSms)
}

// 确认周期评估短信提醒 ,预创建待发送的短信消息
func AddNotifyConfirmEvaluationScore(param *domain.SummaryEvaluation) error {
	newNotify := notifyConfirmEvaluationScore{}
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return err
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	logSmsRepo := factory.CreateLogSmsRepository(map[string]interface{}{"transactionContext": transactionContext})

	cnt, _, err := logSmsRepo.Find(map[string]interface{}{"from": newNotify.from(), "index": param.Id, "limit": 1})
	if err != nil {
		return err
	}
	if cnt > 0 {
		return nil
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return err
	}

	newSms := newNotify.makeNotify(param)
	if newSms == nil {
		return nil
	}
	return taskSmsNotify.addTask(newSms)
}