package data_manage

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

// ChartCollect 图表收藏
type ChartCollect struct {
	ChartCollectId         int       `gorm:"primaryKey;autoIncrement;column:chart_collect_id;type:int(10) unsigned;not null"`
	ChartCollectClassifyId int       `gorm:"index:idx_classify_id;column:chart_collect_classify_id;type:int(10) unsigned;not null;default:0"` // 图表收藏分类ID
	ChartInfoId            int       `gorm:"column:chart_info_id;type:int(10) unsigned;not null;default:0"`                                   // 图表ID
	SysUserId              int       `gorm:"column:sys_user_id;type:int(10) unsigned;not null;default:0"`                                     // 创建人ID
	SysRealName            string    `gorm:"column:sys_real_name;type:int(10) unsigned;not null;default:0"`                                   // 创建人姓名
	Sort                   int       `gorm:"column:sort;type:int(10);default:0"`                                                              // 排序
	CreateTime             time.Time `gorm:"column:create_time;type:datetime"`                                                                // 创建时间
	ModifyTime             time.Time `gorm:"column:modify_time;type:datetime"`                                                                // 更新时间
}

func (m *ChartCollect) TableName() string {
	return "chart_collect"
}

type ChartCollectCols struct {
	PrimaryId              string
	ChartCollectClassifyId string
	ChartInfoId            string
	SysUserId              string
	SysRealName            string
	Sort                   string
	CreateTime             string
	ModifyTime             string
}

func (m *ChartCollect) Cols() ChartCollectCols {
	return ChartCollectCols{
		PrimaryId:              "chart_collect_id",
		ChartCollectClassifyId: "chart_collect_classify_id",
		ChartInfoId:            "chart_info_id",
		SysUserId:              "sys_user_id",
		SysRealName:            "sys_real_name",
		Sort:                   "sort",
		CreateTime:             "create_time",
		ModifyTime:             "modify_time",
	}
}

func (m *ChartCollect) Create() (err error) {
	err = global.DmSQL["data"].Create(m).Error
	return
}

func (m *ChartCollect) CreateMulti(items []*ChartCollect) (err error) {
	if len(items) == 0 {
		return
	}
	err = global.DmSQL["data"].CreateInBatches(items, utils.MultiAddNum).Error
	return
}

func (m *ChartCollect) Update(cols []string) (err error) {
	err = global.DmSQL["data"].Select(cols).Updates(m).Error
	return
}

func (m *ChartCollect) Remove() (err error) {
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = global.DmSQL["data"].Exec(sql, m.ChartCollectId).Error
	return
}

func (m *ChartCollect) MultiRemove(ids []int) (err error) {
	if len(ids) == 0 {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.Cols().PrimaryId, utils.GetOrmInReplace(len(ids)))
	err = global.DmSQL["data"].Exec(sql, ids).Error
	return
}

func (m *ChartCollect) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	err = global.DmSQL["data"].Exec(sql, pars...).Error
	return
}

// RemoveAndCreateMulti
// @Description: 清除原有配置并新增收藏
// @receiver m
// @param delCondition
// @param delPars
// @param items
// @return err
func (m *ChartCollect) RemoveAndCreateMulti(delCondition string, delPars []interface{}, items []*ChartCollect) (err error) {
	to := global.DmSQL["data"].Begin()
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 先删除
	{
		if delCondition == "" {
			return
		}
		sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), delCondition)
		err = to.Exec(sql, delPars...).Error
		if err != nil {
			return
		}
	}

	if len(items) == 0 {
		return
	}
	err = to.CreateInBatches(items, utils.MultiAddNum).Error

	return
}

func (m *ChartCollect) GetItemById(id int) (item *ChartCollect, err error) {
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = global.DmSQL["data"].Raw(sql, id).First(&item).Error
	return
}

func (m *ChartCollect) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *ChartCollect, err error) {
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = global.DmSQL["data"].Raw(sql, pars...).First(&item).Error
	return
}

func (m *ChartCollect) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = global.DmSQL["data"].Raw(sql, pars...).Scan(&count).Error
	return
}

func (m *ChartCollect) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ChartCollect, err error) {
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	err = global.DmSQL["data"].Raw(sql, pars...).Find(&items).Error
	return
}

func (m *ChartCollect) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*ChartCollect, err error) {
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	pars = append(pars, startSize, pageSize)
	err = global.DmSQL["data"].Raw(sql, pars...).Find(&items).Error
	return
}

// GetCollectChartInfoByClassifyId 获取分类下收藏的图表信息
func GetCollectChartInfoByClassifyId(classifyId int) (items []*ChartInfo, err error) {
	sql := `SELECT b.* FROM chart_collect AS a JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id WHERE a.chart_collect_classify_id = ? ORDER BY a.sort ASC`
	err = global.DmSQL["data"].Raw(sql, classifyId).Find(&items).Error
	return
}

