package data_manage

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"time"
)

type ChartClassify struct {
	ChartClassifyId     int       `orm:"column(chart_classify_id);pk" gorm:"primaryKey" `
	ChartClassifyName   string    `description:"分类名称"`
	ParentId            int       `description:"父级id"`
	HasData             int       `description:"是否含有指标数据"`
	CreateTime          time.Time `description:"创建时间"`
	ModifyTime          time.Time `description:"修改时间"`
	SysUserId           int       `description:"创建人id"`
	SysUserRealName     string    `description:"创建人姓名"`
	Level               int       `description:"层级"`
	UniqueCode          string    `description:"唯一编码"`
	Sort                int       `description:"排序字段,越小越靠前,默认值:10"`
	Source              int       `description:"1:ETA图库;2:商品价格曲线"`
	IsJoinPermission    int       `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
	ChartClassifyNameEn string    `description:"英文分类名称"`
	RootId              int       `description:"顶级ID"`
}

func AddChartClassify(item *ChartClassify) (lastId int64, err error) {
	err = global.DmSQL["data"].Create(item).Error
	if err != nil {
		return
	}
	lastId = int64(item.ChartClassifyId)

	return
}

type AddChartClassifyReq struct {
	ChartClassifyName string `description:"分类名称"`
	ParentId          int    `description:"父级id,第一级传0"`
	Level             int    `description:"层级,第一级传0,其余传上一级的层级"`
}

// GetChartClassifyCount
// @Description: 根据图表分类名称获取对应的数量
// @author: Roc
// @datetime 2024-04-16 18:13:40
// @param chartClassifyName string
// @param parentId int
// @param source int
// @return count int
// @return err error
func GetChartClassifyCount(chartClassifyName string, parentId, source int) (count int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT COUNT(1) AS count FROM chart_classify WHERE parent_id=? AND source = ? AND chart_classify_name=? `
	err = o.Raw(sql, parentId, source, chartClassifyName).Scan(&count).Error

	return
}

// GetChartClassifyEnCount
// @Description: 根据图表分类英文名称获取对应的数量
// @author: Roc
// @datetime 2024-04-16 18:13:24
// @param chartClassifyNameEn string
// @param parentId int
// @param source int
// @return count int
// @return err error
func GetChartClassifyEnCount(chartClassifyNameEn string, parentId, source int) (count int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT COUNT(1) AS count FROM chart_classify WHERE parent_id=? AND source = ? AND chart_classify_name_en = ? `
	err = o.Raw(sql, parentId, source, chartClassifyNameEn).Scan(&count).Error

	return
}

type EditChartClassifyReq struct {
	ChartClassifyName string `description:"分类名称"`
	ChartClassifyId   int    `description:"分类id"`
}

func GetChartClassifyById(classifyId int) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE chart_classify_id=? `
	err = o.Raw(sql, classifyId).First(&item).Error
	return
}

func GetChartClassifyCountById(classifyId int) (count int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT count(1) AS count FROM chart_classify WHERE chart_classify_id=? `
	err = o.Raw(sql, classifyId).Scan(&count).Error

	return
}

type DeleteChartClassifyReq struct {
	ChartClassifyId int `description:"分类id"`
	ChartInfoId     int `description:"指标id"`
}

// GetChartClassifyByParentId
// @param source int 1:ETA图库;2:商品价格曲线;3:相关性图表
func GetChartClassifyByParentId(parentId, source int) (items []*ChartClassifyItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE parent_id=? AND source = ? order by sort asc,chart_classify_id asc`
	err = o.Raw(sql, parentId, source).Scan(&items).Error

	return
}

// GetChartClassifyAll
// @param source int 1:ETA图库;2:商品价格曲线;3:相关性图表
func GetChartClassifyAll(source int) (items []*ChartClassifyItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE parent_id<>0 AND source = ? order by sort asc,chart_classify_id asc`
	err = o.Raw(sql, source).Scan(&items).Error

	return
}

type ChartClassifyItems struct {
	ChartClassifyId     int `description:"分类id"`
	ChartInfoId         int `description:"指标id"`
	ChartClassifyName   string
	ChartClassifyNameEn string
	ParentId            int
	Level               int                      `description:"层级"`
	Sort                int                      `description:"排序字段,越小越靠前,默认值:10"`
	UniqueCode          string                   `description:"唯一编码"`
	Source              int                      `description:"来源id"`
	SourceName          string                   `description:"来源名称"`
	SysUserId           int                      `description:"创建人id"`
	SysUserRealName     string                   `description:"创建人姓名"`
	DateType            int                      `description:"日期类型:1:00年至今,2:10年至今,3:15年至今,4:年初至今,5:自定义时间"`
	StartDate           string                   `description:"自定义开始日期"`
	EndDate             string                   `description:"自定义结束日期"`
	ChartType           int                      `description:"生成样式:1:曲线图,2:季节性图"`
	Calendar            string                   `description:"公历/农历"`
	SeasonStartDate     string                   `description:"季节性图开始日期"`
	SeasonEndDate       string                   `description:"季节性图开始日期"`
	Children            []*ChartClassifyItems    `gorm:"-"`
	Button              ChartClassifyItemsButton `gorm:"-" description:"按钮权限"`
	IsJoinPermission    int                      `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
	HaveOperaAuth       bool                     `description:"是否有数据权限,默认:false"`
}

