package data_manage

import (
	"eta/eta_api/global"
	"eta/eta_api/utils"
	"time"

	"github.com/rdlucklib/rdluck_tools/paging"
	"gorm.io/gorm"
)

type BaseFromFenweiIndex struct {
	FenweiIndexId int       `orm:"column(fenwei_index_id);pk" gorm:"primaryKey;"`
	ClassifyId    int
	IndexCode     string
	IndexName     string
	Frequency     string
	Unit          string
	Sort          int
	CreateTime    time.Time
	ModifyTime    time.Time
}

type BaseFromFenweiIndexList struct {
	FenweiIndexId int `orm:"column(fenwei_index_id);pk" gorm:"primaryKey;"`
	ClassifyId    int
	IndexCode     string
	IndexName     string
	Frequency     string
	Unit          string
	Sort          int
	CreateTime    string
	ModifyTime    string
	DataList      []*BaseFromFenweiData `gorm:"-"`
	Paging        *paging.PagingItem    `description:"分页数据" gorm:"-"`
	EdbInfoId     int                   `description:"指标库主键id"`
}

func (b *BaseFromFenweiIndexList) AfterFind(tx *gorm.DB) (err error) {
		b.CreateTime = utils.GormDateStrToDateTimeStr(b.CreateTime)
		b.ModifyTime = utils.GormDateStrToDateTimeStr(b.ModifyTime)
	return
}
type FenweiSingleDataResp struct {
	FenweiIndexId int
	ClassifyId    int
	IndexCode     string
	IndexName     string
	Frequency     string
	Unit          string
	CreateTime    string
	ModifyTime    string
	Data          []*FenweiSingleData
	EdbInfoId     int `description:"指标库主键id"`
}

type FenweiSingleData struct {
	Value    string `orm:"column(value)" description:"日期"`
	DataTime string `orm:"column(data_time)" description:"值"`
}

// BaseFromFenWeiIndexBatchAddCheckReq 校验编码是否存在请求参数
type BaseFromFenWeiIndexBatchAddCheckReq struct {
	IndexCodes []string `form:"IndexCodes" description:"指标编码列表"`
}

// IndexCheckData 校验编码是否存在
type FenWeiIndexCheckData struct {
	IndexCode  string `orm:"column(index_code)" description:"指标编码"`
	IndexName  string `orm:"column(index_name)" description:"指标名称"`
	Frequency  string `orm:"column(frequency)" description:"频度"`
	Unit       string `orm:"column(unit)" description:"单位"`
	EdbInfoId  int    `json:"edb_info_id" description:"指标库主键id"`
	UniqueCode string `json:"unique_code" description:"指标库唯一编码"`
	ClassifyId int    `json:"classify_id" description:"分类id"`
}

// NameCheckResult 校验名称是否存在
type FenWeiNameCheckResult struct {
	IndexCode string `from:"EdbCode" description:"edb编码"`
	IndexName string `from:"EdbName" description:"edb名称"`
	Exist     bool
}

// FenWeiIndexAddReq 指标添加vo
type FenWeiIndexAddReq struct {
	EdbCode       string `description:"指标编码"`
	EdbName       string `description:"指标名称"`
	Frequency     string `description:"频度"`
	Unit          string `description:"单位"`
	ClassifyId    int    `description:"分类ID"`
	AdminId       int    `description:"管理员ID"`
	AdminRealName string `description:"管理员名称"`
}

type BaseFromFenWeiIndexPage struct {
	List   []*BaseFromFenweiIndex `description:"指标列表"`
	Paging *paging.PagingItem     `description:"分页数据"`
}

func GetFenweiIndex(condition string, pars []interface{}) (items []*BaseFromFenweiIndexList, err error) {
	sql := ` SELECT * FROM base_from_fenwei_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY sort ASC, fenwei_index_id asc`
	err = global.DbMap[utils.DbNameIndex].Raw(sql, pars...).Find(&items).Error
	return
}

