package models

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

const (
	FiccProductId = 1
)

// ChartPermission 报告权限表
type ChartPermission struct {
	ChartPermissionId     int       `orm:"column(chart_permission_id);pk" description:"问题ID" json:"chart_permission_id"`
	ChartPermissionName   string    `description:"名称" json:"chart_permission_name"`
	PermissionName        string    `description:"权限名" json:"permission_name"`
	Sort                  int       `description:"排序" json:"sort"`
	Enabled               int       `description:"是否可用" json:"enabled"`
	CreatedTime           time.Time `description:"创建时间" json:"created_time"`
	LastUpdatedTime       time.Time `description:"更新时间" json:"last_updated_time"`
	TeleconferenceSort    int       `description:"电话会类型排序" json:"teleconference_sort"`
	Remark                string    `description:"备注" json:"remark"`
	ClassifyName          string    `description:"分类名称" json:"classify_name"`
	ProductName           string    `description:"产品名称" json:"product_name"`
	ProductId             int       `description:"产品ID" json:"product_id"`
	ImageURL              string    `orm:"column(image_url);" description:"图片地址" json:"image_url"`
	ShowType              int       `description:"1:查研观向小程序展示" json:"show_type"`
	IsOther               int       `description:"是否是其他，用于查研观向小程序后台展示" json:"is_other"`
	IsReport              int       `description:"是否是报告，用于查研观向小程序前台报告展示" json:"is_report"`
	CygxAuth              int       `description:"是否是权限，用于查研观向小程序前台权限校验" json:"cygx_auth"`
	PermissionType        int       `description:"1主观，2客观" json:"permission_type"`
	YbImgUrl              string    `description:"研报小程序报告列表icon" json:"yb_img_url"`
	ProductPermissionName string    `description:"种类权限名称" json:"product_permission_name"`
	PriceDrivenState      int       `description:"品种价格驱动开启状态 0-关闭 1-开启" json:"price_driven_state"`
	ImageUrlM             string    `description:"图片地址(查研观向移动端)" json:"image_url_m"`
	ParentId              int       `description:"父级权限id" json:"parent_id"`
	IsPublic              int       `description:"是否是公有权限1:公有权限，0私有权限" json:"is_public"`
}

type ChartPermissionVO struct {
	ChartPermissionId   int       `orm:"column(chart_permission_id);pk" description:"问题ID" json:"chart_permission_id"`
	ChartPermissionName string    `description:"名称" json:"chart_permission_name"`
	PermissionName      string    `description:"权限名" json:"permission_name"`
	Sort                int       `description:"排序" json:"sort"`
	Enabled             int       `description:"是否可用" json:"enabled"`
	CreatedTime         time.Time `description:"创建时间" json:"created_time"`
	LastUpdatedTime     time.Time `description:"更新时间" json:"last_updated_time"`
	ParentId            int       `description:"父级权限id" json:"parent_id"`
	Children            []*ChartPermissionVO
}

type ChartPermissionItem struct {
	PermissionId   int    `description:"品种权限ID"`
	PermissionName string `description:"品种权限名称"`
	ParentId       int    `description:"父级ID"`
	IsPublic       int    `description:"是否是公有权限1:公有权限，0私有权限" `
	Enabled        int    `description:"是否可用：1可用，0不可用" `
	Sort           int    `description:"排序"`
	CreateTime     string `description:"创建时间"`
	Child          []*ChartPermissionItem
}

// Update 更新
func (c *ChartPermission) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(c, cols...)
	return
}

type PermissionAddReq struct {
	PermissionName string `description:"品种权限名称"`
	ParentId       int    `description:"父级ID"`
	Enabled        int    `description:"是否可用 0禁用， 1启用"` //启用，禁用操作会关联二级品种
	IsPublic       int    `description:"是否是公有权限1:公有权限，0私有权限"`
}

type PermissionEditReq struct {
	PermissionId        int    `description:"品种权限Id"` // 如果ID存在，则是更新操作，否则是新增操作
	PermissionName      string `description:"品种权限名称"`
	ParentId            int    `description:"父级ID"`
	Enabled             int    `description:"是否可用 0禁用， 1启用"` //启用，禁用操作会关联二级品种
	IsPublic            int    `description:"是否是公有权限1:公有权限，0私有权限"`
	PublicPermissionIds []int  `description:"公有权限的ID列表"` //一级品种没有公有私有属性
}

type PermissionEnabledReq struct {
	PermissionId int `description:"品种权限Id"`        // 如果ID存在，则是更新操作，否则是新增操作
	Enabled      int `description:"是否可用 0禁用， 1启用"` //启用，禁用操作会关联二级品种
}

type PermissionMoveReq struct {
	PermissionId int `description:"品种id"`
	//	ParentChartPermissionId int `description:"父级品种id"`
	PrevPermissionId int `description:"上一个兄弟节点品种id"`
	NextPermissionId int `description:"下一个兄弟节点品种id"`
}

func (c *ChartPermission) SetEnabled(id, enabled int) (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 := ` UPDATE chart_permission SET enabled =?  WHERE id = ?`
	_, err = to.Raw(sql, enabled, id).Exec()
	if err != nil {
		return
	}
	sql = ` UPDATE chart_permission SET enabled =?  WHERE parent_id = ?`
	_, err = to.Raw(sql, enabled, id).Exec()
	if err != nil {
		return
	}
	return
}

// Create 新增权限
func (c *ChartPermission) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(c)
	if err != nil {
		return
	}
	c.ChartPermissionId = int(id)
	return
}