// ChartClassifyItemsButton 操作按钮
type ChartClassifyItemsButton struct {
	AddButton    bool `description:"是否可添加"`
	OpButton     bool `description:"是否可编辑"`
	DeleteButton bool `description:"是否可删除"`
	MoveButton   bool `description:"是否可移动"`
}

type ChartClassifyListResp struct {
	AllNodes      []*ChartClassifyItems
	Language      string `description:"指标的展示语言,CN:中文,EN:英文"`
	CanOpClassify bool   `description:"是否允许操作分类"`
}

type ChartClassifyDeleteCheckResp struct {
	DeleteStatus int    `description:"检测状态:0:默认值,如果为0,继续走其他校验,1:该分类下关联图表不可删除,2:确认删除当前目录及包含的子目录吗"`
	TipsMsg      string `description:"提示信息"`
}

type ChartClassifyDeleteCheckReq struct {
	ChartClassifyId int `description:"分类id"`
	ChartInfoId     int `description:"指标id"`
}

func GetChartClassifyByCondition(condition string, pars []interface{}) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE 1=1 `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars...).First(&item).Error

	return
}

// MoveChartClassifyReq 移动图表分类请求参数
type MoveChartClassifyReq struct {
	ClassifyId       int `description:"分类id"`
	ParentClassifyId int `description:"父级分类id"`
	PrevClassifyId   int `description:"上一个兄弟节点分类id"`
	NextClassifyId   int `description:"下一个兄弟节点分类id"`
	ChartInfoId      int `description:"图表ID, 如果图表ID有值,则移动对象为图表,否则认为移动对象分类"`
	PrevChartInfoId  int `description:"上一个图表ID"`
	NextChartInfoId  int `description:"下一个图表ID"`
}

// GetFirstChartClassifyByParentId 获取当前父级图表分类下的排序第一条的数据
func GetFirstChartClassifyByParentId(parentId int) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE parent_id=? order by sort asc,chart_classify_id asc limit 1`
	err = o.Raw(sql, parentId).First(&item).Error

	return
}

// GetFirstChartClassifyByParentIdAndSource 获取当前父级图表分类下的排序第一条的数据
func GetFirstChartClassifyByParentIdAndSource(parentId, source int) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE parent_id=?  and source = ? order by sort asc,chart_classify_id asc limit 1`
	err = o.Raw(sql, parentId, source).First(&item).Error

	return
}

// UpdateChartClassifySortByParentId 根据图表父类id更新排序
func UpdateChartClassifySortByParentId(parentId, classifyId, nowSort int, updateSort string) (err error) {
	o := global.DmSQL["data"]
	sql := ` update chart_classify set sort = ` + updateSort + ` WHERE parent_id=? and sort > ? `
	if classifyId > 0 {
		sql += ` or ( chart_classify_id > ` + fmt.Sprint(classifyId) + ` and sort= ` + fmt.Sprint(nowSort) + `)`
	}
	err = o.Exec(sql, parentId, nowSort).Error

	return
}

// Update 更新图表分类基础信息
func (chartClassify *ChartClassify) Update(cols []string) (err error) {
	err = global.DmSQL["data"].Select(cols).Updates(chartClassify).Error

	return
}

// GetChartClassifyMaxSort 获取图表分类下最大的排序数
func GetChartClassifyMaxSort(parentId, source int) (sort int, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT COALESCE(MAX(sort),0) AS sort FROM chart_classify WHERE parent_id=? AND source = ? `
	err = o.Raw(sql, parentId, source).Scan(&sort).Error

	return
}

type ChartClassifyView struct {
	ChartClassifyId   int    `orm:"column(chart_classify_id);pk" gorm:"primaryKey" `
	ChartClassifyName string `description:"分类名称"`
	ParentId          int    `description:"父级id"`
}

func GetChartClassifyViewById(classifyId int) (item *ChartClassifyView, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE chart_classify_id=? `
	err = o.Raw(sql, classifyId).First(&item).Error

	return
}

func GetChartClassifyByLevel(level, source int) (items []*ChartClassifyItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE level=? AND source = ? order by sort asc,chart_classify_id asc`
	err = o.Raw(sql, level, source).Scan(&items).Error

	return
}