func GetFenweiIndexDataCount(indexCode string) (count int, err error) {
	sql := ` SELECT COUNT(1) AS count FROM base_from_fenwei_data WHERE index_code=? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).Scan(&count).Error
	return
}

type FenweiIndexDataCountGroup struct {
	IndexCode string
	Count     int
}

func GetFenweiIndexDataCountGroup(indexCodes []string) (items []*FenweiIndexDataCountGroup, err error) {
	if len(indexCodes) <= 0 {
		return
	}
	sql := ` SELECT COUNT(1) AS count, index_code FROM base_from_fenwei_data WHERE index_code IN (` + utils.GetOrmInReplace(len(indexCodes)) + `) GROUP BY index_code`
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCodes).Find(&items).Error
	return
}

func GetFenweiIndexData(indexCode string, startSize, pageSize int) (items []*BaseFromFenweiData, err error) {
	sql := ` SELECT *  FROM base_from_fenwei_data WHERE index_code=? ORDER BY data_time DESC LIMIT ?,? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode, startSize, pageSize).Find(&items).Error
	return
}

func GetFenweiIndexDataByCodes(indexCode []string) (items []*BaseFromFenweiData, err error) {
	if len(indexCode) <= 0 {
		return
	}
	sql := ` SELECT *  FROM base_from_fenwei_data WHERE index_code in (` + utils.GetOrmInReplace(len(indexCode)) + `) ORDER BY data_time DESC  `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).Find(&items).Error
	return
}

type BaseFromFenweiData struct {
	FenweiDataId  int `orm:"column(fenwei_data_id);pk" gorm:"primaryKey;"`
	FenweiIndexId int
	IndexCode     string
	DataTime      string
	Value         string
	CreateTime    string
	ModifyTime    string
	DataTimestamp int64
}

func (b *BaseFromFenweiData) AfterFind(tx *gorm.DB) (err error) {
		b.CreateTime = utils.GormDateStrToDateTimeStr(b.CreateTime)
		b.ModifyTime = utils.GormDateStrToDateTimeStr(b.ModifyTime)
		b.DataTime = utils.GormDateStrToDateStr(b.DataTime)
	return
}
type BaseFromFenweiIndexSearchItem struct {
	FenweiIndexId int `orm:"column(fenwei_index_id);pk"`
	ClassifyId    int
	IndexCode     string
	IndexName     string
}

// GetFenweiItemList 模糊查询汾渭数据库指标列表
func GetFenweiItemList(condition string) (items []*BaseFromFenweiIndexSearchItem, err error) {
	sql := "SELECT * FROM base_from_fenwei_index WHERE 1=1"
	if condition != "" {
		sql += condition
	}
	err = global.DbMap[utils.DbNameIndex].Raw(sql).Find(&items).Error
	return
}

func GetFenweiIndexDataByCode(indexCode string) (list []*BaseFromFenweiData, err error) {
	sql := `SELECT * FROM base_from_fenwei_data WHERE index_code=? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).Find(&list).Error
	return
}

func GetBaseFromFenweiIndexByIndexCode(indexCode string) (list *BaseFromFenweiIndex, err error) {
	sql := ` SELECT * FROM base_from_fenwei_index WHERE index_code=? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).First(&list).Error
	return
}

// GetFenWeiIndexFrequency 获取指标频度
func GetFenWeiIndexFrequency(classifyId int) (items []*string, err error) {
	sql := `SELECT DISTINCT frequency 
        FROM base_from_fenwei_index 
        WHERE frequency is not null`

	// 如果 classifyId > 0,则添加该条件
	if classifyId > 0 {
		sql += ` AND classify_id = ?`
	}

	sql += ` ORDER BY FIELD(frequency, '日度', '周度', '月度', '季度', '半年度', '年度')`

	if classifyId > 0 {
		err = global.DbMap[utils.DbNameIndex].Raw(sql, classifyId).Find(&items).Error
	} else {
		err = global.DbMap[utils.DbNameIndex].Raw(sql).Find(&items).Error
	}

	return items, err
}

