package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// ReportGrant Ppt授权表
type ReportGrant struct {
	GrantId      int64     `orm:"column(grant_id);pk;auto" description:"自增序号"`
	ReportId     int64     `description:"report ID"`
	DepartmentId int64     `description:"授权部门id"`
	GrantAdminId int64     `description:"授权部门id"`
	CreateTime   time.Time `orm:"auto_now_add;type(datetime)" description:"创建时间"`
}

// GetReportGrantInfo 获取已经有权限的report列表
func GetReportGrantInfo(reportId int) (list []*ReportGrant, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM report_grant WHERE report_id=? `
	_, err = o.Raw(sql, reportId).QueryRows(&list)
	return
}

// MultiAddReportGrant 批量添加授权记录
func MultiAddReportGrant(reportId int, list []*ReportGrant) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	sql := "DELETE from report_grant where report_id=?"
	_, err = to.Raw(sql, reportId).Exec()
	if err != nil {
		return
	}

	// 新增授权记录
	if len(list) > 0 {
		_, tmpErr := to.InsertMulti(len(list), list)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	return
}

// DeleteReportGrant 移除授权记录
func DeleteReportGrant(reportId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := "DELETE from report_grant where report_id=?"
	_, err = o.Raw(sql, reportId).Exec()

	return
}