/*
 * @description: 管理员组数据相关
 * @Author: CP
 * @Date: 2021-06-01 15:04:06
 * @FilePath: \construction_management\dao\group_dao.go
 */
package dao

import (
	"errors"

	"github.com/go-xorm/xorm"
	"go.mod/models"
)

type GroupDao struct {
	engine *xorm.Engine
}

func NewGroupDao(engine *xorm.Engine) *GroupDao {
	return &GroupDao{
		engine: engine,
	}
}

// 新增
func (d *GroupDao) Add(data *models.CmGroup) error {
	_, err := d.engine.Insert(data)
	return err
}

//更新
func (d *GroupDao) Update(data *models.CmGroup, columns []string) error {
	_, err := d.engine.Id(data.Id).Cols(columns...).Update(data)
	return err
}

func (d *GroupDao) Get(id int) *models.CmGroup {
	data := &models.CmGroup{Id: id}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

func (d *GroupDao) GetByName(name string) *models.CmGroup {
	data := &models.CmGroup{Name: name}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

//获得全部管理员数据
func (d *GroupDao) GetAll() (data []models.CmGroup, total int64) {

	num, _ := d.engine.
		Count(&models.CmGroup{})

	datalist := make([]models.CmGroup, 0)
	err := d.engine.Asc("create_time").Find(&datalist)
	//Asc("displayorder").
	//Find(&datalist)

	if err != nil {
		return datalist, num
	} else {
		return datalist, num
	}
}

func (d *GroupDao) Delete(data *models.CmGroup) error {
	_, err := d.engine.Where("id = ?  ", data.Id).Delete(data)
	if err != nil {
		return errors.New("删除到账号失败")
	}
	return nil
}
