/*
 * @description: 安全巡检数据库操作相关
 * @Author: LanJianRong
 * @Date: 2020-11-20
 * @FilePath: \construction_management\dao\version_dao.go
 */

package dao

import (
	"errors"

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

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

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

//获得标段下的账号数据
func (d *VersionDao) Get() *models.CmVersion {
	data := &models.CmVersion{}
	ok, err := d.engine.
		Desc("id").
		Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

func (d *VersionDao) FindById(id int) *models.CmVersion {
	data := &models.CmVersion{}
	_, err := d.engine.
		Where("id=? ", id).
		Get(data)
	if err != nil {
		data.Id = 0
		return data
	}
	return data
}

// 获得版本更新列表
func (d *VersionDao) GetList(pageData viewmodels.Version) ([]models.CmVersion, int64) {

	page := pageData.Page
	size := pageData.Size
	if page == 1 {
		page = 0
	} else {
		page--
		page = page * size
	}

	datalist := make([]models.CmVersion, 0)
	version := &models.CmVersion{}

	count, _ := d.engine.
		Count(version)
	_ = d.engine.
		Desc("id").
		Find(&datalist)
	return datalist, count
}

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

// 删除
func (d *VersionDao) Delete(id int) error {
	data := &models.CmVersion{}
	is, err := d.engine.Where("id = ? ", id).Delete(data)
	if is == 0 {
		return errors.New("未找到版本信息")
	}
	return err
}
