package dao

import (
	"github.com/shopspring/decimal"
	"server/global"
)

type Borrowing struct {
	global.GVA_MODEL
	Name            string          `json:"name" form:"name" gorm:"comment:支借名称"`
	Applicant       string          `json:"applicant" form:"applicant" gorm:"comment:申请人"`
	ApplicationTime string          `json:"applicationTime" form:"applicationTime" gorm:"comment:申请日期"`
	Charge          int             `json:"charge" form:"charge" gorm:"comment:负责人"`
	User            SysUser         `json:"user" form:"user" gorm:"foreignKey:Charge;references:id;"`
	BorrowingPrice  decimal.Decimal `json:"borrowingPrice" form:"borrowingPrice" gorm:"comment:支借金额;type:decimal(10,2)"`
}

func (Borrowing) TableName() string {
	return "borrowing"
}

// TODO:支借查询

// QueryBorrowingList 查询支借列表
func QueryBorrowingList(limit, offset int, name, time, yearTime string) (borrowing []Borrowing, total int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&Borrowing{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}
	if time != "" {
		db = db.Where("DATE_FORMAT(application_time, '%Y-%m') = ?", time)
	}
	if yearTime != "" {
		db = db.Where("DATE_FORMAT(application_time, '%Y') = ?", yearTime)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("id desc").Limit(limit).Offset(offset).Preload("User").Find(&borrowing).Error
	return borrowing, total, err
}

// QueryBorrowing 查询支借
func QueryBorrowing(id int) (borrowing Borrowing, err error) {
	err = global.GVA_DB.Model(&Borrowing{}).Where("id = ?", id).Preload("User").First(&borrowing).Error
	return borrowing, err
}

// TODO:支借新增

// CreateBorrowing 新增支借
func (b Borrowing) CreateBorrowing() error {
	return global.GVA_DB.Create(&b).Error
}

// TODO:支借修改

// UpdateBorrowing 更新支借
func (b Borrowing) UpdateBorrowing() error {
	return global.GVA_DB.Model(&b).Where("id = ?", b.ID).Updates(&b).Error
}

// TODO:支借删除

// DeleteBorrowing 删除支借
func (b Borrowing) DeleteBorrowing() error {
	return global.GVA_DB.Unscoped().Delete(&b).Error
}
