package data_manage

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

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

type BaseFromCCFIndex struct {
	BaseFromCcfIndexId int `orm:"column(base_from_ccf_index_id);pk"`
	ClassifyId         int
	IndexCode          string
	IndexName          string
	Frequency          string
	Unit               string
	Sort               int
	CreateTime         time.Time
	ModifyTime         time.Time
}

type BaseFromCCFIndexList struct {
	BaseFromCcfIndexId int `orm:"column(base_from_ccf_index_id);pk"`
	EdbInfoId          int
	ClassifyId         int
	IndexCode          string
	IndexName          string
	Frequency          string
	Unit               string
	Sort               int
	CreateTime         string
	ModifyTime         string
	EndDate            string
	EndValue           string
	EdbExist           int                `description:"指标库是否已添加:0-否;1-是"`
	DataList           []*BaseFromCCFData `gorm:"-"`
	Paging             *paging.PagingItem `description:"分页数据" gorm:"-"`
}
func (b *BaseFromCCFIndexList) TableName() string {
	return "base_from_ccf_index"
}

func (b *BaseFromCCFIndexList) AfterFind(tx *gorm.DB) (err error) {
		b.ModifyTime = utils.GormDateStrToDateTimeStr(b.ModifyTime)
		b.CreateTime = utils.GormDateStrToDateTimeStr(b.CreateTime)
		b.EndDate = utils.GormDateStrToDateStr(b.EndDate)
	return
}

type CCFSingleDataResp struct {
	BaseFromCcfIndexId int
	ClassifyId         int
	IndexCode          string
	IndexName          string
	Frequency          string
	Unit               string
	CreateTime         string
	ModifyTime         string
	Data               []*CCFSingleData
}

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

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

func GetCCFIndexDataCount(indexCode string) (count int, err error) {
	sqlStr := ` SELECT COUNT(1) AS count FROM base_from_ccf_data WHERE index_code=? `
	var totalNull sql.NullInt64
	err = global.DbMap[utils.DbNameIndex].Raw(sqlStr, indexCode).Scan(&totalNull).Error
	if !totalNull.Valid {
		count = 0
	} else {
		count = int(totalNull.Int64)
	}
	return
}

type CCFIndexDataCountGroup struct {
	IndexCode string
	Count     int
}

func GetCCFIndexDataCountGroup(indexCodes []string) (items []*CCFIndexDataCountGroup, err error) {
	if len(indexCodes) <= 0 {
		return
	}
	sql := ` SELECT COUNT(1) AS count, index_code FROM base_from_ccf_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 GetCCFIndexData(indexCode string, startSize, pageSize int) (items []*BaseFromCCFData, err error) {
	sql := ` SELECT *  FROM base_from_ccf_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 GetCCFIndexDataByCodes(indexCode []string) (items []*BaseFromCCFData, err error) {
	if len(indexCode) <= 0 {
		return
	}
	sql := ` SELECT *  FROM base_from_ccf_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 BaseFromCCFData struct {
	BaseFromCcfDataId  int `orm:"column(base_from_ccf_data_id);pk"`
	BaseFromCcfIndexId int
	IndexCode          string
	DataTime           string
	Value              string
	CreateTime         string
	ModifyTime         string
	DataTimestamp      int64
}

func (baseFromCCFData *BaseFromCCFData) AfterFind(tx *gorm.DB) (err error) {
			baseFromCCFData.ModifyTime = utils.GormDateStrToDateTimeStr(baseFromCCFData.ModifyTime)
			baseFromCCFData.CreateTime = utils.GormDateStrToDateTimeStr(baseFromCCFData.CreateTime)
			baseFromCCFData.DataTime = utils.GormDateStrToDateStr(baseFromCCFData.DataTime)
	return
}

type BaseFromCCFIndexSearchItem struct {
	BaseFromCcfIndexId int `orm:"column(base_from_ccf_index_id);pk"`
	ClassifyId         int
	IndexCode          string
	IndexName          string
}

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

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

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

func GetCCFIndexPage(condition string, pars []interface{}, startSize, pageSize int) (items []*BaseFromCCFIndexList, err error) {
	sql := ` SELECT * FROM base_from_ccf_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	sql += ` ORDER BY sort ASC, base_from_ccf_index_id asc LIMIT ?,?`
	pars = append(pars, startSize, pageSize)
	err = global.DbMap[utils.DbNameIndex].Raw(sql, pars...).Find(&items).Error
	return
}

func GetCCFIndexPageCount(condition string, pars []interface{}) (count int, err error) {
	sql := ` SELECT COUNT(1) AS count  FROM base_from_ccf_index WHERE 1=1  `
	if condition != "" {
		sql += condition
	}
	err = global.DbMap[utils.DbNameIndex].Raw(sql, pars...).Scan(&count).Error
	return
}

type BaseFromCCFIndexSearchList struct {
	List   []*BaseFromCCFIndexList
	Paging *paging.PagingItem `description:"分页数据"`
}

type CCFIndexSource2EdbReq struct {
	EdbCode       string
	EdbName       string
	Frequency     string
	Unit          string
	ClassifyId    int
	AdminId       int
	AdminRealName string
}

// BatchCheckCCFEdbReq 指标数据结构体
type BatchCheckCCFEdbReq struct {
	//IsJoinEdb      int      `form:"IsJoinEdb" description:"是否加到指标库,0:未加到指标库"`
	Frequencies   string `description:"频度;枚举值:日度、周度、月度、季度、半年度、年度"`
	Keyword       string `description:"关键字"`
	ClassifyIds   string `description:"所选品种id列表"`
	ListAll       bool   `form:"ListAll" json:"ListAll" description:"列表全选"`
	TradeCodeList string `form:"TradeCodeList" json:"TradeCodeList" description:"全选为false时, 该数组为选中; 全选为true时, 该数组为不选的指标"`
}

func GetCCFFrequencyByClassifyId(classifyId int) (items []*GlFrequency, err error) {
	sql := ` SELECT frequency FROM base_from_ccf_index WHERE classify_id = ? `
	sql += ` GROUP BY frequency ORDER BY frequency ASC `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, classifyId).Find(&items).Error
	return
}

