package data_manage

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

// BaseFromBloombergIndex 彭博原始指标表
type BaseFromBloombergIndex struct {
	BaseFromBloombergIndexId int       `orm:"column(base_from_bloomberg_index_id);pk"`
	IndexCode                string    `description:"指标编码"`
	IndexName                string    `description:"指标名称"`
	Unit                     string    `description:"单位"`
	Source                   int       `description:"数据来源"`
	Frequency                string    `description:"频度"`
	StartDate                time.Time `description:"开始日期"`
	EndDate                  time.Time `description:"结束日期"`
	Describe                 string    `description:"指标描述"`
	Sort                     int       `description:"排序"`
	IsStop                   int       `description:"是否停更：0-否；1-停更"`
	EdbExist                 int       `description:"指标库是否已添加：0-否；1-是"`
	TerminalCode             string    `description:"所属终端编码"`
	FilePath                 string    `description:"文件存储路径"`
	CreateTime               time.Time `description:"创建时间"`
	ModifyTime               time.Time `description:"修改时间"`
}

var BaseFromBloombergIndexCols = struct {
	BaseFromBloombergIndexId string
	IndexCode                string
	IndexName                string
	Unit                     string
	Source                   string
	Frequency                string
	StartDate                string
	EndDate                  string
	Describe                 string
	Sort                     string
	IsStop                   string
	EdbExist                 string
	TerminalCode             string
	FilePath                 string
	CreateTime               string
	ModifyTime               string
}{
	BaseFromBloombergIndexId: "base_from_bloomberg_index_id",
	IndexCode:                "index_code",
	IndexName:                "index_name",
	Unit:                     "unit",
	Source:                   "source",
	Frequency:                "frequency",
	StartDate:                "start_date",
	EndDate:                  "end_date",
	Describe:                 "describe",
	Sort:                     "sort",
	IsStop:                   "is_stop",
	EdbExist:                 "edb_exist",
	TerminalCode:             "terminal_code",
	FilePath:                 "file_path",
	CreateTime:               "create_time",
	ModifyTime:               "modify_time",
}

func (m *BaseFromBloombergIndex) TableName() string {
	return "base_from_bloomberg_index"
}

func (m *BaseFromBloombergIndex) PrimaryId() string {
	return BaseFromBloombergIndexCols.BaseFromBloombergIndexId
}

func (m *BaseFromBloombergIndex) Create() (err error) {
	o := orm.NewOrmUsingDB("data")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.BaseFromBloombergIndexId = int(id)
	return
}

func (m *BaseFromBloombergIndex) CreateMulti(items []*BaseFromBloombergIndex) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *BaseFromBloombergIndex) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, cols...)
	return
}

func (m *BaseFromBloombergIndex) Del() (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	_, err = o.Raw(sql, m.BaseFromBloombergIndexId).Exec()
	return
}

func (m *BaseFromBloombergIndex) MultiDel(menuIds []int) (err error) {
	if len(menuIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
	_, err = o.Raw(sql, menuIds).Exec()
	return
}

func (m *BaseFromBloombergIndex) GetItemById(id int) (item *BaseFromBloombergIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *BaseFromBloombergIndex) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *BaseFromBloombergIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	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 = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *BaseFromBloombergIndex) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *BaseFromBloombergIndex) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, limit int) (items []*BaseFromBloombergIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	if limit > 0 {
		sql += fmt.Sprintf(` LIMIT %d`, limit)
	}
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *BaseFromBloombergIndex) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*BaseFromBloombergIndex, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

// BaseFromBloombergIndexItem 彭博原始指标信息
type BaseFromBloombergIndexItem struct {
	BaseFromBloombergIndexId int
	IndexCode                string `description:"指标编码"`
	IndexName                string `description:"指标名称"`
	Unit                     string `description:"单位"`
	Source                   int    `description:"数据来源"`
	Frequency                string `description:"频度"`
	StartDate                string `description:"开始日期"`
	EndDate                  string `description:"结束日期"`
	Describe                 string `description:"指标描述"`
	Sort                     int    `description:"排序"`
	IsStop                   int    `description:"是否停更：0-否；1-停更"`
	EdbExist                 int    `description:"指标库是否已添加：0-否；1-是"`
	CreateTime               string `description:"创建时间"`
	ModifyTime               string `description:"修改时间"`
	EdbInfoId                int    `description:"指标库ID"`
	EdbUniqueCode            string `description:"指标库唯一编码"`
	EdbClassifyId            int    `description:"指标库分类ID"`
}