// ChartCollectReq 加入/取消收藏
type ChartCollectReq struct {
	ClassifyId     int   `description:"分类ID"`
	ClassifyIdList []int `description:"分类ID列表"`
	ChartInfoId    int   `description:"图表ID"`
}

// GetCollectChartInfoCount 获取收藏的图表信息总数
func GetCollectChartInfoCount(condition string, pars []interface{}) (total int64, err error) {
	sql := fmt.Sprintf(`SELECT COUNT(1) AS ct FROM (
	  SELECT b.chart_info_id FROM chart_collect AS a JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id
	  WHERE 1=1 %s
	  GROUP BY b.chart_info_id
	) AS sub`, condition)
	err = global.DmSQL["data"].Raw(sql, pars...).Scan(&total).Error
	return
}

// GetCollectChartInfoPageList 获取收藏的图表信息列表-分页
func GetCollectChartInfoPageList(condition string, pars []interface{}, startSize, pageSize int) (list []*CollectChartInfoQuery, err error) {
	sql := fmt.Sprintf(`SELECT b."chart_info_id",
       WM_CONCAT(DISTINCT a."chart_collect_classify_id") AS "collect_classify_id",
MAX(a.create_time) as collect_time,
MAX(b."chart_name") "chart_name",
MAX(b."chart_type") "chart_type",
MAX(b."source") "source",
MAX(b."chart_classify_id") "chart_classify_id",
MAX(b."create_time") "create_time",
MAX(b."unique_code") "unique_code",
MAX(b."chart_image") "chart_image",
MAX(b."modify_time") "modify_time",
MAX(a."sort") AS "sort"
 FROM chart_collect AS a JOIN chart_info AS b ON a.chart_info_id = b.chart_info_id
	  WHERE 1=1 %s
	  GROUP BY b.chart_info_id
ORDER BY collect_time DESC LIMIT ?,?`, condition)
	pars = append(pars, startSize, pageSize)
	err = global.DmSQL["data"].Raw(sql, pars...).Scan(&list).Error
	return
}

// GetUserAllCollectChartInfoIdList
// @Description: 获取用户所有收藏的图表id列表
// @author: Roc
// @datetime 2024-11-28 15:27:52
// @param userId int
// @return list []int
// @return err error
func GetUserAllCollectChartInfoIdList(userId int) (list []int, err error) {
	sql := `SELECT chart_info_id FROM chart_collect WHERE 1=1 AND sys_user_id = ? GROUP BY chart_info_id`
	err = global.DmSQL["data"].Raw(sql, userId).Scan(&list).Error
	return
}

type CollectChartInfoQuery struct {
	ChartInfo
	CollectClassifyIdStr string    `gorm:"column:collect_classify_id" description:"收藏分类ID"`
	CollectTime          time.Time `gorm:"column:collect_time" description:"收藏时间"`
}

// CollectChartInfoItem 收藏列表图表信息
type CollectChartInfoItem struct {
	ChartInfoId           int    `description:"图表ID"`
	ChartInfoType         int    `description:"图表类型:0-普通图表; 1-预测图表"`
	ChartType             int    `description:"图表类型:1-基础图表; 2-计算图表"`
	Source                int    `description:"来源ID"`
	SourceName            string `description:"来源名称"`
	ChartName             string `description:"图表名称"`
	Frequency             string `description:"频率"`
	Unit                  string `description:"单位"`
	UniqueCode            string `description:"唯一编码"`
	ChartImage            string `description:"图表图片"`
	ClassifyId            int    `description:"图表分类ID"`
	CollectClassifyIdList []int  `description:"收藏分类ID列表"`
	CollectTime           string `description:"收藏时间"`
	CreateTime            string `description:"创建时间"`
	Sort                  int    `description:"排序"`
}

func FormatChartInfo2CollectItem(origin *CollectChartInfoQuery) (item *CollectChartInfoItem) {
	item = new(CollectChartInfoItem)
	item.ChartInfoId = origin.ChartInfoId
	item.ChartType = origin.ChartType
	item.Source = origin.Source
	item.ChartName = origin.ChartName
	item.Unit = origin.Unit
	item.UniqueCode = origin.UniqueCode
	item.ChartImage = origin.ChartImage
	item.ClassifyId = origin.ChartClassifyId
	collectClassifyIdList := make([]int, 0)
	if origin.CollectClassifyIdStr != `` {
		collectClassifyIdStrList := strings.Split(origin.CollectClassifyIdStr, ",")
		for _, v := range collectClassifyIdStrList {
			collectClassifyId, tmpErr := strconv.Atoi(v)
			if tmpErr == nil {
				collectClassifyIdList = append(collectClassifyIdList, collectClassifyId)
			}
		}
	}
	item.CollectClassifyIdList = collectClassifyIdList
	item.CollectTime = origin.CollectTime.Format(utils.FormatDateTime)
	item.CreateTime = origin.CreateTime.Format(utils.FormatDateTime)
	item.Sort = origin.Sort
	return
}

