package repository

import (
	"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_element/model"
)

// 实例化数据层 UDMAuthImpl 结构体
var NewUDMAuthImpl = &UDMAuthImpl{
	selectSql: `select id, imsi, amf, status, ki, algo_index, opc, ne_id from u_auth_user`,

	resultMap: map[string]string{
		"id":         "ID",
		"imsi":       "Imsi",
		"amf":        "Amf",
		"status":     "Status",
		"ki":         "Ki",
		"algo_index": "AlgoIndex",
		"opc":        "Opc",
		"ne_id":      "NeID",
	},
}

// UDMAuthImpl UDM鉴权信息表 数据层处理
type UDMAuthImpl struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

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

// ClearAndInsert 清空ne_id后新增实体
func (r *UDMAuthImpl) ClearAndInsert(neID string, authArr []model.UDMAuth) int64 {
	// 清空指定ne_id
	_, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil)
	if err != nil {
		logger.Errorf("TRUNCATE err => %v", err)
	}

	return r.Inserts(authArr)
}

// SelectPage 根据条件分页查询
func (r *UDMAuthImpl) SelectPage(query map[string]any) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if v, ok := query["imsi"]; ok && v != "" {
		conditions = append(conditions, "imsi like concat(concat('%', ?), '%')")
		params = append(params, strings.Trim(v.(string), " "))
	}
	if v, ok := query["neId"]; ok && v != "" {
		conditions = append(conditions, "ne_id = ?")
		params = append(params, v)
	}

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

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

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from u_auth_user"
	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(query["pageNum"], query["pageSize"])
	pageSql := " limit ?,? "
	params = append(params, pageNum*pageSize)
	params = append(params, pageSize)

	// 排序
	sortSql := ""
	if v, ok := query["sortField"]; ok && v != "" {
		if v == "imsi" {
			sortSql += " order by imsi "
		}
		if o, ok := query["sortOrder"]; ok && o != nil && v != "" {
			if o == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
	}

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

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

// SelectList 根据实体查询
func (r *UDMAuthImpl) SelectList(auth model.UDMAuth) []model.UDMAuth {
	// 查询条件拼接
	var conditions []string
	var params []any
	if auth.Imsi != "" {
		conditions = append(conditions, "imsi = ?")
		params = append(params, auth.Imsi)
	}
	if auth.NeID != "" {
		conditions = append(conditions, "ne_id = ?")
		params = append(params, auth.NeID)
	}

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

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

	// 转换实体
	return r.convertResultRows(results)
}

// Insert 批量添加
func (r *UDMAuthImpl) Inserts(authUsers []model.UDMAuth) int64 {
	tx := datasource.DefaultDB().CreateInBatches(authUsers, 3000)
	if err := tx.Error; err != nil {
		logger.Errorf("CreateInBatches err => %v", err)
	}
	return tx.RowsAffected
}

// Delete 删除实体
func (r *UDMAuthImpl) Delete(neID, imsi string) int64 {
	tx := datasource.DefaultDB().Where("imsi = ? and ne_id = ?", imsi, neID).Delete(&model.UDMAuth{})
	if err := tx.Error; err != nil {
		logger.Errorf("Delete err => %v", err)
	}
	return tx.RowsAffected
}

// DeletePrefixImsi 删除前缀匹配的实体
func (r *UDMAuthImpl) DeletePrefixImsi(neID, imsi string) int64 {
	tx := datasource.DefaultDB().Where("imsi like concat(?, '%') and ne_id = ?", imsi, neID).Delete(&model.UDMAuth{})
	if err := tx.Error; err != nil {
		logger.Errorf("DeletePrefixImsi err => %v", err)
	}
	return tx.RowsAffected
}
