package manage

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

func GetDictDataById(id int64) (domain.DictData, error) {
	var dictData domain.DictData
	_, err := configs.Engine.Table("dict_data").Where("id = ?", id).Get(&dictData)
	if err != nil {
		return dictData, err
	}
	return dictData, nil
}

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

func GetDictDataList(dictData domain.DictData, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.DictData
	Count, err := configs.Engine.Table("dict_data").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &dictData)
	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 SaveDictData(dictData *domain.DictData) (domain.DictData, error) {
	_, err := configs.Engine.Table("dict_data").Insert(&dictData)
	if err != nil {
		return *dictData, err
	}
	return *dictData, nil
}

func SetDictData(dictDataMap map[string]interface{}, id int64) (domain.DictData, bool, error) {
	var dictData domain.DictData
	_, err := configs.Engine.Table("dict_data").Where("id = ?", id).Update(dictDataMap)
	if err != nil {
		return dictData, false, err
	}
	return dictData, true, nil
}

func DeleteDictData(id int64) bool {
	var dictData domain.DictData
	i, err := configs.Engine.Table("dict_data").Where("id = ?", id).Delete(&dictData)
	if err != nil {
		return false
	}
	return i > 0
}
