package manage

import (
	"demo/configs"
	"demo/data/domain"
	"demo/data/domain/vo"
)

func GetGenTableById(id int64) (domain.GenTable, error) {
	var genTable domain.GenTable
	_, err := configs.Engine.Table("gen_table").Where("id = ?", id).Get(&genTable)
	if err != nil {
		return genTable, err
	}
	return genTable, nil
}

func GetGenTableListInId(ids []int64) ([]domain.GenTable, error) {
	rows, err := configs.Engine.Table("gen_table").In("id", ids).Rows(&domain.GenTable{})
	if err != nil {
		return make([]domain.GenTable, 0), err
	}
	defer rows.Close()
	var list []domain.GenTable
	for rows.Next() {
		var u domain.GenTable
		rows.Scan(&u)
		list = append(list, u)
	}
	return list, nil
}

func GetGenTableList(genTable domain.GenTable, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.GenTable
	Count, err := configs.Engine.Table("gen_table").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &genTable)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, len(arr))
	for i, v := range arr {
		vo.List[i] = v
	}
	vo.Total = int(Count)
	return vo, nil
}

func SaveGenTable(genTable *domain.GenTable) (domain.GenTable, error) {
	_, err := configs.Engine.Table("gen_table").Insert(&genTable)
	if err != nil {
		return *genTable, err
	}
	return *genTable, nil
}

func SetGenTable(genTableMap map[string]interface{}, id int64) (domain.GenTable, bool, error) {
	var genTable domain.GenTable
	_, err := configs.Engine.Table("gen_table").Where("id = ?", id).Update(genTableMap)
	if err != nil {
		return genTable, false, err
	}
	return genTable, true, nil
}

func DeleteGenTable(id int64) bool {
	var genTable domain.GenTable
	i, err := configs.Engine.Table("gen_table").Where("id = ?", id).Delete(&genTable)
	if err != nil {
		return false
	}
	return i > 0
}
