package ai_summary

import (
	"eta_gn/eta_api/global"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

type AiSummaryClassify struct {
	AiSummaryClassifyId int       `gorm:"primaryKey;column:ai_summary_classify_id;type:int(11);not null"`
	ClassifyName        string    `gorm:"column:classify_name;type:varchar(255);not null;default:''"` // 分类名称
	ParentId            int       `gorm:"column:parent_id;type:int(11);not null;default:0"`           // 父级id
	CreateTime          time.Time `gorm:"column:create_time;type:datetime"`                           // 创建时间
	ModifyTime          time.Time `gorm:"column:modify_time;type:datetime"`                           // 修改时间
	SysUserId           int       `gorm:"index:idx_sys_user_id;column:sys_user_id;type:int(11)"`      // 创建人id
	SysUserRealName     string    `gorm:"column:sys_user_real_name;type:varchar(50)"`                 // 创建人姓名
	Level               int       `gorm:"column:level;type:int(11);default:0"`                        // 层级
	Sort                int       `gorm:"column:sort;type:int(9) unsigned;default:10"`                // 排序字段,越小越靠前,默认值:10
	RootId              int       `gorm:"column:root_id;type:int(11);not null;default:0"`             // 顶级ID
	HasData             int       `gorm:"column:has_data;type:tinyint(4);default:0"`                  // 是否存在指标数据:1有,2:无
}

func AddAiSummaryClassify(item *AiSummaryClassify) (lastId int64, err error) {
	//o := orm.NewOrm()
	//lastId, err = o.Insert(item)
	err = global.DEFAULT_DmSQL.Create(item).Error
	lastId = int64(item.AiSummaryClassifyId)
	return
}

type AiSummaryClassifyItems struct {
	AiSummaryClassifyId int                       `gorm:"primaryKey;column:ai_summary_classify_id;type:int(11);not null"`
	ClassifyName        string                    `gorm:"column:classify_name;type:varchar(255);not null;default:''"` // 分类名称
	ParentId            int                       `gorm:"column:parent_id;type:int(11);not null;default:0"`           // 父级id
	CreateTime          time.Time                 `gorm:"column:create_time;type:datetime"`                           // 创建时间
	ModifyTime          time.Time                 `gorm:"column:modify_time;type:datetime"`                           // 修改时间
	SysUserId           int                       `gorm:"index:idx_sys_user_id;column:sys_user_id;type:int(11)"`      // 创建人id
	SysUserRealName     string                    `gorm:"column:sys_user_real_name;type:varchar(50)"`                 // 创建人姓名
	Level               int                       `gorm:"column:level;type:int(11);default:0"`                        // 层级
	Sort                int                       `gorm:"column:sort;type:int(9) unsigned;default:10"`                // 排序字段,越小越靠前,默认值:10
	RootId              int                       `gorm:"column:root_id;type:int(11);not null;default:0"`             // 顶级ID
	HasData             int                       `gorm:"column:has_data;type:tinyint(4);default:0"`                  // 是否存在指标数据:1有,2:无
	AiSummaryId         int                       `description:"纪要id" gorm:"ai_summary_id"`
	UniqueCode          string                    `description:"唯一编码" gorm:"-"`
	Children            []*AiSummaryClassifyItems `gorm:"-"`
}

type AiSummaryClassifyListResp struct {
	AllNodes []*AiSummaryClassifyItems
}

// GetAiSummaryClassifyByParentId
func GetAiSummaryClassifyByParentId(parentId int) (items []*AiSummaryClassifyItems, err error) {
	//o := orm.NewOrm()
	//sql := ` SELECT * FROM ai_summary_classify WHERE parent_id=? order by sort asc,ai_summary_classify_id asc`
	//_, err = o.Raw(sql, parentId).QueryRows(&items)
	sql := ` SELECT * FROM ai_summary_classify WHERE parent_id=? order by sort asc,ai_summary_classify_id asc`
	err = global.DEFAULT_DmSQL.Raw(sql, parentId).Find(&items).Error
	return
}

// GetAiSummaryInfoByAdminId 获取所有我创建的纪要,用于分类展示
func GetAiSummaryInfoByAdminId(adminId int) (items []*AiSummaryClassifyItems, err error) {
	//	o := orm.NewOrm()
	//	sql := ` SELECT
	//	a.*,
	//	b.ai_summary_classify_id,
	//	b.classify_name
	//FROM
	//	ai_summary AS a
	//	JOIN ai_summary_classify AS b ON a.classify_id = b.ai_summary_classify_id
	//WHERE
	//	a.sys_user_id = ?
	//ORDER BY
	//	a.sort ASC,
	//	a.create_time ASC `
	//	_, err = o.Raw(sql, adminId).QueryRows(&items)
	sql := ` SELECT
	a.*,
	b.ai_summary_classify_id,
	b.classify_name 
FROM
	ai_summary AS a
	JOIN ai_summary_classify AS b ON a.classify_id = b.ai_summary_classify_id 
WHERE
	a.sys_user_id = ? 
ORDER BY
	a.sort ASC,
	a.create_time ASC `
	err = global.DEFAULT_DmSQL.Raw(sql, adminId).Find(&items).Error
	return
}

// GetAiSummaryClassifyAndInfoByParentId
func GetAiSummaryClassifyAndInfoByParentId(parentId int) (items []*AiSummaryClassifyItems, err error) {
	//o := orm.NewOrm()
	//	sql := ` SELECT
	//	0 AS ai_summary_id,
	//	ai_summary_classify_id,
	//	classify_name,
	//	parent_id,
	//	create_time,
	//	modify_time,
	//	sys_user_id,
	//	sys_user_real_name AS sys_user_real_name,
	//	sort,
	//	level
	//FROM
	//	ai_summary_classify
	//WHERE
	//	parent_id = ? UNION ALL
	//SELECT
	//	ai_summary_id,
	//	classify_id as ai_summary_classify_id,
	//	title AS classify_name,
	//	0 AS parent_id,
	//	create_time,
	//	modify_time,
	//	sys_user_id,
	//	sys_user_real_name,
	//	sort,
	//	0 AS level
	//FROM
	//	ai_summary
	//WHERE
	//	classify_id = ?
	//ORDER BY
	//	sort ASC,
	//	ai_summary_classify_id ASC`
	//	_, err = o.Raw(sql, parentId, parentId).QueryRows(&items)
	sql := ` SELECT
	0 AS ai_summary_id,
	ai_summary_classify_id,
	classify_name,
	parent_id,
	create_time,
	modify_time,
	sys_user_id,
	sys_user_real_name AS sys_user_real_name,
	sort,
	level
FROM
	ai_summary_classify 
WHERE
	parent_id = ? UNION ALL
SELECT
	ai_summary_id,
	classify_id as ai_summary_classify_id,
	title AS classify_name,
	0 AS parent_id,
	create_time,
	modify_time,
	sys_user_id,
	sys_user_real_name,
	sort,
	0 AS level
FROM
	ai_summary 
WHERE
	classify_id = ? 
ORDER BY
	sort ASC,
	ai_summary_classify_id ASC`
	err = global.DEFAULT_DmSQL.Raw(sql, parentId, parentId).Find(&items).Error
	return
}

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

func GetAiSummaryClassifyCount(classifyName string, parentId int) (count int, err error) {
	//o := orm.NewOrm()
	//sql := `SELECT COUNT(1) AS count FROM ai_summary_classify WHERE parent_id=? AND classify_name=? `
	//err = o.Raw(sql, parentId, classifyName).QueryRow(&count)
	sql := `SELECT COUNT(1) AS count FROM ai_summary_classify WHERE parent_id=? AND classify_name=? `
	err = global.DEFAULT_DmSQL.Raw(sql, parentId, classifyName).Scan(&count).Error
	return
}

// GetAiSummaryClassifyMaxSort 获取ai纪要下最大的排序数
func GetAiSummaryClassifyMaxSort(parentId int) (sort int, err error) {
	//o := orm.NewOrm()
	//sql := `SELECT Max(sort) AS sort FROM ai_summary_classify WHERE parent_id=? `
	//err = o.Raw(sql, parentId).QueryRow(&sort)
	sql := `SELECT Max(sort) AS sort FROM ai_summary_classify WHERE parent_id=? `
	err = global.DEFAULT_DmSQL.Raw(sql, parentId).Scan(&sort).Error
	return
}

type EditAiSummaryClassifyReq struct {
	ClassifyName        string `description:"分类名称"`
	AiSummaryClassifyId int    `description:"分类id"`
}

func EditSandboxClassify(classifyId int, classifyName string) (err error) {
	//o := orm.NewOrm()
	//sql := `UPDATE ai_summary_classify SET classify_name=?, modify_time=NOW() WHERE ai_summary_classify_id=? `
	//_, err = o.Raw(sql, classifyName, classifyId).Exec()
	sql := `UPDATE ai_summary_classify SET classify_name=?, modify_time=NOW() WHERE ai_summary_classify_id=? `
	err = global.DEFAULT_DmSQL.Exec(sql, classifyName, classifyId).Error
	return
}

type AiSummaryClassifyDeleteCheckReq struct {
	AiSummaryClassifyId int `description:"分类id"`
}

func GetAiSummaryInfoCountByClassifyId(classifyId int) (count int, err error) {
	//o := orm.NewOrm()
	//sql := ` SELECT COUNT(1) AS count FROM ai_summary AS a
	//			WHERE a.classify_id IN(
	//			SELECT t.ai_summary_classify_id FROM
	//			(
	//			SELECT rd.*
	//			FROM (SELECT * FROM ai_summary_classify WHERE parent_id IS NOT NULL) rd,
	//				 (SELECT @pid := ?) pd
	//			WHERE FIND_IN_SET(parent_id, @pid) > 0
	//			  AND @pid := CONCAT(@pid, ',', ai_summary_classify_id)
	//			UNION SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id = @pid
	//			)AS t
	//			) `
	//err = o.Raw(sql, classifyId).QueryRow(&count)
	sql := ` SELECT COUNT(1) AS count FROM ai_summary AS a
				WHERE a.classify_id IN(
				SELECT t.ai_summary_classify_id FROM 
				(
				SELECT rd.*
				FROM (SELECT * FROM ai_summary_classify WHERE parent_id IS NOT NULL) rd,
					 (SELECT @pid := ?) pd 
				WHERE FIND_IN_SET(parent_id, @pid) > 0 
				  AND @pid := CONCAT(@pid, ',', ai_summary_classify_id) 
				UNION SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id = @pid 
				)AS t
				) `
	err = global.DEFAULT_DmSQL.Raw(sql, classifyId).Scan(&count).Error
	return
}

type DeleteAiSummaryClassifyReq struct {
	AiSummaryClassifyId int `description:"分类id"`
	AiSummaryId         int `description:"纪要id"`
}

func DeleteAiSummaryClassify(classifyId int) (err error) {
	//o := orm.NewOrm()
	//sql := ` DELETE FROM ai_summary_classify
	//			WHERE ai_summary_classify_id IN(
	//			SELECT t.ai_summary_classify_id FROM
	//			(
	//			SELECT rd.*
	//			FROM (SELECT * FROM ai_summary_classify WHERE parent_id IS NOT NULL) rd,
	//			(SELECT @pid := ?) pd
	//			WHERE FIND_IN_SET(parent_id, @pid) > 0
	//			AND @pid := CONCAT(@pid, ',', ai_summary_classify_id)
	//			UNION SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id = @pid
	//			)AS t
	//			) `
	//_, err = o.Raw(sql, classifyId).Exec()
	sql := ` DELETE FROM ai_summary_classify
				WHERE ai_summary_classify_id IN(
				SELECT t.ai_summary_classify_id FROM
				(
				SELECT rd.*
				FROM (SELECT * FROM ai_summary_classify WHERE parent_id IS NOT NULL) rd,
				(SELECT @pid := ?) pd
				WHERE FIND_IN_SET(parent_id, @pid) > 0
				AND @pid := CONCAT(@pid, ',', ai_summary_classify_id)
				UNION SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id = @pid
				)AS t
				) `
	err = global.DEFAULT_DmSQL.Exec(sql, classifyId).Error
	return
}

// MoveAiSummaryClassifyReq 移动纪要分类请求参数
type MoveAiSummaryClassifyReq struct {
	AiSummaryClassifyId int `description:"分类id"`
	AiSummaryId         int `description:"纪要ID"`
	ParentClassifyId    int `description:"父级分类id 移动纪要时为目标分类id"`
	PrevId              int `description:"上一个兄弟节点分类id"`
	NextId              int `description:"下一个兄弟节点分类id"`
	PrevType            int `description:"上一个兄弟节点类型 1分类 2纪要 "`
	NextType            int `description:"上一个兄弟节点类型 1分类 2纪要 "`
}

func GetAiSummaryClassifyById(classifyId int) (item *AiSummaryClassify, err error) {
	//o := orm.NewOrm()
	//sql := `SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id=? `
	//err = o.Raw(sql, classifyId).QueryRow(&item)
	sql := `SELECT * FROM ai_summary_classify WHERE ai_summary_classify_id=? `
	err = global.DEFAULT_DmSQL.Raw(sql, classifyId).First(&item).Error
	return
}

func GetAiSummaryClassifyCountById(classifyId int) (count int, err error) {
	//o := orm.NewOrm()
	//sql := `SELECT count(1) AS count FROM ai_summary_classify WHERE ai_summary_classify_id=? `
	//err = o.Raw(sql, classifyId).QueryRow(&count)
	sql := `SELECT count(1) AS count FROM ai_summary_classify WHERE ai_summary_classify_id=? `
	err = global.DEFAULT_DmSQL.Raw(sql, classifyId).Scan(&count).Error
	return
}

// Update 更新沙盘分类基础信息
func (aiSummaryClassify *AiSummaryClassify) Update(cols []string) (err error) {
	//o := orm.NewOrm()
	//_, err = o.Update(aiSummaryClassify, cols...)
	err = global.DEFAULT_DmSQL.Select(cols).Updates(aiSummaryClassify).Error
	return
}

// GetFirstAiSummaryClassifyByParentId 获取当前父级沙盘分类下的排序第一条的数据
func GetFirstAiSummaryClassifyByParentId(parentId int) (item *AiSummaryClassify, err error) {
	//o := orm.NewOrm()
	//sql := ` SELECT * FROM ai_summary_classify WHERE parent_id=? order by sort asc,ai_summary_classify_id asc limit 1`
	//err = o.Raw(sql, parentId).QueryRow(&item)
	sql := ` SELECT * FROM ai_summary_classify WHERE parent_id=? order by sort asc,ai_summary_classify_id asc limit 1`
	err = global.DEFAULT_DmSQL.Raw(sql, parentId).First(&item).Error
	return
}

// UpdateAiSummaryClassifySortByParentId 根据沙盘父类id更新排序
func UpdateAiSummaryClassifySortByParentId(parentId, classifyId, nowSort int, updateSort string) (err error) {
	//o := orm.NewOrm()
	//sql := ` update ai_summary_classify set sort = ` + updateSort + ` WHERE parent_id=? and sort > ? `
	//if classifyId > 0 {
	//	sql += ` or ( ai_summary_classify_id > ` + fmt.Sprint(classifyId) + ` and sort= ` + fmt.Sprint(nowSort) + `)`
	//}
	//_, err = o.Raw(sql, parentId, nowSort).Exec()
	sql := ` update ai_summary_classify set sort = ` + updateSort + ` WHERE parent_id=? and sort > ? `
	if classifyId > 0 {
		sql += ` or ( ai_summary_classify_id > ` + fmt.Sprint(classifyId) + ` and sort= ` + fmt.Sprint(nowSort) + `)`
	}
	err = global.DEFAULT_DmSQL.Exec(sql, parentId, nowSort).Error
	return
}

// 获取所有子级分类id
//func GetAiSummaryClassifySubcategories(classifyId int) (Ids string, err error) {
//	o := orm.NewOrm()
//	sql := `SELECT GROUP_CONCAT(ai_summary_classify_id) AS ids
//FROM (
//SELECT @pv := ? AS ai_summary_classify_id
//UNION ALL
//SELECT sc.ai_summary_classify_id
//FROM ai_summary_classify sc
//JOIN (SELECT @pv := ?) initial
//WHERE sc.parent_id = @pv
//) subcategories; `
//	err = o.Raw(sql, classifyId, classifyId).QueryRow(&Ids)
//	return
//}

func GetAiSummaryClassify(aiSummaryClassify int) (aiSummaryClassifyIds string, err error) {
	//	o := orm.NewOrm()
	//	sql := `SELECT GROUP_CONCAT(t.ai_summary_classify_id) AS ai_summary_classify_id FROM (
	//			SELECT a.ai_summary_classify_id FROM ai_summary_classify AS a
	//			WHERE a.ai_summary_classify_id=?
	//			UNION ALL
	//			SELECT a.ai_summary_classify_id FROM ai_summary_classify AS a
	//			WHERE a.parent_id=? UNION ALL
	//	SELECT
	//		ai_summary_classify_id
	//	FROM
	//		ai_summary_classify
	//WHERE
	//	parent_id IN ( SELECT ai_summary_classify_id FROM ai_summary_classify WHERE parent_id = ? )
	//			)AS t`
	//	err = o.Raw(sql, aiSummaryClassify, aiSummaryClassify, aiSummaryClassify).QueryRow(&aiSummaryClassifyIds)
	sql := `SELECT GROUP_CONCAT(t.ai_summary_classify_id) AS ai_summary_classify_id FROM (
			SELECT a.ai_summary_classify_id FROM ai_summary_classify AS a 
			WHERE a.ai_summary_classify_id=?
			UNION ALL
			SELECT a.ai_summary_classify_id FROM ai_summary_classify AS a 
			WHERE a.parent_id=? UNION ALL
	SELECT
		ai_summary_classify_id 
	FROM
		ai_summary_classify 
WHERE
	parent_id IN ( SELECT ai_summary_classify_id FROM ai_summary_classify WHERE parent_id = ? )
			)AS t`
	err = global.DEFAULT_DmSQL.Raw(sql, aiSummaryClassify, aiSummaryClassify, aiSummaryClassify).Scan(&aiSummaryClassifyIds).Error
	return
}

func GetAiSummaryAllParentByClassifyId(aiSummaryClassifyId int) (ids string, err error) {
	//	o := orm.NewOrm()
	//	sql := `SELECT
	//	GROUP_CONCAT(DISTINCT m.ai_summary_classify_id  ORDER BY m.level) AS ids
	//FROM
	//	(
	//	SELECT
	//		@id AS _id,(
	//		SELECT
	//			@id := parent_id
	//		FROM
	//			ai_summary_classify
	//		WHERE
	//			ai_summary_classify_id = _id
	//		)
	//	FROM
	//		(
	//		SELECT
	//			@id :=(
	//			SELECT
	//				parent_id
	//			FROM
	//				ai_summary_classify
	//			WHERE
	//				ai_summary_classify_id = ?
	//			)) vm,
	//		ai_summary_classify m
	//	WHERE
	//		@id IS NOT NULL
	//	) vm
	//	INNER JOIN ai_summary_classify m
	//WHERE
	//	ai_summary_classify_id = vm._id `
	//	err = o.Raw(sql, aiSummaryClassifyId).QueryRow(&ids)
	sql := `SELECT
	GROUP_CONCAT(DISTINCT m.ai_summary_classify_id  ORDER BY m.level) AS ids 
FROM
	(
	SELECT
		@id AS _id,(
		SELECT
			@id := parent_id 
		FROM
			ai_summary_classify 
		WHERE
			ai_summary_classify_id = _id 
		) 
	FROM
		(
		SELECT
			@id :=(
			SELECT
				parent_id 
			FROM
				ai_summary_classify 
			WHERE
				ai_summary_classify_id = ? 
			)) vm,
		ai_summary_classify m 
	WHERE
		@id IS NOT NULL 
	) vm
	INNER JOIN ai_summary_classify m 
WHERE
	ai_summary_classify_id = vm._id `
	err = global.DEFAULT_DmSQL.Raw(sql, aiSummaryClassifyId).Scan(&ids).Error
	return
}

type AiSummaryListResp struct {
	Paging *paging.PagingItem
	List   []*AiSummaryItems
}

// GetAiSummaryClassifyAll
func GetAiSummaryClassifyAll() (items []*AiSummaryClassifyItems, err error) {
	//o := orm.NewOrm()
	//sql := ` SELECT * FROM ai_summary_classify WHERE parent_id<>0 order by sort asc,ai_summary_classify_id asc`
	//_, err = o.Raw(sql).QueryRows(&items)
	sql := ` SELECT * FROM ai_summary_classify WHERE parent_id<>0 order by sort asc,ai_summary_classify_id asc`
	err = global.DEFAULT_DmSQL.Raw(sql).Find(&items).Error
	return
}