// SetIsPublic 更新公有私有权限
func (c *ChartPermission) SetIsPublic(ids []int, parentId, isPublic int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `update chart_permission set is_public=? WHERE parent_id = ?  and  chart_permission_id IN (` + utils.GetOrmInReplace(len(ids)) + `)`
	_, err = o.Raw(sql, isPublic, parentId, ids).Exec()
	return
}

// UpdatesByParentId 更新启动禁用
func (c *ChartPermission) UpdateClassifyNameByParentId(parentId int, classifyName string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `update chart_permission set classify_name=? WHERE parent_id = ?`
	_, err = o.Raw(sql, classifyName, parentId).Exec()
	return
}

// SetEnabledByParentId 更新启动禁用
func (c *ChartPermission) SetEnabledByParentId(parentId, enabled int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` UPDATE chart_permission SET enabled =?  WHERE parent_id = ?`
	_, err = o.Raw(sql, enabled, parentId).Exec()
	return
}

// SetEnabledByChartPermissionId 更新启动禁用
func (c *ChartPermission) SetEnabledByChartPermissionId(chartPermissionId, enabled int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` UPDATE chart_permission SET enabled =?  WHERE chart_permission_id = ?`
	_, err = o.Raw(sql, enabled, chartPermissionId).Exec()
	return
}

// GetItemById 查询品种
func (c *ChartPermission) GetItemById(chartPermissionId int) (item *ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select * from chart_permission WHERE chart_permission_id = ?`
	err = o.Raw(sql, chartPermissionId).QueryRow(&item)
	return
}

// GetItemsByCondition 查询列表
func (c *ChartPermission) GetItemsByCondition(condition string, pars []interface{}) (items []*ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select * from chart_permission WHERE 1=1 ` + condition + ` order by sort asc, chart_permission_id asc`
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// GetItemByCondition 查询列表
func (c *ChartPermission) GetItemByCondition(condition string, pars []interface{}) (item *ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select * from chart_permission WHERE 1=1 ` + condition
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

// UpdateChartPermissionSortByParentId 根据父类id更新排序
func UpdateChartPermissionSortByParentId(parentId, chartPermissionId, nowSort int, updateSort string, productId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := ` update chart_permission set sort = ` + updateSort + ` WHERE parent_id=? AND product_id = ? AND (sort > ? `
	if chartPermissionId > 0 {
		sql += ` or ( chart_permission_id > ` + fmt.Sprint(chartPermissionId) + ` and sort = ` + fmt.Sprint(nowSort) + `))`
	} else {
		sql += `)`
	}
	_, err = o.Raw(sql, parentId, productId, nowSort).Exec()
	return
}

// GetMaxSort 获取最大的排序值
func (c *ChartPermission) GetMaxSort() (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select max(sort) from chart_permission `
	err = o.Raw(sql).QueryRow(&maxSort)
	return
}

// GetMaxSortByParentId 获取最大的排序值
func (c *ChartPermission) GetMaxSortByParentId(parentId int) (maxSort int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select max(sort) from chart_permission WHERE parent_id=? `
	err = o.Raw(sql, parentId).QueryRow(&maxSort)
	return
}

// GetFirstChartPermissionByParentId 获取当前父级分类下，且排序数相同 的排序第一条的数据
func (c *ChartPermission) GetFirstChartPermissionByParentId(parentId int) (item *ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `select * from chart_permission WHERE parent_id=? ORDER BY sort ASC, chart_permission_id ASC LIMIT 1`
	err = o.Raw(sql, parentId).QueryRow(&item)
	return
}

// GetChartPermissionById 主键获取品种
func GetChartPermissionById(permissionId int) (item *ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE chart_permission_id = ?`
	err = o.Raw(sql, permissionId).QueryRow(&item)
	return
}

// GetSecondaryChartPermissions 获取二级权限列表
func GetSecondaryChartPermissions() (list []*ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE product_id = ? AND parent_id > 0 AND enabled = 1 ORDER BY parent_id ASC, sort ASC, created_time ASC`
	_, err = o.Raw(sql, FiccProductId).QueryRows(&list)
	return
}

type SimpleChartPermission struct {
	ChartPermissionId   int                      `description:"品种ID"`
	ChartPermissionName string                   `description:"品种名称"`
	Sort                int                      `description:"排序"`
	Children            []*SimpleChartPermission `description:"子分类"`
}

func FormatChartPermission2Simple(origin *ChartPermission) (item *SimpleChartPermission) {
	if origin == nil {
		return
	}
	item = new(SimpleChartPermission)
	item.ChartPermissionId = origin.ChartPermissionId
	item.ChartPermissionName = origin.PermissionName
	item.Sort = origin.Sort

	return
}

// GetChartPermissionsByProductId 获取权限列表
func GetChartPermissionsByProductId() (list []*ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE product_id = ? AND enabled = 1 ORDER BY parent_id ASC, sort ASC, created_time ASC`
	_, err = o.Raw(sql, FiccProductId).QueryRows(&list)

	return
}

// GetChartPermissionByIdList
// @Description: 根据品种ID列表获取权限列表
// @author: Roc
// @datetime 2024-06-07 10:32:29
// @param permissionIdList []int
// @return items []*ChartPermission
// @return err error
func GetChartPermissionByIdList(permissionIdList []int) (items []*ChartPermission, err error) {
	num := len(permissionIdList)
	if num <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE chart_permission_id in (` + utils.GetOrmInReplace(num) + `) `
	_, err = o.Raw(sql, permissionIdList).QueryRows(&items)

	return
}
