package repository

import (
	"fmt"
	"strings"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/network_data/model"
)

// 实例化数据层 CDREventMF 结构体
var NewCDREventMF = &CDREventMF{}

// CDREventMF CDR会话事件 数据层处理
type CDREventMF struct{}

// SelectByPage 分页查询集合
func (r CDREventMF) SelectByPage(querys model.CDREventMFQuery) ([]model.CDREventMF, int64) {
	tx := datasource.DB("").Model(&model.CDREventMF{})
	// 查询条件拼接
	if querys.NeType != "" {
		tx = tx.Where("ne_type = ?", querys.NeType)
	}
	if querys.RmUID != "" {
		tx = tx.Where("rm_uid = ?", querys.RmUID)
	}
	if querys.StartTime != 0 {
		startTime := fmt.Sprintf("%d", querys.StartTime)
		if len(startTime) == 13 {
			startTime = startTime[:10]
		}
		tx = tx.Where("timestamp >= ?", startTime)
	}
	if querys.EndTime != 0 {
		endTime := fmt.Sprintf("%d", querys.EndTime)
		if len(endTime) == 13 {
			endTime = endTime[:10]
		}
		tx = tx.Where("timestamp <= ?", endTime)
	}
	if querys.CallerParty != "" {
		tx = tx.Where("JSON_EXTRACT(cdr_json, '$.callerParty') = ?", querys.CallerParty)
	}
	if querys.CalledParty != "" {
		tx = tx.Where("JSON_EXTRACT(cdr_json, '$.calledParty') = ?", querys.CalledParty)
	}

	if querys.RecordType != "" {
		recordTypes := strings.Split(querys.RecordType, ",")
		var queryStrArr []string
		for _, recordType := range recordTypes {
			queryStrArr = append(queryStrArr, fmt.Sprintf("JSON_EXTRACT(cdr_json, '$.recordType') = '%s'", recordType))
		}
		tx = tx.Where(fmt.Sprintf("( %s )", strings.Join(queryStrArr, " OR ")))
	}

	// 查询结果
	var total int64 = 0
	rows := []model.CDREventMF{}

	// 查询数量为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 排序
	if querys.SortField != "" {
		sortField := querys.SortField
		if querys.SortOrder == "desc" {
			sortField = sortField + " desc"
		}
		tx = tx.Order(sortField)
	}

	// 查询数据分页
	pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.PageSize)
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
	err := tx.Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询
func (r *CDREventMF) SelectByIds(ids []string) []model.CDREventMF {
	rows := []model.CDREventMF{}
	if len(ids) <= 0 {
		return rows
	}
	tx := datasource.DB("").Model(&model.CDREventMF{})
	// 构建查询条件
	tx = tx.Where("id in ?", ids)
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// DeleteByIds 批量删除信息
func (r *CDREventMF) DeleteByIds(ids []string) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := datasource.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.CDREventMF{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}
