package repository

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

// 实例化数据层 TraceTask 结构体
var NewTraceTask = &TraceTask{
	selectSql: `select id, trace_id, trace_type, start_time, end_time, 
	interfaces, imsi, msisdn, 
	ue_ip, src_ip, dst_ip, signal_port, 
	create_by, create_time, update_by, update_time, remark, 
	ne_type, ne_id, notify_url, fetch_msg 
	from trace_task`,

	resultMap: map[string]string{
		"id":          "ID",
		"trace_id":    "TraceId",
		"trace_type":  "TraceType",
		"start_time":  "StartTime",
		"end_time":    "EndTime",
		"interfaces":  "Interfaces",
		"imsi":        "IMSI",
		"msisdn":      "MSISDN",
		"ue_ip":       "UeIp",
		"src_ip":      "SrcIp",
		"dst_ip":      "DstIp",
		"signal_port": "SignalPort",
		"create_by":   "CreateBy",
		"create_time": "CreateTime",
		"update_by":   "UpdateBy",
		"update_time": "UpdateTime",
		"remark":      "Remark",
		"ne_type":     "NeType",
		"ne_id":       "NeId",
		"notify_url":  "NotifyUrl",
		"fetch_msg":   "FetchMsg",
	},
}

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

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

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

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

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

	// 排序
	orderSql := ""
	if v, ok := query["sortField"]; ok && v != "" {
		sortSql := v.(string)
		if v, ok := query["sortOrder"]; ok && v != "" {
			if v.(string) == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		orderSql = fmt.Sprintf(" order by %s ", sortSql)
	}

	// 查询数据
	querySql := r.selectSql + whereSql + orderSql + 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 *TraceTask) SelectList(task model.TraceTask) []model.TraceTask {
	// 查询条件拼接
	var conditions []string
	var params []any
	if task.IMSI != "" {
		conditions = append(conditions, "imsi = ?")
		params = append(params, task.IMSI)
	}
	if task.SrcIp != "" {
		conditions = append(conditions, "src_ip = ?")
		params = append(params, task.SrcIp)
	}
	if task.DstIp != "" {
		conditions = append(conditions, "dst_ip = ?")
		params = append(params, task.DstIp)
	}

	// 构建查询条件语句
	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 *TraceTask) SelectByIds(ids []string) []model.TraceTask {
	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.TraceTask{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

// Insert 新增信息
func (r *TraceTask) Insert(task model.TraceTask) string {
	// 参数拼接
	params := make(map[string]any)
	if task.TraceId != "" {
		params["trace_id"] = task.TraceId
	}
	if task.TraceType != "" {
		params["trace_type"] = task.TraceType
	}
	if task.StartTime > 0 {
		params["start_time"] = task.StartTime
	}
	if task.EndTime > 0 {
		params["end_time"] = task.EndTime
	}
	if task.Interfaces != "" {
		params["interfaces"] = task.Interfaces
	}
	if task.IMSI != "" {
		params["imsi"] = task.IMSI
	}
	if task.MSISDN != "" {
		params["msisdn"] = task.MSISDN
	}
	if task.UeIp != "" {
		params["ue_ip"] = task.UeIp
	}
	if task.SrcIp != "" {
		params["src_ip"] = task.SrcIp
	}
	if task.DstIp != "" {
		params["dst_ip"] = task.DstIp
	}
	if task.SignalPort != 0 {
		params["signal_port"] = task.SignalPort
	}
	if task.NeType != "" {
		params["ne_type"] = task.NeType
	}
	if task.NeId != "" {
		params["ne_id"] = task.NeId
	}
	if task.NotifyUrl != "" {
		params["notify_url"] = task.NotifyUrl
	}
	if task.FetchMsg != "" {
		params["fetch_msg"] = task.FetchMsg
	}
	if task.Remark != "" {
		params["remark"] = task.Remark
	}
	if task.CreateBy != "" {
		params["create_by"] = task.CreateBy
		params["create_time"] = time.Now().UnixMilli()
	}

	// 构建执行语句
	keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
	sql := "insert into trace_task (" + 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 *TraceTask) Update(task model.TraceTask) int64 {
	// 参数拼接
	params := make(map[string]any)
	params["trace_id"] = task.TraceId
	params["trace_type"] = task.TraceType
	params["ne_type"] = task.NeType
	params["ne_id"] = task.NeId
	params["notify_url"] = task.NotifyUrl

	params["start_time"] = task.StartTime
	params["end_time"] = task.EndTime
	params["fetch_msg"] = task.FetchMsg
	params["remark"] = task.Remark

	params["interfaces"] = task.Interfaces

	params["imsi"] = task.IMSI
	params["msisdn"] = task.MSISDN

	params["ue_ip"] = task.UeIp
	params["src_ip"] = task.SrcIp
	params["dst_ip"] = task.DstIp
	params["signal_port"] = task.SignalPort

	if task.UpdateBy != "" {
		params["update_by"] = task.UpdateBy
		params["update_time"] = time.Now().UnixMilli()
	}

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

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

// DeleteByIds 批量删除信息
func (r *TraceTask) DeleteByIds(ids []string) int64 {
	placeholder := repo.KeyPlaceholderByQuery(len(ids))
	sql := "delete from trace_task 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
}

// LastID 最后一条ID
func (r *TraceTask) LastID() int64 {
	// 查询数据
	querySql := "SELECT id as 'str' FROM trace_task ORDER BY id DESC LIMIT 1"
	results, err := datasource.RawDB("", querySql, nil)
	if err != nil {
		logger.Errorf("query err %v", err)
		return 0
	}
	if len(results) > 0 {
		return parse.Number(results[0]["str"])
	}
	return 0
}