func EditChartClassifySysUser(classifyId, sysUserId int, chartClassifyName string) (err error) {
	o := global.DmSQL["data"]
	sql := `UPDATE chart_classify SET sys_user_id=?,sys_user_real_name=?,modify_time=NOW() WHERE parent_id=?  AND level=3 `
	err = o.Exec(sql, sysUserId, chartClassifyName, classifyId).Error

	return
}

func GetAllChartClassifyItemsBySource(source int) (items []*ChartClassifyItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE source = ? order by sort ASC,chart_classify_id ASC`
	err = o.Raw(sql, source).Scan(&items).Error

	return
}

// GetCrossVarietyChartClassifyBySysUserId
// @Description: 根据创建人获取跨品种分析的分类
// @author: Roc
// @datetime 2023-11-24 14:05:43
// @param sysUserId int
// @return item *ChartClassify
// @return err error
func GetCrossVarietyChartClassifyBySysUserId(sysUserId int) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE source = ? AND sys_user_id=?`
	err = o.Raw(sql, utils.CHART_SOURCE_CROSS_HEDGING, sysUserId).First(&item).Error

	return
}

// GetChartClassifyByParentIdAndName 根据父级ID和名称获取分类
func GetChartClassifyByParentIdAndName(source, parentId int, classifyName string, classifyId int) (item *ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE source = ? AND parent_id = ? AND chart_classify_name = ? AND chart_classify_id <> ? LIMIT 1`
	err = o.Raw(sql, source, parentId, classifyName, classifyId).First(&item).Error

	return
}

// GetChartClassifyByIdList
// @Description:  根据分类ID列表获取分类
// @author: Roc
// @datetime 2024-04-01 13:21:48
// @param classifyId []int
// @return items []*ChartClassify
// @return err error
func GetChartClassifyByIdList(classifyIdList []int) (items []*ChartClassify, err error) {
	num := len(classifyIdList)
	if num <= 0 {
		return
	}
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE chart_classify_id in (` + utils.GetOrmInReplace(num) + `) `
	err = o.Raw(sql, classifyIdList).Scan(&items).Error

	return
}

// GetChartClassifyBySourceAndIsJoinPermission
// @Description: 根据分类类型和是否涉密获取分类列表
// @author: Roc
// @datetime 2024-03-29 10:30:21
// @param source int
// @param isJoinPermission int
// @return items []*ChartClassify
// @return err error
func GetChartClassifyBySourceAndIsJoinPermission(source, isJoinPermission int) (items []*ChartClassify, err error) {
	o := global.DmSQL["data"]
	sql := `SELECT * FROM chart_classify WHERE source = ? AND is_join_permission = ? `
	err = o.Raw(sql, source, isJoinPermission).Scan(&items).Error

	return
}

type ChartClassifyIdItems struct {
	ChartClassifyId   int    `description:"分类id"`
	ChartClassifyName string `description:"分类名称"`
	UniqueCode        string `description:"唯一编码"`
	ParentId          int    `description:"父级分类id"`
	Level             int    `description:"层级"`
	RootId            int    `description:"顶级分类id"`
	IsJoinPermission  int    `description:"是否加入权限管控,0:不加入;1:加入;默认:0" json:"-"`
	HaveOperaAuth     bool   `description:"是否有该数据权限,默认:false"`
}

func GetChartClassifyByRootIdLevel(rootId, source int, orderStr string) (items []*ChartClassifyIdItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE root_id = ? AND source = ? `
	if orderStr != "" {
		sql += orderStr
	} else {
		sql += ` order by level desc, sort asc, chart_classify_id asc`
	}

	err = o.Raw(sql, rootId, source).Scan(&items).Error

	return
}

// UpdateChartClassifySortByParentIdAndSource 根据图表父类id更新排序
func UpdateChartClassifySortByParentIdAndSource(parentId, classifyId, nowSort int, updateSort string, source int) (err error) {
	o := global.DmSQL["data"]
	sql := ` update chart_classify set sort = ` + updateSort + ` WHERE parent_id=? and sort > ? AND source = ? `
	if classifyId > 0 {
		sql += ` or ( chart_classify_id > ` + fmt.Sprint(classifyId) + ` and sort= ` + fmt.Sprint(nowSort) + `)`
	}
	err = o.Exec(sql, parentId, nowSort, source).Error

	return
}

// GetChartClassifyAllBySource 根据来源获取所有分类
func GetChartClassifyAllBySource(source int) (items []*ChartClassifyItems, err error) {
	o := global.DmSQL["data"]
	sql := ` SELECT * FROM chart_classify WHERE source = ? ORDER BY parent_id ASC, sort ASC, chart_classify_id ASC`
	err = o.Raw(sql, source).Scan(&items).Error

	return
}

// delByIds
func DeleteChartClassifyByIds(ids []int) (err error) {
	o := global.DmSQL["data"]
	sql := `DELETE FROM chart_classify WHERE chart_classify_id IN (` + utils.GetOrmInReplace(len(ids)) + `)`
	err = o.Exec(sql, ids).Error
	return
}