// Package data_manage
// @Author gmy 2024/8/7 9:38:00
package data_manage

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

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

type BaseFromRzdIndex struct {
	BaseFromRzdIndexId    int    `orm:"column(base_from_rzd_index_id);pk" gorm:"primaryKey"`
	CreateTime            string `orm:"column(create_time)"`
	ModifyTime            string `orm:"column(modify_time)"`
	BaseFromRzdClassifyId int    `orm:"column(base_from_rzd_classify_id)"`
	IndexCode             string `orm:"column(index_code)"`
	IndexName             string `orm:"column(index_name)"`
	Frequency             string `orm:"column(frequency)"`
	Unit                  string `orm:"column(unit)"`
}

type BaseFromRzdIndexAndData struct {
	BaseFromRzdIndexId    int     `orm:"column(base_from_rzd_index_id);pk" gorm:"primaryKey"`
	CreateTime            string  `orm:"column(create_time)"`
	ModifyTime            string  `orm:"column(modify_time)"`
	BaseFromRzdClassifyId int     `orm:"column(base_from_rzd_classify_id)"`
	IndexCode             string  `orm:"column(index_code)"`
	IndexName             string  `orm:"column(index_name)"`
	Frequency             string  `orm:"column(frequency)"`
	Unit                  string  `orm:"column(unit)"`
	ModifyTimeMax         string  `json:"modify_time_max" description:"最后修改时间"`
	Value                 float64 `orm:"column(value)" description:"数据值"`
}

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

type BaseFromRzdIndexList struct {
	BaseFromRzdIndexId    int                `gorm:"column:base_from_rzd_index_id;primaryKey"`
	CreateTime            string             `orm:"column(create_time)"`
	ModifyTime            string             `orm:"column(modify_time)"`
	BaseFromRzdClassifyId int                `orm:"column(base_from_rzd_classify_id)"`
	IndexCode             string             `orm:"column(index_code)"`
	IndexName             string             `orm:"column(index_name)"`
	Frequency             string             `orm:"column(frequency)"`
	Unit                  string             `orm:"column(unit)"`
	DataList              []*BaseFromRzdData `gorm:"-"`
	Paging                *paging.PagingItem `description:"分页数据" gorm:"-"`
	EdbInfoId             int                `description:"指标库主键id"`
}

func (baseFromRzdIndexList *BaseFromRzdIndexList) AfterFind(tx *gorm.DB) (err error) {
			baseFromRzdIndexList.ModifyTime = utils.GormDateStrToDateTimeStr(baseFromRzdIndexList.ModifyTime)
			baseFromRzdIndexList.CreateTime = utils.GormDateStrToDateTimeStr(baseFromRzdIndexList.CreateTime)
	return
}

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

// RzdIndexCheckData 校验编码是否存在
type RzdIndexCheckData 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"`
}

// BaseFromRzdIndexBatchAddCheckReq 校验编码是否存在请求参数
type BaseFromRzdIndexBatchAddCheckReq struct {
	IndexCodes     []string `form:"IndexCodes" description:"指标编码列表"`
	ClassifyIdList []int    `description:"分类id"`
	FrequencyList  []string `description:"频度"`
	SearchParams   string   `description:"搜索参数 指标编码/指标名称"`
	IsCheckAll     bool     `description:"是否全选"`
}


// GetRzdIndexByClassifyIds 根据分类id获取指标信息
func GetRzdIndexByClassifyIds(classifyIds []int) (items []*BaseFromRzdIndex, err error) {
	o := global.DbMap[utils.DbNameIndex]

	sql := fmt.Sprintf(`SELECT * FROM base_from_rzd_index WHERE base_from_rzd_classify_id IN (`+utils.GetOrmInReplace(len(classifyIds))) + `)`
	err = o.Raw(sql, classifyIds).Find(&items).Error
	if err != nil {
		return nil, err
	}

	return items, nil
}

func GetRzdIndex(condition string, pars []interface{}) (items []*BaseFromRzdIndexList, err error) {
	o := global.DbMap[utils.DbNameIndex]
	sql := ` SELECT * FROM base_from_rzd_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY base_from_rzd_index_id asc`
	err = o.Raw(sql, pars...).Find(&items).Error
	return
}

func GetRzdIndexNotExistEdbInfoCount(condition string, pars []interface{}) (count int, err error) {
	o := global.DbMap[utils.DbNameIndex]
	sql := ` SELECT count(1) FROM base_from_rzd_index WHERE index_code not in (select edb_code from edb_info) `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars...).Scan(&count).Error
	return
}

func GetRzdIndexNotExistEdbInfoPage(condition string, pars []interface{}) (items []*BaseFromRzdIndexAndData, err error) {
	o := global.DbMap[utils.DbNameIndex]
	sql := ` SELECT * FROM base_from_rzd_index WHERE index_code not in (select edb_code from edb_info) `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars...).Find(&items).Error
	return
}

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

	// 如果 classifyId > 0,则添加该条件
	if len(classifyIdList) > 0 {
		sql += ` AND base_from_rzd_classify_id in (` + utils.GetOrmInReplace(len(classifyIdList)) + `)`
	}

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

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

	return items, err
}

// GetRzdIndexByCodeAndClassify 根据指标编码和分类查询 indexCode非必传
func GetRzdIndexByCodeAndClassify(indexCode string, classifyIdList []int, frequency *string) (items []*BaseFromRzdIndex, err error) {
	o := global.DbMap[utils.DbNameIndex]

	// SQL 查询语句
	sql := `SELECT a.index_code, a.index_name, a.frequency, a.unit, MAX(b.modify_time) AS modify_time
			FROM base_from_rzd_index AS a
			INNER JOIN base_from_rzd_data AS b ON a.base_from_rzd_index_id = b.base_from_rzd_index_id
			WHERE 1=1`

	var params []interface{}

	if len(classifyIdList) > 0 {
		sql += ` AND a.base_from_rzd_classify_id in (` + utils.GetOrmInReplace(len(classifyIdList)) + `)`
		//for _, id := range classifyIdList {
		//	params = append(params, id)
		//}
		params = append(params, classifyIdList)
	}

	// 如果 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...).Find(&items).Error
	if err != nil {
		return nil, err
	}
	return
}

// GetRzdIndexInfoCount 分页查询指标信息行数
func GetRzdIndexInfoCount(condition string, pars []interface{}) (count int, err error) {
	o := global.DbMap[utils.DbNameIndex]
	sql := ` SELECT count(1) FROM base_from_rzd_index WHERE index_code not in (select edb_code from edb_info) `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars...).Scan(&count).Error
	return
}

// GetRzdIndexInfoPage 分页查询指标信息
func GetRzdIndexInfoPage(condition string, pars []interface{}) (items []*BaseFromRzdIndexAndData, err error) {
	o := global.DbMap[utils.DbNameIndex]
	sql := ` SELECT * FROM base_from_rzd_index WHERE index_code not in (select edb_code from edb_info) `
	if condition != "" {
		sql += condition
	}
	err = o.Raw(sql, pars...).Find(&items).Error
	return

}