package edb_info

import (
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/utils"
)

// GetEdbInfoById 主键获取指标信息
func GetEdbInfoById(edbInfoId int) (item *EdbInfo, err error) {
	err = global.MYSQL["data"].Where("edb_info_id = ? ", edbInfoId).First(&item).Error

	return
}

// GetEdbInfoAllCalculateByEdbInfoIdList 根据指标id集合 获取基础指标对应的所有计算指标
func GetEdbInfoAllCalculateByEdbInfoIdList(edbInfoIdList []int) (list []*EdbInfo, err error) {
	num := len(edbInfoIdList)
	if num <= 0 {
		return
	}
	sql := ` SELECT b.* FROM edb_info_calculate_mapping AS a
			 INNER JOIN edb_info AS b ON a.edb_info_id=b.edb_info_id
             WHERE a.from_edb_info_id IN (?)
			 GROUP BY a.edb_info_id
			 ORDER BY a.edb_info_id ASC `
	err = global.MYSQL["data"].Raw(sql, edbInfoIdList).Scan(&list).Error
	return
}

// GetEdbInfoByIdList 根据指标id集合 获取 指标列表
func GetEdbInfoByIdList(edbInfoIdList []int) (items []*EdbInfo, err error) {
	num := len(edbInfoIdList)
	if num <= 0 {
		return
	}
	sql := ` SELECT * FROM edb_info WHERE edb_info_id IN (?) `
	err = global.MYSQL["data"].Raw(sql, edbInfoIdList).Scan(&items).Error
	return
}

// GetRefreshEdbInfoFromBase 查询基础指标
func GetRefreshEdbInfoFromBase(edbInfoId, source int) (baseEdbInfoArr, calculateInfoArr []*EdbInfo, err error) {
	calculateList, err := GetEdbInfoCalculateMap(edbInfoId)
	if err != nil && err != utils.ErrNoRow {
		return
	}
	for _, item := range calculateList {
		if item.EdbInfoId == edbInfoId { //	如果查出来关联的指标就是自己的话，那么就过滤
			continue
		}
		if item.EdbType == 1 {
			baseEdbInfoArr = append(baseEdbInfoArr, item)
		} else {
			calculateInfoArr = append(calculateInfoArr, item)
			newBaseEdbInfoArr, newCalculateInfoArr, _ := GetRefreshEdbInfoFromBase(item.EdbInfoId, item.Source)
			baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
			calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
		}
	}
	return
}

// GetEdbInfoCalculateMap 获取计算指标关联信息
func GetEdbInfoCalculateMap(edbInfoId int) (list []*EdbInfo, err error) {
	sql := ` SELECT b.* FROM edb_info_calculate_mapping AS a
			INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
			WHERE a.edb_info_id=? ORDER BY sort ASC `
	err = global.MYSQL["data"].Raw(sql, edbInfoId).Scan(&list).Error
	return
}

// GetPredictEdbInfoAllCalculate 根据基础预测指标id集合 获取 所有的普通指标列表数据
func GetPredictEdbInfoAllCalculate(edbInfoIdList []int) (list []*EdbInfo, err error) {
	num := len(edbInfoIdList)
	if num <= 0 {
		return
	}
	sql := ` SELECT b.* FROM predict_edb_conf AS a
			 INNER JOIN edb_info AS b ON a.source_edb_info_id=b.edb_info_id
             WHERE a.predict_edb_info_id IN (?)
			 GROUP BY a.source_edb_info_id
			 ORDER BY a.source_edb_info_id ASC `
	err = global.MYSQL["data"].Raw(sql, edbInfoIdList).Scan(&list).Error

	return
}

type EdbInfoSearchData struct {
	DataTime string  `description:"数据日期"`
	Value    float64 `description:"数据"`
}
