package repository

import (
	"ems.agt/src/framework/datasource"
	"ems.agt/src/framework/logger"
	"ems.agt/src/framework/utils/repo"
	"ems.agt/src/modules/net_element/model"
)

// 实例化数据层 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 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",
	},
}

// 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)
	}
	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{}
}
