package sandbox

import (
	"hongze/hongze_yb/global"
)

// GetBySandboxId 根据沙盘ID查询详情
func GetBySandboxId(id uint32) (item *Sandbox, err error) {
	err = global.MYSQL["data"].Where("sandbox_id = ? and is_delete=0 ", id).Order("sandbox_id desc").First(&item).Error
	return
}

// GetPageListByWhere 分页获取活动列表
func GetPageListByWhere(condition string, pars []interface{}, startSize, pageSize int) (total int64, list []*Sandbox, err error) {
	// 获取查询总数量
	sql := "select count(1) from sandbox AS s JOIN sandbox_classify AS c ON c.sandbox_classify_id = s.sandbox_classify_id WHERE " + condition + " order by s.modify_time desc,s.sandbox_id desc"
	err = global.MYSQL["data"].Raw(sql, pars...).Scan(&total).Error
	if err != nil {
		return
	}

	// 获取列表数据
	sql = "select s.* from sandbox AS s JOIN sandbox_classify AS c ON c.sandbox_classify_id = s.sandbox_classify_id WHERE " + condition + " order by s.modify_time desc,s.sandbox_id desc"
	sql += " limit ?,? "
	pars = append(pars, startSize, pageSize)
	err = global.MYSQL["data"].Raw(sql, pars...).Find(&list).Error
	return
}

// PermissionSandboxCount 品种下沙盘数
type PermissionSandboxCount struct {
	ChartPermissionID   uint32 `gorm:"column:chart_permission_id;type:int(9) unsigned;not null;default:0" json:"chart_permission_id"`                                  // 品种id
	ChartPermissionName string `gorm:"index:idx_chart_permission_name;column:chart_permission_name;type:varchar(32);not null;default:''" json:"chart_permission_name"` // 品种名称（冗余字段，避免列表页查询时再去关联表查询）
	Total               int64  `json:"total"`                                                                                                                          // 汇总数
}

// GetPermissionCountListByWhere 获取各品种的沙盘数
func GetPermissionCountListByWhere(condition string, pars []interface{}) (list []*PermissionSandboxCount, err error) {

	//err = global.MYSQL["data"].Model(ResearchReport{}).Where("research_report_id IN (?)", ids).Scan(&list).Error

	// 获取列表数据
	err = global.MYSQL["data"].Model(Sandbox{}).Select("chart_permission_id,chart_permission_name,count(1) total").Where(condition, pars...).Order("modify_time desc,sandbox_id desc").Group("chart_permission_id").Scan(&list).Error
	return
}
