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"
)

// 实例化数据层 CDREventSMF 结构体
var NewCDREventSMF = &CDREventSMF{
	selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at,
		t.tenant_id, t.tenant_name	
		from cdr_event_smf c
		left join sys_tenant t on t.tenant_id = c.tenant_id and t.status = 1`,

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

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

// convertResultRows 将结果记录转实体结果组
func (r *CDREventSMF) convertResultRows(rows []map[string]any) []model.CDREventSMF {
	arr := make([]model.CDREventSMF, 0)
	for _, row := range rows {
		item := model.CDREventSMF{}
		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 *CDREventSMF) SelectPage(querys model.CDREventSMFQuery) 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.RecordType != "" {
		conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.recordType') = ?")
		params = append(params, querys.RecordType)
	}
	if querys.SubscriberID != "" {
		conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?")
		params = append(params, querys.SubscriberID)
	}
	if querys.DNN != "" {
		conditions = append(conditions, "JSON_EXTRACT(cdr_json, '$.pDUSessionChargingInformation.dNNID') = ?")
		params = append(params, querys.DNN)
	}

	// 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("tenantName=%v, tenantID=%v", querys.TenantName, tenantID)
		if tenantID != "" {
			conditions = append(conditions, "c.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, "c.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.CDREventSMF{},
	}

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from cdr_event_smf c"
	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 CDREventSMF) SelectByPage(querys model.CDREventSMFQuery) ([]model.CDREventSMF, int64) {
	tx := datasource.DB("").Model(&model.CDREventSMF{})
	// 查询条件拼接
	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.RecordType != "" {
		tx = tx.Where("JSON_EXTRACT(cdr_json, '$.recordType') = ?", querys.RecordType)
	}
	if querys.SubscriberID != "" {
		tx = tx.Where("JSON_EXTRACT(cdr_json, '$.subscriberIdentifier.subscriptionIDData') = ?", querys.SubscriberID)
	}
	if querys.DNN != "" {
		tx = tx.Where("JSON_EXTRACT(cdr_json, '$.pDUSessionChargingInformation.dNNID') = ?", querys.DNN)
	}

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

	// 查询数量为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 *CDREventSMF) SelectByIds(ids []string) []model.CDREventSMF {
	rows := []model.CDREventSMF{}
	if len(ids) <= 0 {
		return rows
	}
	tx := datasource.DB("").Model(&model.CDREventSMF{})
	// 构建查询条件
	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 *CDREventSMF) DeleteByIds(ids []string) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := datasource.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.CDREventSMF{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}
