package dao

import (
	"fmt"
	"time"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
)

func InsertStoreAlert(storeAlert *model.StoreAlert) error {
	storeAlert.CreatedTime = time.Now()
	return CreateEntity(nil, storeAlert)
}

func GetStoreAlertList(db *DaoDB, storeIDList []int, cityCode int, keyWord string, dateTime time.Time) (storeAlertList []*model.StoreAlertEx, err error) {
	sql := `
	SELECT t1.*, t2.name store_name, t3.name city_name
	FROM store_alert t1
	JOIN store t2 ON t1.store_id = t2.id
	JOIN place t3 ON t2.city_code = t3.code
	WHERE t1.alert_date >= ? AND t1.alert_date <= ?
	`
	beginTime, endTime := utils.GetTimeRange(dateTime, 1, true)
	sqlParams := []interface{}{
		beginTime,
		endTime,
	}
	if len(storeIDList) > 0 {
		sql += `
		AND t2.id in (` + GenQuestionMarks(len(storeIDList)) + `)`
		sqlParams = append(sqlParams, storeIDList)
	}
	if cityCode > 0 {
		sql += `
		AND t3.code = ?`
		sqlParams = append(sqlParams, cityCode)
	}
	if keyWord != "" {
		sql += `
		AND (t2.id LIKE ? OR t2.name LIKE ? OR t3.name LIKE ?)`
		keyWord = fmt.Sprintf("%%%s%%", keyWord)
		sqlParams = append(sqlParams, keyWord, keyWord, keyWord)
	}
	sql += `
	ORDER BY t1.store_id
	`
	err = GetRows(db, &storeAlertList, sql, sqlParams)

	return storeAlertList, err
}
