package manage

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

func GetDictTypeById(id int64) (domain.DictType, error) {
	var dictType domain.DictType
	_, err := configs.Engine.Table("dict_type").Where("id = ?", id).Get(&dictType)
	if err != nil {
		return dictType, err
	}
	return dictType, nil
}

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

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

func SetDictType(dictTypeMap map[string]interface{}, id int64) (domain.DictType, bool, error) {
	var dictType domain.DictType
	_, err := configs.Engine.Table("dict_type").Where("id = ?", id).Update(dictTypeMap)
	if err != nil {
		return dictType, false, err
	}
	return dictType, true, nil
}

func DeleteDictType(id int64) bool {
	var dictType domain.DictType
	i, err := configs.Engine.Table("dict_type").Where("id = ?", id).Delete(&dictType)
	if err != nil {
		return false
	}
	return i > 0
}
