package report

import (
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// ReportGrant
// @Description: 报告授权用户表
type ReportGrant struct {
	GrantId    int       `orm:"column(grant_id)"` // 授权id
	ReportId   int       `description:"报告id"`
	AdminId    int       `description:"授权的用户id"`
	CreateTime time.Time `description:"授权时间"`
}

// MultiAddReportGrantGrant
// @Description: 批量添加报告授权用户
// @author: Roc
// @receiver m
// @datetime 2024-06-04 15:36:02
// @param reportId int
// @param list []*ReportGrant
// @return err error
func (m ReportGrant) MultiAddReportGrantGrant(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(500, list)
		if tmpErr != nil {
			err = tmpErr
			return
		}
	}

	return
}

// GetGrantListById
// @Description: 根据id获取授权列表
// @author: Roc
// @receiver m
// @datetime 2024-06-04 15:33:58
// @param reportId int
// @return list []*ReportGrant
// @return err error
func (m ReportGrant) GetGrantListById(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
}

// GetGrantListByIdList
// @Description: 根据id列表获取授权列表
// @author: Roc
// @receiver m
// @datetime 2024-06-04 15:33:58
// @param reportIdList []int
// @return list []*ReportGrant
// @return err error
func (m ReportGrant) GetGrantListByIdList(reportIdList []int) (list []*ReportGrant, err error) {
	num := len(reportIdList)
	if num <= 0 {
		return
	}

	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM report_grant WHERE report_id in (` + utils.GetOrmInReplace(num) + `) `
	_, err = o.Raw(sql, reportIdList).QueryRows(&list)

	return
}

// GetGrantByIdAndAdmin
// @Description: 根据reportId和操作人获取报告权限配置
// @author: Roc
// @receiver m
// @datetime 2024-06-04 15:49:59
// @param reportId int
// @param sysUserId int
// @return item *ReportGrant
// @return err error
func (m ReportGrant) GetGrantByIdAndAdmin(reportId, sysUserId int) (item *ReportGrant, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM report_grant WHERE report_id = ? AND admin_id = ? `
	err = o.Raw(sql, reportId, sysUserId).QueryRow(&item)

	return
}

// GetGrantListByAdminId
// @Description: 根据id获取授权列表
// @author: Roc
// @receiver m
// @datetime 2024-06-04 15:33:58
// @param adminId int
// @return list []*ReportGrant
// @return err error
func (m ReportGrant) GetGrantListByAdminId(adminId int) (list []*ReportGrant, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM report_grant WHERE admin_id=? `
	_, err = o.Raw(sql, adminId).QueryRows(&list)

	return
}