package repository

import (
	"fmt"
	"strings"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/utils/repo"
	"be.ems/src/modules/network_data/model"
)

// 实例化数据层 CDREventImpl 结构体
var NewCDREventImpl = &CDREventImpl{
	selectSql: `select id, ne_type, ne_name, rm_uid, timestamp, cdr_json, created_at from cdr_event`,

	resultMap: map[string]string{
		"id":         "ID",
		"ne_type":    "NeType",
		"ne_name":    "NeName",
		"rm_uid":     "RmUID",
		"timestamp":  "Timestamp",
		"cdr_json":   "CDRJSONStr",
		"created_at": "CreatedAt",
	},
}

// CDREventImpl CDR会话事件 数据层处理
type CDREventImpl struct {
	// 查询视图对象SQL
	selectSql string
	// 结果字段与实体映射
	resultMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *CDREventImpl) convertResultRows(rows []map[string]any) []model.CDREvent {
	arr := make([]model.CDREvent, 0)
	for _, row := range rows {
		item := model.CDREvent{}
		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 *CDREventImpl) SelectPage(querys model.CDREventQuery) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if querys.NeType != "" {
		conditions = append(conditions, "ne_type = ?")
		params = append(params, querys.NeType)
	}
	if querys.RmUID != "" {
		conditions = append(conditions, "rm_uid = ?")
		params = append(params, querys.RmUID)
	}
	if querys.RmUID != "" {
		conditions = append(conditions, "rm_uid = ?")
		params = append(params, querys.RmUID)
	}
	if querys.StartTime != "" {
		conditions = append(conditions, "timestamp >= ?")
		beginDate := date.ParseStrToDate(querys.StartTime, date.YYYY_MM_DD_HH_MM_SS)
		params = append(params, beginDate.Unix())
	}
	if querys.EndTime != "" {
		conditions = append(conditions, "timestamp <= ?")
		endDate := date.ParseStrToDate(querys.EndTime, date.YYYY_MM_DD_HH_MM_SS)
		params = append(params, endDate.Unix())
	}
	if querys.RecordType != "" {
		recordTypes := strings.Split(querys.RecordType, ",")
		placeholder := repo.KeyPlaceholderByQuery(len(recordTypes))
		conditions = append(conditions, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') in (%s)", placeholder))
		for _, recordType := range recordTypes {
			params = append(params, recordType)
		}
	}

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

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

	// 查询数量 长度为0直接返回
	totalSql := "select count(1) as 'total' from cdr_event"
	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(querys.PageNum, querys.PageSize)
	pageSql := " limit ?,? "
	params = append(params, pageNum*pageSize)
	params = append(params, pageSize)

	// 排序
	orderSql := ""
	if querys.SortField != "" {
		sortSql := querys.SortField
		if querys.SortOrder != "" {
			if querys.SortOrder == "desc" {
				sortSql += " desc "
			} else {
				sortSql += " asc "
			}
		}
		orderSql = fmt.Sprintf(" order by id desc, %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
}

// SelectByIds 通过ID查询
func (r *CDREventImpl) SelectByIds(cdrIds []string) []model.CDREvent {
	placeholder := repo.KeyPlaceholderByQuery(len(cdrIds))
	querySql := r.selectSql + " where id in (" + placeholder + ")"
	parameters := repo.ConvertIdsSlice(cdrIds)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		logger.Errorf("query err => %v", err)
		return []model.CDREvent{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

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