/*
 * @description:管理员数据库操作
 * @Author: CP
 * @Date: 2020-08-20 15:55:37
 * @FilePath: \construction_management\dao\manager_dao.go
 */

package dao

import (
	"fmt"

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

//数据库操作引擎
type ManagerDao struct {
	engine *xorm.Engine
}

//获得一个DAO对象
func NewManagerDao(engine *xorm.Engine) *ManagerDao {
	return &ManagerDao{
		engine: engine,
	}
}

//id获得数据
func (d *ManagerDao) Get(id int) *models.CmManager {
	data := &models.CmManager{Id: id}
	//Get取到值后，会自动赋值到data中
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

//获得全部管理员数据
func (d *ManagerDao) GetAll() []models.CmManager {

	datalist := make([]models.CmManager, 0)
	err := d.engine.Asc("created_time").Find(&datalist)
	//Asc("displayorder").
	//Find(&datalist)
	fmt.Println(err)
	if err != nil {
		//log.Println
		return datalist
	} else {
		return datalist
	}
}

//获得总数
func (d *ManagerDao) CountAll() int64 {
	num, err := d.engine.
		Count(&models.CmManager{})
	if err != nil {
		return 0
	} else {
		return num
	}
}

//创建
func (d *ManagerDao) Create(data *models.CmManager) error {
	_, err := d.engine.Insert(data)
	return err
}

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

func (d *ManagerDao) Delete(data *models.CmManager, columns []string) error {
	_, err := d.engine.Id(data.Id).MustCols(columns...).Update(data)
	return err
}
