/*
 * @description: 标段-数据库操作
 * @Author: CP
 * @Date: 2020-09-28 10:35:56
 * @FilePath: \construction_management\dao\bidsection_dao.go
 */
package dao

import (
	"errors"
	"time"

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

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

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

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

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

//创建
func (d *BidsectionDao) Create(data *models.CmTree) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("创建标段出错-db")
	}

	// 创建标段
	bidsection := &models.CmBidsection{}
	bidsection.ProjectId = data.ProjectId
	bidsection.Name = data.Name
	bidsection.CreateTime = time.Now()
	bidsection.DealTp = "0"
	bidsection.TotalPrice = "0"
	_, err = session.Insert(bidsection)
	if err != nil {
		session.Rollback()
		return errors.New("标段创建不正确")
	}
	// 创建标段在树结构中的联系
	data.BidsectionId = bidsection.Id
	data.ContractsIncome = "0"
	data.ContractsPaid = "0"
	data.ContractsPay = "0"
	data.ContractsReturned = "0"
	_, err = session.Insert(data)
	if err != nil {
		session.Rollback()
		return errors.New("创建标段联系出错-db")
	}

	err = session.Commit()
	if err != nil {
		session.Rollback()
		return errors.New("创建标段出错-db")
	}

	return nil
}
