package chart_permission_chapter_mapping

import (
	"github.com/beego/beego/v2/client/orm"
	"hongze/hongze_open_api/utils"
)

type ChartPermissionChapterMapping struct {
	Id                  int    `orm:"column(id);pk"`
	ChartPermissionId   int    `description:"权限ID"`
	ReportChapterTypeId int    `description:"report_chapter_type表主键id或research_report表主键id或tactic表主键id"`
	ResearchType        string `description:"报告类型 week;two_week;tactic;month;other;rddp; "`
}

// GetReportChapterTypeIdsByPermissionIds 根据权限ID筛选报告分类ID， rddp 类型表示新后台新增的报告，区分老后台
func GetReportChapterTypeIdsByPermissionIds(permissionIds []int, researchType string) (reportIds []int, err error) {
	lenNum := len(permissionIds)
	if lenNum < 0 {
		return
	}
	var charPermissionMapping []*ChartPermissionChapterMapping
	o := orm.NewOrm()
	sql := "SELECT DISTINCT report_chapter_type_id from chart_permission_chapter_mapping WHERE chart_permission_id in (" + utils.GetOrmInReplace(lenNum) + ") and research_type = ?"
	_, err = o.Raw(sql, permissionIds, researchType).QueryRows(&charPermissionMapping)
	if err != nil {
		return
	}
	for _, v := range charPermissionMapping {
		reportIds = append(reportIds, v.ReportChapterTypeId)
	}
	return
}

// GetPermissionIdsByReportId 根据报告获取品种权限id
func GetPermissionIdsByReportId(reportId int, researchType string) (ids []int, err error) {
	o := orm.NewOrm()
	var list []*ChartPermissionChapterMapping

	sql := "SELECT DISTINCT chart_permission_id from chart_permission_chapter_mapping WHERE report_chapter_type_id = ? and research_type = ?"
	_, err = o.Raw(sql, reportId, researchType).QueryRows(&list)
	if err != nil {
		return
	}

	if len(list) > 0 {
		for _, item := range list {
			ids = append(ids, item.ChartPermissionId)
		}
	}
	return
}

// GetPermissionIdsByWeek 根据周度报告获取品种权限id
func GetPermissionIdsByWeek() (ids []int, err error) {
	o := orm.NewOrm()
	var list []*ChartPermissionChapterMapping

	sql := `SELECT DISTINCT chart_permission_id from chart_permission_chapter_mapping WHERE  research_type = "week" `
	_, err = o.Raw(sql).QueryRows(&list)
	if err != nil {
		return
	}

	if len(list) > 0 {
		for _, item := range list {
			ids = append(ids, item.ChartPermissionId)
		}
	}
	return
}
