package repository

import (
	"fmt"
	"strings"

	"nms_nbi/src/framework/datasource"
	"nms_nbi/src/framework/logger"
	"nms_nbi/src/modules/network_data/model"
)

// 实例化数据层 PerfKPIImpl 结构体
var NewPerfKPIImpl = &PerfKPIImpl{}

// PerfKPIImpl 性能统计 数据层处理
type PerfKPIImpl struct{}

// SelectGoldKPI 通过网元指标数据信息
func (r *PerfKPIImpl) SelectGoldKPI(query model.GoldKPIQuery, kpiIds []string) []map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if query.RmUID != "" {
		conditions = append(conditions, "gk.rm_uid = ?")
		params = append(params, query.RmUID)
	}
	if query.NeType != "" {
		conditions = append(conditions, "gk.ne_type = ?")
		params = append(params, query.NeType)
	}
	if query.StartTime != "" {
		conditions = append(conditions, "gk.start_time >= ?")
		params = append(params, query.StartTime)
	}
	if query.EndTime != "" {
		conditions = append(conditions, "gk.start_time <= ?")
		params = append(params, query.EndTime)
	}
	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	// 查询字段列
	timeFormat := "DATE_FORMAT(gk.start_time, '%Y-%m-%d %H:%i:')"
	secondGroup := fmt.Sprintf("LPAD(FLOOR(SECOND(gk.start_time) / %d) * %d, 2, '0')", query.Interval, query.Interval)
	groupByField := fmt.Sprintf("CONCAT( %s, %s ) AS timeGroup", timeFormat, secondGroup)
	if query.Interval > 60 {
		minute := query.Interval / 60
		timeFormat = "DATE_FORMAT(gk.start_time, '%Y-%m-%d %H:')"
		minuteGroup := fmt.Sprintf("LPAD(FLOOR(MINUTE(gk.start_time) / %d) * %d, 2, '0')", minute, minute)
		groupByField = fmt.Sprintf("CONCAT( %s, %s ) AS timeGroup", timeFormat, minuteGroup)
	}
	var fields = []string{
		groupByField,
		"min(CASE WHEN gk.index != '' THEN gk.index ELSE 0 END) AS startIndex",
		"min(CASE WHEN gk.ne_type != '' THEN gk.ne_type ELSE 0 END) AS neType",
		"min(CASE WHEN gk.ne_name != '' THEN gk.ne_name ELSE 0 END) AS neName",
	}
	for _, kid := range kpiIds {
		// 特殊字段，只取最后一次收到的非0值
		if kid == "AMF.01" || kid == "UDM.01" || kid == "UDM.02" || kid == "UDM.03" || kid == "SMF.01" {
			str := fmt.Sprintf("IFNULL(SUBSTRING_INDEX(GROUP_CONCAT( CASE WHEN gk.kpi_id = '%s' and gk.VALUE != 0 THEN gk.VALUE END  ), ',', 1), 0) AS '%s'", kid, kid)
			fields = append(fields, str)
		} else {
			str := fmt.Sprintf("sum(CASE WHEN gk.kpi_id = '%s' THEN gk.value ELSE 0 END) AS '%s'", kid, kid)
			fields = append(fields, str)
		}
	}
	fieldsSql := strings.Join(fields, ",")

	// 查询数据
	if query.SortField == "" {
		query.SortField = "timeGroup"
	}
	if query.SortOrder == "" {
		query.SortOrder = "desc"
	}
	orderSql := fmt.Sprintf(" order by %s %s", query.SortField, query.SortOrder)
	querySql := fmt.Sprintf("SELECT %s FROM gold_kpi gk %s GROUP BY timeGroup %s", fieldsSql, whereSql, orderSql)
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err => %v", err)
	}
	return results
}

// SelectGoldKPITitle 网元对应的指标名称
func (r *PerfKPIImpl) SelectGoldKPITitle(neType string) []model.GoldKPITitle {
	result := []model.GoldKPITitle{}
	tx := datasource.DefaultDB().Table("kpi_title").Where("ne_type = ?", neType).Find(&result)
	if err := tx.Error; err != nil {
		logger.Errorf("Find err => %v", err)
	}
	return result
}

// SelectUPFTotalFlow 查询UPF总流量 N3上行 N6下行
func (r *PerfKPIImpl) SelectUPFTotalFlow(neType, rmUID, startDate, endDate string) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neType != "" {
		conditions = append(conditions, "gk.ne_type = ?")
		params = append(params, neType)
	}
	if rmUID != "" {
		conditions = append(conditions, "gk.rm_uid = ?")
		params = append(params, rmUID)
	}
	if startDate != "" {
		conditions = append(conditions, "gk.date >= ?")
		params = append(params, startDate)
	}
	if endDate != "" {
		conditions = append(conditions, "gk.date <= ?")
		params = append(params, endDate)
	}
	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	// 查询数据
	querySql := fmt.Sprintf("SELECT sum( CASE WHEN gk.kpi_id = 'UPF.03' THEN gk.VALUE ELSE 0 END ) AS 'up', sum( CASE WHEN gk.kpi_id = 'UPF.06' THEN gk.VALUE ELSE 0 END ) AS 'down' FROM gold_kpi gk %s", whereSql)
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err => %v", err)
	}
	return results[0]
}
