package data_manage

import (
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

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

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) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_fenwei_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY sort ASC, fenwei_index_id asc`
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func GetFenweiIndexDataCount(indexCode string) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT COUNT(1) AS count FROM base_from_fenwei_data WHERE index_code=? `
	err = o.Raw(sql, indexCode).QueryRow(&count)
	return
}

type FenweiIndexDataCountGroup struct {
	IndexCode string
	Count     int
}

func GetFenweiIndexDataCountGroup(indexCodes []string) (items []*FenweiIndexDataCountGroup, err error) {
	if len(indexCodes) <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	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 = o.Raw(sql, indexCodes).QueryRows(&items)
	return
}

func GetFenweiIndexData(indexCode string, startSize, pageSize int) (items []*BaseFromFenweiData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT *  FROM base_from_fenwei_data WHERE index_code=? ORDER BY data_time DESC LIMIT ?,? `
	_, err = o.Raw(sql, indexCode, startSize, pageSize).QueryRows(&items)
	return
}

func GetFenweiIndexDataByCodes(indexCode []string) (items []*BaseFromFenweiData, err error) {
	if len(indexCode) <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT *  FROM base_from_fenwei_data WHERE index_code in (` + utils.GetOrmInReplace(len(indexCode)) + `) ORDER BY data_time DESC  `
	_, err = o.Raw(sql, indexCode).QueryRows(&items)
	return
}

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

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) {
	o := orm.NewOrmUsingDB("data")
	sql := "SELECT * FROM base_from_fenwei_index WHERE 1=1"
	if condition != "" {
		sql += condition
	}
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

func GetFenweiIndexDataByCode(indexCode string) (list []*BaseFromFenweiData, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM base_from_fenwei_data WHERE index_code=? `
	_, err = o.Raw(sql, indexCode).QueryRows(&list)
	return
}

func GetBaseFromFenweiIndexByIndexCode(indexCode string) (list *BaseFromFenweiIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := ` SELECT * FROM base_from_fenwei_index WHERE index_code=? `
	err = o.Raw(sql, indexCode).QueryRow(&list)
	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, '日度', '周度', '月度', '季度', '半年度', '年度')`

	o := orm.NewOrmUsingDB("data")
	if classifyId > 0 {
		_, err = o.Raw(sql, classifyId).QueryRows(&items)
	} else {
		_, err = o.Raw(sql).QueryRows(&items)
	}

	return items, err
}

// GetFenWeiIndexByCodeAndClassify 根据指标编码和分类查询 indexCode非必传
func GetFenWeiIndexByCodeAndClassify(indexCode string, classifyId int, frequency *string) (items []*BaseFromFenweiIndex, err error) {
	o := orm.NewOrmUsingDB("data")

	// 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 = o.Raw(sql, params...).QueryRows(&items)
	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`
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql, indexCode).QueryRows(&items)
	return
}

// GetFenWeiDataListByIndexCodes 根据指标编码查询
func GetFenWeiDataListByIndexCodes(IndexCodes string) (items []string, err error) {
	sql := ` SELECT data_time FROM base_from_fenwei_data WHERE index_code IN(` + IndexCodes + `)  GROUP BY data_time DESC `
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql).QueryRows(&items)
	return
}

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

}

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