package repo

import (
	"strconv"
	"strings"

	"nms_nbi/features/udm_user/model"
	"nms_nbi/lib/core/datasource"
	"nms_nbi/lib/core/utils/parse"
	"nms_nbi/lib/log"
)

// 实例化数据层 RepoUdmAuthUser 结构体
var NewRepoUdmAuthUser = &RepoUdmAuthUser{
	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",
	},
}

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

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

// SelectPage 根据条件分页查询
func (r *RepoUdmAuthUser) 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, v)
	}
	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.UdmAuthUser{},
	}

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

	// 分页
	pageNum, pageSize := datasource.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 {
		log.Errorf("query err => %v", err)
	}

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

// SelectList 根据实体查询
func (r *RepoUdmAuthUser) SelectList(auth model.UdmAuthUser) []model.UdmAuthUser {
	// 查询条件拼接
	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 {
		log.Errorf("query err => %v", err)
	}

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

// ClearAndInsert 清空ne_id后新增实体
func (r *RepoUdmAuthUser) ClearAndInsert(neID string, authArr []model.UdmAuthUser) int64 {
	var num int64 = 0

	// 清空指定ne_id
	_, err := datasource.ExecDB("", "TRUNCATE TABLE u_auth_user", nil)
	// _, err := datasource.ExecDB("", "DELETE FROM u_auth_user WHERE ne_id = ?", []any{neID})
	if err != nil {
		log.Errorf("TRUNCATE err => %v", err)
	}

	n := len(authArr)
	batchSize := 2000
	for i := 0; i < n; i += batchSize {
		end := i + batchSize
		if end > n {
			end = n
		}
		batch := authArr[i:end]

		// 调用 InsertMulti 函数将批量数据插入数据库
		results, err := datasource.DefaultDB().Table("u_auth_user").InsertMulti(batch)
		if err != nil {
			log.Errorf("InsertMulti err => %v", err)
			continue
		}
		num += results
	}
	return num
}

// Insert 新增实体
func (r *RepoUdmAuthUser) Insert(authUser model.UdmAuthUser) int64 {
	results, err := datasource.DefaultDB().Table("u_auth_user").Insert(authUser)
	if err != nil {
		log.Errorf("Insert err => %v", err)
		return results
	}
	return results
}

// Insert 批量添加
func (r *RepoUdmAuthUser) Inserts(authUsers []model.UdmAuthUser) int64 {
	var num int64
	n := len(authUsers)
	batchSize := 2000
	for i := 0; i < n; i += batchSize {
		end := i + batchSize
		if end > n {
			end = n
		}
		batch := authUsers[i:end]

		// 调用 InsertMulti 函数将批量数据插入数据库
		results, err := datasource.DefaultDB().Table("u_auth_user").InsertMulti(batch)
		if err != nil {
			log.Errorf("Insert err => %v", err)
			continue
		}
		num += results
	}
	return num
}

// Update 修改更新
func (r *RepoUdmAuthUser) Update(neID string, authUser model.UdmAuthUser) int64 {
	// 查询先
	var user model.UdmAuthUser
	has, err := datasource.DefaultDB().Table("u_auth_user").Where("imsi = ? and ne_id = ?", authUser.Imsi, neID).Get(&user)
	if !has || err != nil {
		return 0
	}

	if authUser.Ki != "" && authUser.Ki != user.Ki {
		user.Ki = authUser.Ki
	}
	if authUser.Amf != "" && authUser.Amf != user.Amf {
		user.Amf = authUser.Amf
	}
	if authUser.AlgoIndex != "" && authUser.AlgoIndex != user.AlgoIndex {
		user.AlgoIndex = authUser.AlgoIndex
	}
	if authUser.Opc != "" && authUser.Opc != user.Opc {
		user.Opc = authUser.Opc
	}

	results, err := datasource.DefaultDB().Table("u_auth_user").Where("imsi = ? and ne_id = ?", user.Imsi, user.NeID).Update(user)
	if err != nil {
		return 0
	}
	return results
}

// Delete 删除实体
func (r *RepoUdmAuthUser) Delete(neID, imsi string) int64 {
	results, err := datasource.DefaultDB().Table("u_auth_user").Where("imsi = ? and ne_id = ?", imsi, neID).Delete()
	if err != nil {
		return results
	}
	return results
}

// Delete 删除范围实体
func (r *RepoUdmAuthUser) Deletes(neID, imsi, num string) int64 {
	imsiV, err := strconv.Atoi(imsi)
	if err != nil {
		return 0
	}

	numV, err := strconv.Atoi(num)
	if err != nil {
		return 0
	}

	results, err := datasource.DefaultDB().Table("u_auth_user").Where("imsi >= ? and imsi < ? and ne_id = ?", imsiV, imsiV+numV, neID).Delete()
	if err != nil {
		return results
	}
	return results
}
