package dao

import (
	"time"

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

func GetSkuSalesCntList(db *DaoDB, storeID, cityCode, dayNum, limit int, skuIDs []int) (skuCountList []*model.SkuCount, err error) {
	sql := `
	SELECT t2.jx_sku_id sku_id, SUM(t2.count) count 
	FROM goods_order t1
	JOIN order_sku t2 on t1.vendor_order_id = t2.vendor_order_id and t1.vendor_id = t2.vendor_id
	JOIN store t3 on t1.jx_store_id = t3.id
	WHERE t1.order_finished_at >= ? AND t1.order_finished_at < ?
	AND t1.status = ? 
	AND t2.jx_sku_id <> 0 
	AND t3.city_code = ?
	`
	if dayNum < 0 {
		dayNum = 30
	}
	beginTime := utils.GetCurDate().Add(-time.Hour * 24 * time.Duration(dayNum))
	endTime := utils.GetCurDate()
	sqlParams := []interface{}{
		beginTime,
		endTime,
		model.OrderStatusFinished,
		cityCode,
	}
	if storeID > 0 {
		sql += `
		AND t1.jx_store_id = ?
		`
		sqlParams = append(sqlParams, storeID)
	}
	if len(skuIDs) > 0 {
		sql += ` 
		AND t2.jx_sku_id IN (` + GenQuestionMarks(len(skuIDs)) + `)`
		sqlParams = append(sqlParams, skuIDs)
	}
	sql += `
	GROUP BY jx_sku_id
	ORDER BY count DESC
	`
	if limit > 0 {
		sql += `
		LIMIT ?
		`
		sqlParams = append(sqlParams, limit)
	}
	err = GetRows(db, &skuCountList, sql, sqlParams)
	return skuCountList, err
}

func GetSkuBadCommentCntList(db *DaoDB, storeID, dayNum int) (skuCountList []*model.SkuCount, err error) {
	sql := `
	SELECT t2.jx_sku_id sku_id, COUNT(*) count 
	FROM jx_bad_comments t1
	JOIN order_sku t2 ON t1.order_id = t2.vendor_order_id
	WHERE t1.createtime >= ? AND t1.createtime < ?
	AND t1.jxstoreid = ?
	GROUP BY t2.jx_sku_id
	`
	if dayNum < 0 {
		dayNum = 30
	}
	beginTime := utils.GetCurDate().Add(-time.Hour * 24 * time.Duration(dayNum))
	endTime := utils.GetCurDate()
	sqlParams := []interface{}{
		beginTime,
		endTime,
		storeID,
	}
	err = GetRows(db, &skuCountList, sql, sqlParams)
	return skuCountList, err
}
