package repository

import (
	"fmt"
	"strings"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/utils/repo"
	"be.ems/src/modules/network_data/model"
)

// 实例化数据层 AlarmImpl 结构体
var NewAlarmImpl = &AlarmImpl{
	selectSql: `select 
	id, alarm_seq, alarm_id, alarm_title, ne_type, ne_id, alarm_code, event_time, 
	alarm_type, orig_severity, perceived_severity, pv_flag, ne_name, object_uid, object_name,
	object_type, location_info, province, alarm_status, specific_problem, specific_problem_id,
	add_info, counter, latest_event_time, ack_state, ack_time, ack_user, clear_type,
	clear_time, clear_user, timestamp
	from alarm`,

	resultMap: map[string]string{
		"id":                  "ID",
		"alarm_seq":           "AlarmSeq",
		"alarm_id":            "AlarmId",
		"alarm_title":         "AlarmTitle",
		"ne_type":             "NeType",
		"ne_id":               "NeId",
		"alarm_code":          "AlarmCode",
		"event_time":          "EventTime",
		"alarm_type":          "AlarmType",
		"orig_severity":       "OrigSeverity",
		"perceived_severity":  "PerceivedSeverity",
		"pv_flag":             "PvFlag",
		"ne_name":             "NeName",
		"object_uid":          "ObjectUid",
		"object_name":         "ObjectName",
		"object_type":         "ObjectType",
		"location_info":       "LocationInfo",
		"province":            "Province",
		"alarm_status":        "AlarmStatus",
		"specific_problem":    "SpecificProblem",
		"specific_problem_id": "SpecificProblemId",
		"add_info":            "AddInfo",
		"counter":             "Counter",
		"latest_event_time":   "LatestEventTime",
		"ack_state":           "AckState",
		"ack_time":            "AckTime",
		"ack_user":            "AckUser",
		"clear_type":          "ClearType",
		"clear_time":          "ClearTime",
		"clear_user":          "ClearUser",
		"timestamp":           "Timestamp",
	},
}

// AlarmImpl 告警 数据层处理
type AlarmImpl struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *AlarmImpl) convertResultRows(rows []map[string]any) []model.Alarm {
	arr := make([]model.Alarm, 0)
	for _, row := range rows {
		item := model.Alarm{}
		for key, value := range row {
			if keyMapper, ok := r.resultMap[key]; ok {
				repo.SetFieldValue(&item, keyMapper, value)
			}
		}
		arr = append(arr, item)
	}
	return arr
}

// SelectPage 根据条件分页查询
func (r *AlarmImpl) SelectPage(querys model.AlarmQuery) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if querys.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, querys.NeType)
	}
	if querys.RmUID != "" {
		conditions = append(conditions, "object_uid = ?")
		params = append(params, querys.RmUID)
	}
	if querys.StartTime != "" {
		conditions = append(conditions, "timestamp >= ?")
		params = append(params, querys.StartTime)
	}
	if querys.EndTime != "" {
		conditions = append(conditions, "timestamp <= ?")
		params = append(params, querys.EndTime)
	}
	if querys.OrigSeverity != "" {
		eventTypes := strings.Split(querys.OrigSeverity, ",")
		placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
		conditions = append(conditions, fmt.Sprintf("orig_severity in (%s)", placeholder))
		for _, eventType := range eventTypes {
			params = append(params, eventType)
		}
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	result := map[string]any{
		"total": 0,
		"rows":  []model.Alarm{},
	}

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from alarm"
	totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
	if err != nil {
		logger.Errorf("total err => %v", err)
		return result
	}
	total := parse.Number(totalRows[0]["total"])
	if total == 0 {
		return result
	} else {
		result["total"] = total
	}

	// 分页
	pageNum, pageSize := repo.PageNumSize(querys.PageNum, querys.PageSize)
	pageSql := " limit ?,? "
	params = append(params, pageNum*pageSize)
	params = append(params, pageSize)

	// 排序
	orderSql := ""
	if querys.SortField != "" {
		sortSql := querys.SortField
		if querys.SortOrder != "" {
			if querys.SortOrder == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		orderSql = fmt.Sprintf(" order by %s ", sortSql)
	}

	// 查询数据
	querySql := r.selectSql + whereSql + orderSql + pageSql
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err => %v", err)
	}

	// 转换实体
	result["rows"] = r.convertResultRows(results)
	return result
}

// SelectByIds 通过ID查询
func (r *AlarmImpl) SelectByIds(ids []string) []model.Alarm {
	placeholder := repo.KeyPlaceholderByQuery(len(ids))
	querySql := r.selectSql + " where id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(ids)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.Alarm{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

// DeleteByIds 批量删除信息
func (r *AlarmImpl) DeleteByIds(ids []string) int64 {
	placeholder := repo.KeyPlaceholderByQuery(len(ids))
	sql := "delete from alarm where id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(ids)
	results, err := datasource.ExecDB("", sql, parameters)
	if err != nil {
		logger.Errorf("delete err => %v", err)
		return 0
	}
	return results
}
