package repository

import (
	"fmt"
	"strings"
	"time"

	"nms_nbi/src/framework/datasource"
	"nms_nbi/src/framework/logger"
	"nms_nbi/src/framework/utils/crypto"
	"nms_nbi/src/framework/utils/parse"
	"nms_nbi/src/framework/utils/repo"
	"nms_nbi/src/modules/network_element/model"
)

// 实例化数据层 NewNeHostImpl 结构体
var NewNeHostImpl = &NeHostImpl{
	selectSql: `select 
	host_id, host_type, group_id, title, addr, port, user, auth_mode, password, private_key, pass_phrase, remark, create_by, create_time, update_by, update_time
	from ne_host`,

	resultMap: map[string]string{
		"host_id":          "HostID",
		"host_type":        "HostType",
		"group_id":         "GroupID",
		"title":            "Title",
		"addr":             "Addr",
		"port":             "Port",
		"user":             "User",
		"auth_mode":        "AuthMode",
		"password":         "Password",
		"private_key":      "PrivateKey",
		"private_password": "PassPhrase",
		"remark":           "Remark",
		"create_by":        "CreateBy",
		"create_time":      "CreateTime",
		"update_by":        "UpdateBy",
		"update_time":      "UpdateTime",
	},
}

// NeHostImpl 网元主机连接 数据层处理
type NeHostImpl struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *NeHostImpl) convertResultRows(rows []map[string]any) []model.NeHost {
	arr := make([]model.NeHost, 0)
	for _, row := range rows {
		item := model.NeHost{}
		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 *NeHostImpl) SelectPage(query map[string]any) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if v, ok := query["hostType"]; ok && v != "" {
		conditions = append(conditions, "host_type = ?")
		params = append(params, strings.Trim(v.(string), " "))
	}
	if v, ok := query["groupId"]; ok && v != "" {
		conditions = append(conditions, "group_id = ?")
		params = append(params, strings.Trim(v.(string), " "))
	}
	if v, ok := query["title"]; ok && v != "" {
		conditions = append(conditions, "title 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.NeHost{},
	}

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from ne_host"
	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 + 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 *NeHostImpl) SelectList(neHost model.NeHost) []model.NeHost {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neHost.HostType != "" {
		conditions = append(conditions, "host_type = ?")
		params = append(params, neHost.HostType)
	}
	if neHost.GroupID != "" {
		conditions = append(conditions, "group_id = ?")
		params = append(params, neHost.GroupID)
	}
	if neHost.Title != "" {
		conditions = append(conditions, "title like concat(?, '%')")
		params = append(params, neHost.Title)
	}

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

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

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

// SelectByIds 通过ID查询
func (r *NeHostImpl) SelectByIds(hostIds []string) []model.NeHost {
	placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
	querySql := r.selectSql + " where host_id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(hostIds)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.NeHost{}
	}
	// 转换实体
	rows := r.convertResultRows(results)
	arr := &rows
	for i := range *arr {
		passwordDe, err := crypto.StringDecryptByAES((*arr)[i].Password)
		if err != nil {
			logger.Errorf("selectById %s StringDecryptByAES : %v", (*arr)[i].HostID, err.Error())
			(*arr)[i].Password = ""
		} else {
			(*arr)[i].Password = passwordDe
		}
		privateKeyDe, err := crypto.StringDecryptByAES((*arr)[i].PrivateKey)
		if err != nil {
			logger.Errorf("selectById %s StringDecryptByAES : %v", (*arr)[i].HostID, err.Error())
			(*arr)[i].PrivateKey = ""
		} else {
			(*arr)[i].PrivateKey = privateKeyDe
		}
		passPhraseDe, err := crypto.StringDecryptByAES((*arr)[i].PassPhrase)
		if err != nil {
			logger.Errorf("selectById %s StringDecryptByAES : %v", (*arr)[i].HostID, err.Error())
			(*arr)[i].PassPhrase = ""
		} else {
			(*arr)[i].PassPhrase = passPhraseDe
		}
	}
	return rows
}

// CheckUniqueNeHost 校验主机是否唯一
func (r *NeHostImpl) CheckUniqueNeHost(neHost model.NeHost) string {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neHost.HostType != "" {
		conditions = append(conditions, "host_type = ?")
		params = append(params, neHost.HostType)
	}
	if neHost.GroupID != "" {
		conditions = append(conditions, "group_id = ?")
		params = append(params, neHost.GroupID)
	}
	if neHost.Title != "" {
		conditions = append(conditions, "title = ?")
		params = append(params, neHost.Title)
	}

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

	// 查询数据
	querySql := "select host_id as 'str' from ne_host " + 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 *NeHostImpl) Insert(neHost model.NeHost) string {
	// 参数拼接
	params := make(map[string]any)
	if neHost.HostType != "" {
		params["host_type"] = neHost.HostType
	}
	if neHost.GroupID != "" {
		params["group_id"] = neHost.GroupID
	}
	if neHost.Title != "" {
		params["title"] = neHost.Title
	}
	if neHost.Addr != "" {
		params["addr"] = neHost.Addr
	}
	if neHost.Port > 0 {
		params["port"] = neHost.Port
	}
	if neHost.User != "" {
		params["user"] = neHost.User
	}
	if neHost.AuthMode != "" {
		params["auth_mode"] = neHost.AuthMode
	}
	if neHost.Password != "" {
		passwordEn, err := crypto.StringEncryptByAES(neHost.Password)
		if err != nil {
			logger.Errorf("insert StringEncryptByAES : %v", err.Error())
			return ""
		}
		params["password"] = passwordEn
	}
	if neHost.PrivateKey != "" {
		privateKeyEn, err := crypto.StringEncryptByAES(neHost.PrivateKey)
		if err != nil {
			logger.Errorf("insert StringEncryptByAES : %v", err.Error())
			return ""
		}
		params["private_key"] = privateKeyEn
	}
	if neHost.PassPhrase != "" {
		passPhraseEn, err := crypto.StringEncryptByAES(neHost.PassPhrase)
		if err != nil {
			logger.Errorf("insert StringEncryptByAES : %v", err.Error())
			return ""
		}
		params["pass_phrase"] = passPhraseEn
	}
	if neHost.Remark != "" {
		params["remark"] = neHost.Remark
	}
	if neHost.CreateBy != "" {
		params["create_by"] = neHost.CreateBy
		params["create_time"] = time.Now().UnixMilli()
	}

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into ne_host (" + 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 *NeHostImpl) Update(neHost model.NeHost) int64 {
	// 参数拼接
	params := make(map[string]any)
	if neHost.HostType != "" {
		params["host_type"] = neHost.HostType
	}
	if neHost.GroupID != "" {
		params["group_id"] = neHost.GroupID
	}
	if neHost.Title != "" {
		params["title"] = neHost.Title
	}
	if neHost.Addr != "" {
		params["addr"] = neHost.Addr
	}
	if neHost.Port > 0 {
		params["port"] = neHost.Port
	}
	if neHost.User != "" {
		params["user"] = neHost.User
	}
	if neHost.AuthMode != "" {
		params["auth_mode"] = neHost.AuthMode
	}
	if neHost.Password != "" {
		passwordEn, err := crypto.StringEncryptByAES(neHost.Password)
		if err != nil {
			logger.Errorf("update StringEncryptByAES : %v", err.Error())
			return 0
		}
		params["password"] = passwordEn
	}
	if neHost.PrivateKey != "" {
		privateKeyEn, err := crypto.StringEncryptByAES(neHost.PrivateKey)
		if err != nil {
			logger.Errorf("update StringEncryptByAES : %v", err.Error())
			return 0
		}
		params["private_key"] = privateKeyEn
	}
	if neHost.PassPhrase != "" {
		passPhraseEn, err := crypto.StringEncryptByAES(neHost.PassPhrase)
		if err != nil {
			logger.Errorf("update StringEncryptByAES : %v", err.Error())
			return 0
		}
		params["pass_phrase"] = passPhraseEn
	}
	params["remark"] = neHost.Remark
	if neHost.UpdateBy != "" {
		params["update_by"] = neHost.UpdateBy
		params["update_time"] = time.Now().UnixMilli()
	}

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

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

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