/*
 * @description: 编号规则数据库操作相关
 * @Author: LanJianRong
 * @Date: 2020-11-27
 * @FilePath: \construction_management\dao\rule_dao.go
 */

package dao

import (
	"fmt"

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

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

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

// 通过项目id和标段id查找
func (d *RuleDao) FindByPidWithBid(pid int, bid int) *models.CmRule {
	data := &models.CmRule{BidsectionId: bid, ProjectId: pid}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

// 根据pid和bid更新、不存在则创建
func (d *RuleDao) UpdateOrCreate(pid int, bid int, key string, value string) error {
	data := &models.CmRule{BidsectionId: bid, ProjectId: pid}
	has, err := d.engine.Get(data)
	if key == "safe_rule" {
		data.SafeRule = value
	} else if key == "quality_rule" {
		data.QualityRule = value
	} else {
		data.ContractRule = value
	}
	// fmt.Println("newData", data, "value", value, "key", key)
	if has && err == nil {
		_, err := d.engine.Id(data.Id).Update(data)
		fmt.Println("err2", err)
		return err
	} else if !has && err == nil {
		_, err := d.engine.Insert(data)
		fmt.Println("err3", err)
		return err
	}
	fmt.Println(err)
	return err
}
