package repository

import (
	"strings"

	"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/trace/model"
)

// 实例化数据层 TraceData 结构体
var NewTraceData = &TraceData{
	selectSql: `select id, task_id, imsi, msisdn, src_addr, dst_addr, if_type, msg_type, msg_direct, length, timestamp, raw_msg, dec_msg from trace_data`,

	resultMap: map[string]string{
		"id":         "ID",
		"task_id":    "TaskId",
		"imsi":       "IMSI",
		"msisdn":     "MSISDN",
		"src_addr":   "SrcAddr",
		"dst_addr":   "DstAddr",
		"if_type":    "IfType",
		"msg_type":   "MsgType",
		"msg_direct": "MsgDirect",
		"length":     "Length",
		"timestamp":  "Timestamp",
		"raw_msg":    "RawMsg",
		"dec_msg":    "DecMsg",
	},
}

// CDREventIMSImpl 跟踪_任务给HRL网元 数据层处理
type TraceData struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *TraceData) convertResultRows(rows []map[string]any) []model.TraceData {
	arr := make([]model.TraceData, 0)
	for _, row := range rows {
		item := model.TraceData{}
		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 *TraceData) 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(?, '%')")
		params = append(params, v)
	}
	if v, ok := query["msisdn"]; ok && v != "" {
		conditions = append(conditions, "msisdn like concat(?, '%')")
		params = append(params, v)
	}
	if v, ok := query["startTime"]; ok && v != "" {
		conditions = append(conditions, "timestamp >= ?")
		params = append(params, v)
	}
	if v, ok := query["endTime"]; ok && v != "" {
		conditions = append(conditions, "timestamp <= ?")
		params = append(params, v)
	}

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

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

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

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

// SelectList 根据实体查询
func (r *TraceData) SelectList(data model.TraceData) []model.TraceData {
	// 查询条件拼接
	var conditions []string
	var params []any
	if data.IMSI != "" {
		conditions = append(conditions, "imsi = ?")
		params = append(params, data.IMSI)
	}
	if data.MSISDN != "" {
		conditions = append(conditions, "msisdn = ?")
		params = append(params, data.MSISDN)
	}

	// 构建查询条件语句
	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 *TraceData) SelectByIds(ids []string) []model.TraceData {
	placeholder := repo.KeyPlaceholderByQuery(len(ids))
	querySql := r.selectSql + " where id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(ids)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.TraceData{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

// Insert 新增信息
func (r *TraceData) Insert(data model.TraceData) string {
	// 参数拼接
	params := make(map[string]any)
	if data.TaskId > 0 {
		params["task_id"] = data.TaskId
	}
	if data.IMSI != "" {
		params["imsi"] = data.IMSI
	}
	if data.MSISDN != "" {
		params["msisdn"] = data.MSISDN
	}
	if data.SrcAddr != "" {
		params["src_addr"] = data.SrcAddr
	}
	if data.DstAddr != "" {
		params["dst_addr"] = data.DstAddr
	}
	if data.IfType > -1 {
		params["if_type"] = data.IfType
	}
	if data.MsgType > -1 {
		params["msg_type"] = data.MsgType
	}
	if data.MsgDirect > -1 {
		params["msg_direct"] = data.MsgDirect
	}
	if data.Length > 0 {
		params["length"] = data.Length
	}
	if data.Timestamp > 0 {
		params["timestamp"] = data.Timestamp
	}
	if data.RawMsg != "" {
		params["raw_msg"] = data.RawMsg
	}
	if data.DecMsg != "" {
		params["dec_msg"] = data.DecMsg
	}

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into trace_data (" + 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
}

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