package models

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

type EnClassifyPermission struct {
	EnClassifyPermissionId int       `orm:"column(en_classify_permission_id);pk" description:"英文品种权限ID"`
	EnClassifyId           int       `description:"英文分类ID"`
	EnPermissionId         int       `description:"英文品种ID"`
	CreateTime             time.Time `description:"创建时间"`
}

var EnClassifyPermissionColumns = struct {
	EnClassifyPermissionId string
	EnClassifyId           string
	EnPermissionId         string
	CreateTime             string
}{
	EnClassifyPermissionId: "en_classify_permission_id",
	EnClassifyId:           "en_classify_id",
	EnPermissionId:         "en_permission_id",
	CreateTime:             "create_time",
}

func (m *EnClassifyPermission) TableName() string {
	return "en_classify_permission"
}

func (m *EnClassifyPermission) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EnClassifyPermissionId = int(id)
	return
}

func (m *EnClassifyPermission) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(m, cols...)
	return
}

func (m *EnClassifyPermission) Del() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnClassifyPermissionColumns.EnClassifyPermissionId)
	_, err = o.Raw(sql, m.EnClassifyPermissionId).Exec()
	return
}

func (m *EnClassifyPermission) GetItemById(id int) (item *EnClassifyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnClassifyPermissionColumns.EnClassifyPermissionId)
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *EnClassifyPermission) GetItemByCondition(condition string, pars []interface{}) (item *EnClassifyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 `, m.TableName())
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *EnClassifyPermission) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *EnClassifyPermission) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*EnClassifyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *EnClassifyPermission) GetPageItemsByCondition(startSize, pageSize int, condition string, pars []interface{}, fieldArr []string, orderRule string) (total int, items []*EnClassifyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSql, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

func ClearAndCreateEnClassifyPermissions(classifyId int, permissions []*EnClassifyPermission) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `DELETE FROM en_classify_permission WHERE en_classify_id = ?`
	if _, e := o.Raw(sql, classifyId).Exec(); e != nil {
		err = fmt.Errorf("delete err: %s", e.Error())
		return
	}
	if len(permissions) > 0 {
		if _, e := o.InsertMulti(len(permissions), permissions); e != nil {
			err = fmt.Errorf("insert multi err: %s", e.Error())
			return
		}
	}
	return
}

func CreateEnClassifyPermissions(permissions []*EnClassifyPermission) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	if len(permissions) > 0 {
		if _, e := o.InsertMulti(len(permissions), permissions); e != nil {
			err = fmt.Errorf("insert multi err: %s", e.Error())
			return
		}
	}
	return
}

type EnClassifyPermissionEditReq struct {
	ClassifyId    int   `description:"分类ID"`
	EnPermissions []int `description:"权限IDs"`
}

// GetEnglishReportIdsByEnPermissionIds 根据权限IDs获取报告IDs
func GetEnglishReportIdsByEnPermissionIds(permissionIds []int) (reportIds []int, err error) {
	if len(permissionIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT id FROM english_report WHERE classify_id_second IN (
				SELECT DISTINCT en_classify_id FROM en_classify_permission WHERE en_permission_id IN (` + utils.GetOrmInReplace(len(permissionIds)) + `)
			)`
	_, err = o.Raw(sql, permissionIds).QueryRows(&reportIds)
	return
}

// GetEnPermissionIdsByEnglishReportId 获取英文报告权限IDs
func GetEnPermissionIdsByEnglishReportId(reportId int) (permissionIds []int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT en_permission_id FROM en_classify_permission WHERE en_classify_id = (
				SELECT classify_id_second FROM english_report WHERE id = ?
			)`
	_, err = o.Raw(sql, reportId).QueryRows(&permissionIds)
	return
}

// GetEnPermissionIdsByEnglishVideoId 获取英文视频权限IDs
func GetEnPermissionIdsByEnglishVideoId(videoId int) (permissionIds []int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT en_permission_id FROM en_classify_permission WHERE en_classify_id = (
				SELECT classify_id_second FROM english_video WHERE id = ?
			)`
	_, err = o.Raw(sql, videoId).QueryRows(&permissionIds)
	return
}
