package repository

import (
	"fmt"
	"strings"

	dborm "be.ems/lib/core/datasource"
	"be.ems/lib/log"
	"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"
)

// 实例化数据层 UEEventMME 结构体
var NewUEEventMME = &UEEventMME{
	selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, event_type, event_json, created_at,
		t.tenant_id, t.tenant_name
		from ue_event_mme e
		left join sys_tenant t on t.tenant_id = e.tenant_id and t.status = 1`,

	resultMap: map[string]string{
		"id":          "ID",
		"ne_type":     "NeType",
		"ne_name":     "NeName",
		"rm_uid":      "RmUID",
		"timestamp":   "Timestamp",
		"event_type":  "EventType",
		"event_json":  "EventJSONStr",
		"created_at":  "CreatedAt",
		"tenant_id":   "TenantID",
		"tenant_name": "TenantName",
	},
}

// UEEventMME UE会话事件 数据层处理
type UEEventMME struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *UEEventMME) convertResultRows(rows []map[string]any) []model.UEEventMME {
	arr := make([]model.UEEventMME, 0)
	for _, row := range rows {
		item := model.UEEventMME{}
		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 *UEEventMME) SelectPage(querys model.UEEventMMEQuery) 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, "rm_uid = ?")
		params = append(params, querys.RmUID)
	}
	if querys.StartTime != 0 {
		conditions = append(conditions, "timestamp >= ?")
		startTime := fmt.Sprintf("%d", querys.StartTime)
		if len(startTime) == 13 {
			startTime = startTime[:10]
		}
		params = append(params, startTime)
	}
	if querys.EndTime != 0 {
		conditions = append(conditions, "timestamp <= ?")
		endTime := fmt.Sprintf("%d", querys.EndTime)
		if len(endTime) == 13 {
			endTime = endTime[:10]
		}
		params = append(params, endTime)
	}
	if querys.EventType != "" {
		eventTypes := strings.Split(querys.EventType, ",")
		placeholder := repo.KeyPlaceholderByQuery(len(eventTypes))
		conditions = append(conditions, fmt.Sprintf("event_type in (%s)", placeholder))
		for _, eventType := range eventTypes {
			params = append(params, eventType)
		}
	}
	if querys.IMSI != "" {
		conditions = append(conditions, "JSON_EXTRACT(event_json, '$.imsi') = ?")
		params = append(params, querys.IMSI)
	}

	// for multi-tenancy solution
	if querys.TenantName != "" {
		var tenantID string
		_, err := dborm.DefaultDB().Table("sys_tenant").
			Where("tenant_name=? and status=1", querys.TenantName).Cols("tenant_id").Distinct().Get(&tenantID)
		if err != nil {
			log.Errorf("Get tenant_id from sys_user err => %v", err)
		}
		log.Tracef("userName=%v, tenantID=%v", querys.TenantName, tenantID)
		if tenantID != "" {
			conditions = append(conditions, "e.tenant_id = ?")
			params = append(params, tenantID)
		}
	} else if querys.UserName != "" {
		var tenantID string
		_, err := dborm.DefaultDB().Table("sys_user").
			Where("user_name=? and status=1", querys.UserName).Cols("tenant_id").Distinct().Get(&tenantID)
		if err != nil {
			log.Errorf("Get tenant_id from sys_user err => %v", err)
		}
		log.Tracef("userName=%v, tenantID=%v", querys.UserName, tenantID)
		if tenantID != "" {
			conditions = append(conditions, "e.tenant_id = ?")
			params = append(params, tenantID)
		}
	}

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

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

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from ue_event_mme e"
	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 id desc, %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
}

// SelectByPage 分页查询集合
func (r UEEventMME) SelectByPage(querys model.UEEventMMEQuery) ([]model.UEEventMME, int64) {
	tx := datasource.DB("").Model(&model.UEEventMME{})
	// 查询条件拼接
	if querys.NeType != "" {
		tx = tx.Where("ne_type = ?", querys.NeType)
	}
	if querys.RmUID != "" {
		tx = tx.Where("rm_uid = ?", querys.RmUID)
	}
	if querys.StartTime != 0 {
		startTime := fmt.Sprintf("%d", querys.StartTime)
		if len(startTime) == 13 {
			startTime = startTime[:10]
		}
		tx = tx.Where("timestamp >= ?", startTime)
	}
	if querys.EndTime != 0 {
		endTime := fmt.Sprintf("%d", querys.EndTime)
		if len(endTime) == 13 {
			endTime = endTime[:10]
		}
		tx = tx.Where("timestamp <= ?", endTime)
	}
	if querys.EventType != "" {
		eventTypes := strings.Split(querys.EventType, ",")
		tx = tx.Where("event_type in ?", eventTypes)
	}
	if querys.IMSI != "" {
		tx = tx.Where("JSON_EXTRACT(event_json, '$.imsi') = ?", querys.IMSI)
	}

	// 查询结果
	var total int64 = 0
	rows := []model.UEEventMME{}

	// 查询数量为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 排序
	if querys.SortField != "" {
		sortField := querys.SortField
		if querys.SortOrder == "desc" {
			sortField = sortField + " desc"
		}
		tx = tx.Order(sortField)
	}

	// 查询数据分页
	pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize)
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
	err := tx.Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询
func (r UEEventMME) SelectByIds(ids []string) []model.UEEventMME {
	rows := []model.UEEventMME{}
	if len(ids) <= 0 {
		return rows
	}
	tx := datasource.DB("").Model(&model.UEEventMME{})
	// 构建查询条件
	tx = tx.Where("id in ?", ids)
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// DeleteByIds 批量删除信息
func (r UEEventMME) DeleteByIds(ids []string) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := datasource.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.UEEventMME{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}
