/*
 * @description:工程项目数据库操作
 * @Author: CP
 * @Date: 2020-09-03 14:40:06
 * @FilePath: \construction_management\dao\project_dao.go
 */
package dao

import (
	"errors"

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

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

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

//CmProjectAccount 设置的值获得数据
// func (d *ProjectDao) Get(data *models.CmProject) {
// 	//data := data
// 	ok, err := d.engine.Get(data)
// 	if ok && err == nil {
// 		//return nil
// 	} else {
// 		data.Id = 0
// 		//return err
// 	}
// }

func (d *ProjectDao) GetPage(page int, size int) []models.CmProject {
	datalist := make([]models.CmProject, 0)
	if page == 1 {
		page = 0
	} else {
		page--
		page = page * size
	}
	// Where("project_id = ? and bidsection_id =? and contracts_id=?", projectId, bidsectionId, contractsId).
	_ = d.engine.
		Limit(size, page).
		Find(&datalist)
	return datalist
}

//设置的值获得数据
func (d *ProjectDao) GetCode(code string) *models.CmProject {
	data := &models.CmProject{}
	ok, err := d.engine.
		Where("code = ?", code).
		Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

// 获得一组项目数据
func (d *ProjectDao) GetListByCode(code string) []models.CmProject {
	datalist := make([]models.CmProject, 0)

	err := d.engine.
		Where("code = ?", code).
		Desc("id").
		Find(&datalist)
	if err != nil {
		return datalist
	} else {
		return datalist
	}
}

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

//更新
func (d *ProjectDao) Update(data *models.CmProject, columns []string) error {
	//_, err := d.engine.Id(data.Id).MustCols(columns...).Update(data)
	is, err := d.engine.Where("id = ?  ", data.Id).MustCols(columns...).Update(data)
	if is == 0 {
		return errors.New("未找到项目")
	}
	return err
}

func (d *ProjectDao) FindById(id int) (*models.CmProject, error) {
	data := &models.CmProject{}
	_, err := d.engine.Where("id=?", id).Get(data)
	return data, err
}
