package repository

import (
	"fmt"
	"strings"
	"time"

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

// 实例化数据层 NewNeSoftware 结构体
var NewNeSoftwareImpl = &NeSoftwareImpl{
	selectSql: `select 
	id, ne_type, file_name, path, version, md5_sum, status, comment, update_time 
	from ne_software`,

	resultMap: map[string]string{
		"id":          "ID",
		"ne_type":     "NeType",
		"file_name":   "FileName",
		"path":        "Path",
		"version":     "Version",
		"md5_sum":     "Md5Sum",
		"status":      "Status",
		"comment":     "Comment",
		"update_time": "UpdateTime",
	},
}

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

// convertResultRows 将结果记录转实体结果组
func (r *NeSoftwareImpl) convertResultRows(rows []map[string]any) []model.NeSoftware {
	arr := make([]model.NeSoftware, 0)
	for _, row := range rows {
		item := model.NeSoftware{}
		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 *NeSoftwareImpl) 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["fileName"]; ok && v != "" {
		conditions = append(conditions, "file_name like concat(?, '%')")
		params = append(params, strings.Trim(v.(string), " "))
	}
	if v, ok := query["version"]; ok && v != "" {
		conditions = append(conditions, "version 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_software"
	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 := " order by id desc 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 *NeSoftwareImpl) SelectList(neSoftware model.NeSoftware) []model.NeSoftware {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neSoftware.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, neSoftware.NeType)
	}
	if neSoftware.Path != "" {
		conditions = append(conditions, "path = ?")
		params = append(params, neSoftware.Path)
	}
	if neSoftware.Version != "" {
		conditions = append(conditions, "version = ?")
		params = append(params, neSoftware.Version)
	}
	if neSoftware.FileName != "" {
		conditions = append(conditions, "file_name like concat(?, '%')")
		params = append(params, neSoftware.FileName)
	}

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

	// 查询数据
	querySql := r.selectSql + whereSql + " order by 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 *NeSoftwareImpl) SelectByIds(cmdIds []string) []model.NeSoftware {
	placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
	querySql := r.selectSql + " where id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(cmdIds)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.NeSoftware{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

// CheckUniqueTypeAndFileNameAndVersion 校验网元类型和文件名版本是否唯一
func (r *NeSoftwareImpl) CheckUniqueTypeAndFileNameAndVersion(neSoftware model.NeSoftware) string {
	// 查询条件拼接
	var conditions []string
	var params []any
	if neSoftware.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, neSoftware.NeType)
	}
	if neSoftware.Version != "" {
		conditions = append(conditions, "version = ?")
		params = append(params, neSoftware.Version)
	}
	if neSoftware.FileName != "" {
		conditions = append(conditions, "file_name = ?")
		params = append(params, neSoftware.FileName)
	}

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

	// 查询数据
	querySql := "select id as 'str' from ne_software " + 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 *NeSoftwareImpl) Insert(neSoftware model.NeSoftware) string {
	// 参数拼接
	params := make(map[string]any)
	if neSoftware.NeType != "" {
		params["ne_type"] = neSoftware.NeType
	}
	if neSoftware.FileName != "" {
		params["file_name"] = neSoftware.FileName
	}
	if neSoftware.Path != "" {
		params["path"] = neSoftware.Path
	}
	if neSoftware.Version != "" {
		params["version"] = neSoftware.Version
	}
	if neSoftware.Md5Sum != "" {
		params["md5_sum"] = neSoftware.Md5Sum
	}
	if neSoftware.Status != "" {
		params["status"] = neSoftware.Status
	}
	if neSoftware.Comment != "" {
		params["comment"] = neSoftware.Comment
	}
	if neSoftware.Status != "" {
		params["status"] = neSoftware.Status
	}
	params["update_time"] = time.Now()

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into ne_software (" + 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 *NeSoftwareImpl) Update(neSoftware model.NeSoftware) int64 {
	// 参数拼接
	params := make(map[string]any)
	if neSoftware.NeType != "" {
		params["ne_type"] = neSoftware.NeType
	}
	if neSoftware.FileName != "" {
		params["file_name"] = neSoftware.FileName
	}
	if neSoftware.Path != "" {
		params["path"] = neSoftware.Path
	}
	if neSoftware.Version != "" {
		params["version"] = neSoftware.Version
	}
	if neSoftware.Md5Sum != "" {
		params["md5_sum"] = neSoftware.Md5Sum
	}
	if neSoftware.Status != "" {
		params["status"] = neSoftware.Status
	}
	if neSoftware.Comment != "" {
		params["comment"] = neSoftware.Comment
	}
	if neSoftware.Status != "" {
		params["status"] = neSoftware.Status
	}
	params["update_time"] = time.Now()

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

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

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