// GetFenWeiIndexByCodeAndClassify 根据指标编码和分类查询 indexCode非必传
func GetFenWeiIndexByCodeAndClassify(indexCode string, classifyId int, frequency *string) (items []*BaseFromFenweiIndex, err error) {
	// SQL 查询语句
	sql := `SELECT a.index_code, a.index_name, a.frequency, a.unit, MAX(b.modify_time) AS modify_time
			FROM base_from_fenwei_index AS a
			INNER JOIN base_from_fenwei_data AS b ON a.fenwei_index_id = b.fenwei_index_id
			WHERE 1=1`

	var params []interface{}

	if classifyId != 0 {
		sql += ` AND a.classify_id = ?`
		params = append(params, classifyId)
	}

	// 如果 indexCode 不为空,增加过滤条件
	if indexCode != "" {
		sql += ` AND a.index_code = ?`
		params = append(params, indexCode)
	}

	if frequency != nil {
		sql += ` AND a.frequency = ?`
		params = append(params, *frequency)
	}

	sql += ` GROUP BY a.index_code, a.index_name, a.frequency, a.unit`

	err = global.DbMap[utils.DbNameIndex].Raw(sql, params...).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return
}

// GetBaseFromFenWeiDataByIndexCode 根据指标编码查询
func GetBaseFromFenWeiDataByIndexCode(indexCode string) (items []*BaseFromFenweiData, err error) {
	sql := `SELECT * FROM base_from_fenwei_data WHERE index_code=? ORDER BY data_time desc`
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).Find(&items).Error
	return
}

// GetFenWeiDataListByIndexCodes 根据指标编码查询
func GetFenWeiDataListByIndexCodes(IndexCodes string) (items []string, err error) {
	sql := ` SELECT DISTINCT data_time FROM base_from_fenwei_data WHERE index_code IN(` + IndexCodes + `)  ORDER BY data_time DESC `
	err = global.DbMap[utils.DbNameIndex].Raw(sql).Find(&items).Error
	if err != nil {
		return
	}
		for i := range items {
			items[i] = utils.GormDateStrToDateStr(items[i])
		}
	return
}

// GetFenWeiIndexInfoPage 分页查询指标信息
func GetFenWeiIndexInfoPage(condition string, pars []interface{}) (items []*BaseFromFenweiIndex, err error) {
	sql := ` SELECT * FROM base_from_fenwei_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY fenwei_index_id asc`
	err = global.DbMap[utils.DbNameIndex].Raw(sql, pars...).Find(&items).Error
	return

}

// GetFenWeiIndexInfoCount 查询指标信息总数
func GetFenWeiIndexInfoCount(condition string, pars []interface{}) (count int, err error) {
	sql := ` SELECT COUNT(1) AS count FROM base_from_fenwei_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	err = global.DbMap[utils.DbNameIndex].Raw(sql, pars...).Scan(&count).Error
	return
}

// GetFenWeiDataLastModifyTime 获取指标数据最新更新时间
func GetFenWeiDataLastModifyTime(indexCode string) (lastModifyTime string, err error) {
	sql := ` SELECT MAX(modify_time) AS last_modify_time FROM base_from_fenwei_data WHERE index_code=? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCode).Scan(&lastModifyTime).Error
	if err != nil {
		return
	}
	if lastModifyTime != "" {
		lastModifyTime = utils.GormDateStrToDateTimeStr(lastModifyTime)
	}
	return
}

// GetFenWeiDataLastModifyTimeList 查询指标数据最新更新时间
func GetFenWeiDataLastModifyTimeList(indexCodes []string) (items []*BaseFromFenweiData, err error) {
	sql := ` SELECT MAX(modify_time) AS modify_time, index_code FROM base_from_fenwei_data WHERE index_code IN(` + utils.GetOrmInReplace(len(indexCodes)) + `) GROUP BY index_code `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCodes).Find(&items).Error
	return
}