package dao

import (
	"fmt"
	"time"

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

func InsertStoreScore(storeScore *model.StoreScore) error {
	storeScore.CreatedAt = time.Now()
	return CreateEntity(nil, storeScore)
}

func GetWeeklyStoreScoreList(db *DaoDB, storeID, weekNum int) (storeScoreList []*model.StoreScoreEx, err error) {
	sql := `
	SELECT t2.name store_name, t1.* FROM store_score t1
	JOIN store t2 ON t1.store_id = t2.id
	WHERE t1.store_id = ?
	AND DATE(t1.score_date) >= DATE_SUB(
		DATE_SUB(
			CURDATE(),
			INTERVAL
		IF (
			DAYOFWEEK(CURDATE()) - 1 = 0,
			7,
			DAYOFWEEK(CURDATE()) - 1
		) DAY
		),
		INTERVAL ? DAY
	)
	AND DATE(t1.score_date) <= DATE_SUB(
		CURDATE(),
		INTERVAL
		IF (
			DAYOFWEEK(CURDATE()) - 1 = 0,
			7,
			DAYOFWEEK(CURDATE()) - 1
		) DAY
	)
	ORDER BY score_date DESC
	`
	if weekNum <= 0 {
		weekNum = 1
	}
	diffDays := weekNum*7 - 1
	sqlParams := []interface{}{
		storeID,
		diffDays,
	}
	err = GetRows(db, &storeScoreList, sql, sqlParams)
	return storeScoreList, err
}

func CheckHasStoreScoreData(db *DaoDB, dateTime time.Time) (hasStoreScoreData bool, err error) {
	sql := `
	SELECT COUNT(*) count 
	FROM store_score 
	WHERE DATE(score_date) = DATE(?)
	`
	sqlParams := []interface{}{
		dateTime,
	}
	count := 0
	err = GetRow(db, &count, sql, sqlParams)
	hasStoreScoreData = count > 0
	return hasStoreScoreData, err
}

func GetStoreTotalScoreList(db *DaoDB, storeIDList []int, cityCode int, keyWord string, beginTime, endTime time.Time) (storeTotalScoreList []*model.StoreTotalScore, err error) {
	sql := `
	SELECT t2.id store_id, t2.name store_name, t3.name city_name,
	SUM(t1.store_open_time + t1.sale_sku_count + t1.average_pickup_time + t1.bad_comment_order + t1.unfinish_order 
	+ t1.absent_Goods_order + t1.promotion_sku + t1.full_vendor + t1.store_range + t1.sale_sku_price) store_score
	FROM store_score t1
	JOIN store t2 ON t1.store_id = t2.id
	JOIN place t3 ON t2.city_code = t3.code
	WHERE DATE(t1.score_date) >= DATE(?) AND DATE(t1.score_date) <= DATE(?)
	`
	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 += `
	GROUP BY t1.store_id, t1.score_date
	`
	err = GetRows(db, &storeTotalScoreList, sql, sqlParams)

	return storeTotalScoreList, err
}