// CollectChartInfoListResp 收藏图表分页列表相应
type CollectChartInfoListResp struct {
	Paging *paging.PagingItem
	List   []*CollectChartInfoItem
}

// ChartCollectMoveReq 移动收藏
type ChartCollectMoveReq struct {
	ChartInfoId     int `description:"收藏的图表ID(分类下图表ID唯一)"`
	PrevChartInfoId int `description:"前一个收藏的图表ID"`
	NextChartInfoId int `description:"后一个收藏的图表ID"`
	ClassifyId      int `description:"当前分类ID"`
}

func GetChartCollectSort(adminId, classifyId, sort int) (item *ChartCollect, err error) {
	sql := ` SELECT * FROM chart_collect WHERE 1=1 AND sys_user_id = ? AND chart_collect_classify_id = ? `
	if sort == 1 {
		sql += ` ORDER BY sort DESC, chart_collect_id ASC LIMIT 1 `
	} else {
		sql += ` ORDER BY sort ASC, chart_collect_id DESC LIMIT 1 `
	}
	err = global.DmSQL["data"].Raw(sql, adminId, classifyId).First(&item).Error
	return
}

func GetChartCollectByChartInfoId(adminId, chartInfoId, classifyId int) (item *ChartCollect, err error) {
	sql := `SELECT * FROM chart_collect WHERE sys_user_id = ? AND chart_info_id = ? AND chart_collect_classify_id=? `
	err = global.DmSQL["data"].Raw(sql, adminId, chartInfoId, classifyId).First(&item).Error
	return
}

func UpdateChartCollectSortByClassifyId(classifyId, nowSort int, prevMyChartClassifyMappingId int, updateSort string) (err error) {
	sql := ` update chart_collect set sort = ` + updateSort + ` WHERE chart_collect_classify_id = ?  `
	if prevMyChartClassifyMappingId > 0 {
		sql += ` AND ( sort > ? or ( chart_collect_id < ? and sort=? )) `
	}
	err = global.DmSQL["data"].Exec(sql, classifyId, nowSort, prevMyChartClassifyMappingId, nowSort).Error
	return
}

func UpdateChartCollectMove(sort, adminId, chartInfoId, myChartClassifyId int) (err error) {
	sql := ` UPDATE chart_collect SET sort = ?,modify_time=NOW() WHERE sys_user_id=? AND chart_info_id=? AND chart_collect_classify_id=? `
	err = global.DmSQL["data"].Exec(sql, sort, adminId, chartInfoId, myChartClassifyId).Error
	return
}

// ChartCollectItem 图表收藏信息
type ChartCollectItem struct {
	ChartCollectId         int       `gorm:"primaryKey;autoIncrement;column:chart_collect_id;type:int(10) unsigned;not null"`
	ChartCollectClassifyId int       `gorm:"index:idx_classify_id;column:chart_collect_classify_id;type:int(10) unsigned;not null;default:0"` // 图表收藏分类ID
	ChartInfoId            int       `gorm:"column:chart_info_id;type:int(10) unsigned;not null;default:0"`                                   // 图表ID
	SysUserId              int       `gorm:"column:sys_user_id;type:int(10) unsigned;not null;default:0"`                                     // 创建人ID
	SysRealName            string    `gorm:"column:sys_real_name;type:int(10) unsigned;not null;default:0"`                                   // 创建人姓名
	ClassifyName           string    `gorm:"column:classify_name;type:varchar(255);not null;default:''"`                                      // 分类名称
	Sort                   int       `gorm:"column:sort;type:int(10);default:0"`                                                              // 排序
	CreateTime             time.Time `gorm:"column:create_time;type:datetime"`                                                                // 创建时间
	ModifyTime             time.Time `gorm:"column:modify_time;type:datetime"`                                                                // 更新时间
}

func (m *ChartCollect) GetItemsByUserIdAndChartInfoIdList(userId int, chartInfoIdList []int) (items []*ChartCollectItem, err error) {
	if len(chartInfoIdList) <= 0 {
		return
	}
	sql := `SELECT a.*,b.classify_name FROM chart_collect  AS a
    JOIN chart_collect_classify b on a.chart_collect_classify_id = b.chart_collect_classify_id
    WHERE a.sys_user_id = ? AND a.chart_info_id in (?)  ORDER BY a.chart_collect_id DESC `
	err = global.DmSQL["data"].Raw(sql, userId, chartInfoIdList).Find(&items).Error

	return
}