package models

import (
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"strings"
	"time"

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

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 ChartPermissionList 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"`
	Child                 []*ChartPermissionList `description:"子权限"`
}

// ChartPermissionSearchKeyWordMapping 表示 chart_permission_search_key_word_mapping 表的结构
type ChartPermissionSearchKeyWordMapping struct {
	ChartPermissionID int `gorm:"column:chart_permission_id"` // chart_permission_id 字段
	ClassifyID        int `gorm:"column:classify_id"`         // classify_id 字段
}
type ChartPermissionView struct {
	ParentName     string `description:"父权限名称" json:"parent_name"`
	PermissionName string `description:"权限名" json:"permission_name"`
}

type ChartPermissionListTree struct {
	ChartPermissionId int                        `description:"权限ID"`
	PermissionName    string                     `description:"权限名"`
	ParentId          int                        `description:"父权限ID"`
	IsPublic          int                        `description:"是否是公有权限"`
	PublicChild       []*ChartPermissionListTree `description:"公有权限"`
	PrivateChild      []*ChartPermissionListTree `description:"私有权限"`
}

func GetChartPermissionListByIds(chartPermissionIds []int) (items []*ChartPermissionView, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT c.permission_name AS permission_name, lc.permission_name AS parent_name FROM chart_permission c
		LEFT JOIN chart_permission lc
		ON c.parent_id=lc.chart_permission_id 
		WHERE c.chart_permission_id in (%s)
	`
	// 构建 IN 子句的占位符
	placeholders := make([]string, len(chartPermissionIds))
	args := make([]interface{}, len(chartPermissionIds))
	for i, id := range chartPermissionIds {
		placeholders[i] = "?"
		args[i] = id
	}
	sql = fmt.Sprintf(sql, strings.Join(placeholders, ","))
	_, err = o.Raw(sql, chartPermissionIds).QueryRows(&items)
	return
}

func GetByPermissionIdsByClassifyId(classify int) (permissionIds []int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := "select distinct chart_permission_id from chart_permission_search_key_word_mapping where classify_id =?"
	_, err = o.Raw(sql, classify).QueryRows(&permissionIds)
	return
}

func GetChartPermissionList() (items []*ChartPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE enabled=1 AND product_id=1 ORDER BY sort, chart_permission_id ASC`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}
func GetPermissionNames(ids []int) (items []string, err error) {
	o := orm.NewOrmUsingDB("rddp")
	condition := " AND chart_permission_id in (" + utils.GetOrmReplaceHolder(len(ids)) + ")"
	sql := `SELECT distinct  permission_name FROM chart_permission WHERE enabled=1 AND product_id=1` + condition
	_, err = o.Raw(sql, ids).QueryRows(&items)
	return
}
func GetPermissionNameById(id int) (items string, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT distinct  permission_name FROM chart_permission WHERE enabled=1 AND product_id=1 and chart_permission_id=?`
	err = o.Raw(sql, id).QueryRow(&items)
	return
}
func GetChartPermissionByParentId(parentId int) (items []*ChartPermissionList, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM chart_permission WHERE enabled=1 AND chart_permission_id=? order parent_id asc ,sort asc`
	_, err = o.Raw(sql, parentId).QueryRows(&items)
	return
}
func GetClassifyIdsByPermissionIds(condition string, pars []interface{}) (classifyIds []int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := "select distinct classify_id from chart_permission_search_key_word_mapping where 1=1 "
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql, pars).QueryRows(&classifyIds)
	return
}