func FormatBaseFromBloombergIndex2Item(origin *BaseFromBloombergIndex) (item *BaseFromBloombergIndexItem) {
	if origin == nil {
		return
	}
	item = new(BaseFromBloombergIndexItem)
	item.BaseFromBloombergIndexId = origin.BaseFromBloombergIndexId
	item.IndexCode = origin.IndexCode
	item.IndexName = origin.IndexName
	item.Unit = origin.Unit
	item.Source = origin.Source
	item.Frequency = origin.Frequency
	item.StartDate = utils.TimeTransferString(utils.FormatDate, origin.StartDate)
	item.EndDate = utils.TimeTransferString(utils.FormatDate, origin.EndDate)
	item.Describe = origin.Describe
	item.Sort = origin.Sort
	item.IsStop = origin.IsStop
	//item.EdbExist = origin.EdbExist
	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, origin.CreateTime)
	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, origin.ModifyTime)
	return
}

// BloombergSourceListReq 指标列表筛选
type BloombergSourceListReq struct {
	PageSize     int    `form:"PageSize"`
	CurrentIndex int    `form:"CurrentIndex"`
	Frequency    string `form:"Frequency" description:"频度"`
	Keywords     string `form:"Keywords" description:"指标ID/指标名称"`
	ListAll      bool   `form:"ListAll" description:"列表全选"`
	SortField    int    `form:"SortField" description:"排序字段: 0-默认; 1-开始时间; 2-最新时间; 3-更新时间"`
	SortRule     int    `form:"SortRule" description:"排序方式: 0-默认; 1-正序; 2-倒序"`
}

// BloombergSourceListResp 指标列表响应体
type BloombergSourceListResp struct {
	List   []*BaseFromBloombergIndexItem
	Paging *paging.PagingItem `description:"分页数据"`
}

// UpdateEdbExist 标记已添加指标库
func (m *BaseFromBloombergIndex) UpdateEdbExist(indexCode string) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`UPDATE %s SET %s = ? WHERE %s = ? LIMIT 1`, m.TableName(), BaseFromBloombergIndexCols.EdbExist, BaseFromBloombergIndexCols.IndexCode)
	_, err = o.Raw(sql, 1, indexCode).Exec()
	return
}

// BloombergSourceBatchAddCheckReq Bloomberg批量添加校验
type BloombergSourceBatchAddCheckReq struct {
	BloombergSourceListReq
	IndexCodes []string `form:"IndexCodes" description:"全选为false时, 该数组为选中; 全选为true时, 该数组为不选的指标"`
}

// --------------------------------------------- 以下为测试用 ---------------------------------------------

// BaseFromBloombergData 彭博原始指标表
//type BaseFromBloombergData struct {
//	BaseFromBloombergDataId  int       `orm:"column(base_from_bloomberg_data_id);pk"`
//	BaseFromBloombergIndexId int       `description:"指标ID"`
//	IndexCode                string    `description:"指标编码"`
//	DataTime                 time.Time `description:"数据日期"`
//	Value                    float64   `description:"数据值"`
//	CreateTime               time.Time `description:"创建时间"`
//	ModifyTime               time.Time `description:"修改时间"`
//	DataTimestamp            int       `description:"数据日期时间戳"`
//}
//
//func (m *BaseFromBloombergData) TableName() string {
//	return "base_from_bloomberg_data"
//}
//
//func (m *BaseFromBloombergData) Create() (err error) {
//	o := orm.NewOrmUsingDB("data")
//	id, err := o.Insert(m)
//	if err != nil {
//		return
//	}
//	m.BaseFromBloombergDataId = int(id)
//	return
//}
//
//func (m *BaseFromBloombergData) CreateMulti(items []*BaseFromBloombergData) (err error) {
//	if len(items) == 0 {
//		return
//	}
//	o := orm.NewOrmUsingDB("data")
//	_, err = o.InsertMulti(len(items), items)
//	return
//}
