package repository

import (
	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/chart/model"
)

// 实例化数据层 ChartGraph 结构体
var NewChartGraph = &ChartGraph{}

// ChartGraph G6关系图数据表 数据层处理
type ChartGraph struct{}

// SelectByPage 分页查询集合
func (r ChartGraph) SelectByPage(query map[string]string) ([]model.ChartGraph, int64) {
	tx := db.DB("").Model(&model.ChartGraph{})
	// 查询条件拼接
	if v, ok := query["rowType"]; ok && v != "" {
		tx = tx.Where("row_type = ?", v)
	}
	if v, ok := query["rowGroup"]; ok && v != "" {
		tx = tx.Where("row_group = ?", v)
	}

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

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

	// 查询数据分页
	pageNum, pageSize := db.PageNumSize(query["pageNum"], query["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
}

// Select 查询集合
func (r ChartGraph) Select(param model.ChartGraph) []model.ChartGraph {
	tx := db.DB("").Model(&model.ChartGraph{})
	// 查询条件拼接
	if param.RowType != "" {
		tx = tx.Where("row_type = ?", param.RowType)
	}
	if param.RowGroup != "" {
		tx = tx.Where("row_group = ?", param.RowGroup)
	}

	// 查询数据
	rows := []model.ChartGraph{}
	if err := tx.Order("depth asc").Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// SelectGroup 查询组名
func (r ChartGraph) SelectGroup() []string {
	tx := db.DB("").Model(&model.ChartGraph{})
	// 查询数据
	rows := []string{}
	if err := tx.Select("row_group").Group("row_group").Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// Insert 批量添加
func (r ChartGraph) Inserts(graphs []model.ChartGraph) int64 {
	tx := db.DB("").CreateInBatches(graphs, 500)
	if err := tx.Error; err != nil {
		logger.Errorf("CreateInBatches err => %v", err)
	}
	return tx.RowsAffected
}

// Delete 删除组数据
func (r ChartGraph) DeleteGroup(rowGroup string) int64 {
	tx := db.DB("").Where("row_group = ?", rowGroup).Delete(&model.ChartGraph{})
	if err := tx.Error; err != nil {
		logger.Errorf("Delete err => %v", err)
	}
	return tx.RowsAffected
}