func GetCCFIndexDataByDataTime(indexCodes []string, startDate, endDate string) (items []*BaseFromCCFData, err error) {
	sql := ` SELECT *  FROM base_from_ccf_data WHERE  index_code in (` + utils.GetOrmInReplace(len(indexCodes)) + `) and data_time >=? and data_time <? ORDER BY data_time DESC `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCodes, startDate, endDate).Find(&items).Error
	return
}

func GetCCFIndexDataTimePageByCodes(indexCodes []string, startSize, pageSize int) (dataTimes []string, err error) {
	sql := ` SELECT data_time FROM base_from_ccf_data WHERE index_code in (` + utils.GetOrmInReplace(len(indexCodes)) + `) GROUP BY data_time ORDER BY data_time DESC LIMIT ?,? `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexCodes, startSize, pageSize).Find(&dataTimes).Error
		for i := range dataTimes {
			dataTimes[i] = utils.GormDateStrToDateStr(dataTimes[i])
		}
	return
}

func GetCCFIndexDataTimePageCount(indexCodes []string) (count int, err error) {
	//sqlStr := ` SELECT COUNT(DISTINCT data_time) AS count  FROM base_from_ccf_data WHERE index_code in (` + utils.GetOrmInReplace(len(indexCodes)) + `)`
	sqlStr := ` SELECT COUNT(DISTINCT data_time) AS count  FROM base_from_ccf_data WHERE index_code in ?`
	var totalNull sql.NullInt64
	err = global.DbMap[utils.DbNameIndex].Raw(sqlStr, indexCodes).Scan(&count).Error
	if !totalNull.Valid {
		count = 0
	} else {
		count = int(totalNull.Int64)
	}
	return
}

// GetCCFDataDataTimeByIndexId 根据指标id获取指标数据的日期列表
func GetCCFDataDataTimeByIndexId(indexIdList []int) (items []string, err error) {
	if len(indexIdList) == 0 {
		return
	}
	sql := ` SELECT DISTINCT data_time FROM base_from_ccf_data WHERE base_from_ccf_index_id IN (` + utils.GetOrmInReplace(len(indexIdList)) + `) ORDER BY data_time DESC`
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexIdList).Scan(&items).Error
	if err != nil {
		return
	}
		for i := range items {
			items[i] = utils.GormDateStrToDateStr(items[i])
		}
	return
}

func GetCCFIndexDataByIndexIdAndDataTime(indexId []int, dataTimeList []string) (items []*BaseFromCCFData, err error) {
	sql := ` SELECT *  FROM base_from_ccf_data WHERE  base_from_ccf_index_id in (` + utils.GetOrmInReplace(len(indexId)) + `) and data_time in (` + utils.GetOrmInReplace(len(dataTimeList)) + `)  `
	err = global.DbMap[utils.DbNameIndex].Raw(sql, indexId, dataTimeList).Find(&items).Error
	return
}