package repository

import (
	"fmt"
	"sort"
	"strings"
	"time"

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

// neListSort 网元列表预设排序
var neListSort = []string{
	"OMC",
	"MME",
	"AMF",
	"AUSF",
	"UDM",
	"SMF",
	"PCF",
	"UPF",
	"NRF",
	"NSSF",
	"IMS",
	"N3IWF",
	"NEF",
	"LMF",
}

// 实例化数据层 NeInfoImpl 结构体
var NewNeInfoImpl = &NeInfoImpl{
	selectSql: `select id, ne_type, ne_id, rm_uid, ne_name, ip, port, pv_flag, province, vendor_name, dn, ne_address, status, update_time, host_ids from ne_info`,

	resultMap: map[string]string{
		"id":          "ID",
		"ne_type":     "NeType",
		"ne_id":       "NeId",
		"rm_uid":      "RmUID",
		"ne_name":     "NeName",
		"ip":          "IP",
		"port":        "Port",
		"pv_flag":     "PvFlag",
		"province":    "Province",
		"vendor_name": "VendorName",
		"dn":          "Dn",
		"ne_address":  "NeAddress",
		"status":      "Status",
		"update_time": "UpdateTime",
		"host_ids":    "HostIDs",
	},
}

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

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

	// 排序
	sort.Slice(arr, func(i, j int) bool {
		// 前一个
		after := arr[i]
		afterIndex := 0
		for i, v := range neListSort {
			if after.NeType == v {
				afterIndex = i
				break
			}
		}
		// 后一个
		befter := arr[j]
		befterIndex := 0
		for i, v := range neListSort {
			if befter.NeType == v {
				befterIndex = i
				break
			}
		}
		// 升序
		return afterIndex < befterIndex
	})

	return arr
}

// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r *NeInfoImpl) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
	querySql := r.selectSql + " where ne_type = ? and ne_id = ?"
	results, err := datasource.RawDB("", querySql, []any{neType, neID})
	if err != nil {
		logger.Errorf("query err => %v", err)
		return model.NeInfo{}
	}
	// 转换实体
	rows := r.convertResultRows(results)
	if len(rows) > 0 {
		return rows[0]
	}
	return model.NeInfo{}
}

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

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

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

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

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

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

// SelectList 查询列表
func (r *NeInfoImpl) SelectList(neInfo model.NeInfo) []model.NeInfo {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neInfo.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, neInfo.NeType)
	}
	if neInfo.NeId != "" {
		conditions = append(conditions, "ne_id = ?")
		params = append(params, neInfo.NeId)
	}

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

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

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

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

// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
func (r *NeInfoImpl) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neInfo.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, neInfo.NeType)
	}
	if neInfo.NeId != "" {
		conditions = append(conditions, "ne_id = ?")
		params = append(params, neInfo.NeId)
	}

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

	// 查询数据
	querySql := "select id as 'str' from ne_info " + whereSql + " limit 1"
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		logger.Errorf("query err %v", err)
		return ""
	}
	if len(results) > 0 {
		return fmt.Sprint(results[0]["str"])
	}
	return ""
}

// Insert 新增信息
func (r *NeInfoImpl) Insert(neInfo model.NeInfo) string {
	// 参数拼接
	params := make(map[string]any)
	if neInfo.NeType != "" {
		params["ne_type"] = neInfo.NeType
	}
	if neInfo.NeId != "" {
		params["ne_id"] = neInfo.NeId
	}
	if neInfo.RmUID != "" {
		params["rm_uid"] = neInfo.RmUID
	}
	if neInfo.NeName != "" {
		params["ne_name"] = neInfo.NeName
	}
	if neInfo.IP != "" {
		params["ip"] = neInfo.IP
	}
	if neInfo.Port > 0 {
		params["port"] = neInfo.Port
	}
	if neInfo.PvFlag != "" {
		params["pv_flag"] = neInfo.PvFlag
	}
	if neInfo.Province != "" {
		params["province"] = neInfo.Province
	}
	if neInfo.VendorName != "" {
		params["vendor_name"] = neInfo.VendorName
	}
	if neInfo.Dn != "" {
		params["dn"] = neInfo.Dn
	}
	if neInfo.NeAddress != "" {
		params["ne_address"] = neInfo.NeAddress
	}
	params["status"] = neInfo.Status
	params["update_time"] = time.Now()
	if neInfo.HostIDs != "" {
		params["host_ids"] = neInfo.HostIDs
	}

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into ne_info (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"

	db := datasource.DefaultDB()
	// 开启事务
	tx := db.Begin()
	// 执行插入
	err := tx.Exec(sql, values...).Error
	if err != nil {
		logger.Errorf("insert row : %v", err.Error())
		tx.Rollback()
		return ""
	}
	// 获取生成的自增 ID
	var insertedID string
	err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
	if err != nil {
		logger.Errorf("insert last id : %v", err.Error())
		tx.Rollback()
		return ""
	}
	// 提交事务
	tx.Commit()
	return insertedID
}

// Update 修改信息
func (r *NeInfoImpl) Update(neInfo model.NeInfo) int64 {
	// 参数拼接
	params := make(map[string]any)
	if neInfo.NeType != "" {
		params["ne_type"] = neInfo.NeType
	}
	if neInfo.NeId != "" {
		params["ne_id"] = neInfo.NeId
	}
	if neInfo.RmUID != "" {
		params["rm_uid"] = neInfo.RmUID
	}
	if neInfo.NeName != "" {
		params["ne_name"] = neInfo.NeName
	}
	if neInfo.IP != "" {
		params["ip"] = neInfo.IP
	}
	if neInfo.Port > 0 {
		params["port"] = neInfo.Port
	}
	if neInfo.PvFlag != "" {
		params["pv_flag"] = neInfo.PvFlag
	}
	params["province"] = neInfo.Province
	params["vendor_name"] = neInfo.VendorName
	params["dn"] = neInfo.Dn
	params["ne_address"] = neInfo.NeAddress
	params["status"] = neInfo.Status
	params["update_time"] = time.Now()
	if neInfo.HostIDs != "" {
		params["host_ids"] = neInfo.HostIDs
	}

	// 构建执行语句
	keys, values := repo.KeyValueByUpdate(params)
	sql := "update ne_info set " + strings.Join(keys, ",") + " where id = ?"

	// 执行更新
	values = append(values, neInfo.ID)
	rows, err := datasource.ExecDB("", sql, values)
	if err != nil {
		logger.Errorf("update row : %v", err.Error())
		return 0
	}
	return rows
}

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