package data_manage

import (
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// FactorEdbSeriesCalculateDataQjjs 因子指标系列-区间计算数据表
type FactorEdbSeriesCalculateDataQjjs struct {
	FactorEdbSeriesCalculateDataId int       `orm:"column(factor_edb_series_calculate_data_id);pk"`
	FactorEdbSeriesId              int       `description:"因子指标系列ID"`
	EdbInfoId                      int       `description:"指标ID"`
	EdbCode                        string    `description:"指标编码"`
	DataTime                       time.Time `description:"数据日期"`
	Value                          float64   `description:"数据值"`
	CreateTime                     time.Time `description:"创建时间"`
	ModifyTime                     time.Time `description:"修改时间"`
	DataTimestamp                  int64     `description:"数据日期时间戳"`
}

func (m *FactorEdbSeriesCalculateDataQjjs) TableName() string {
	return "factor_edb_series_calculate_data_qjjs"
}

type FactorEdbSeriesCalculateDataQjjsCols struct {
	PrimaryId         string
	FactorEdbSeriesId string
	EdbInfoId         string
	EdbCode           string
	DataTime          string
	Value             string
	CreateTime        string
	ModifyTime        string
	DataTimestamp     string
}

func (m *FactorEdbSeriesCalculateDataQjjs) Cols() FactorEdbSeriesCalculateDataQjjsCols {
	return FactorEdbSeriesCalculateDataQjjsCols{
		PrimaryId:         "factor_edb_series_calculate_data_id",
		FactorEdbSeriesId: "factor_edb_series_id",
		EdbInfoId:         "edb_info_id",
		EdbCode:           "edb_code",
		DataTime:          "data_time",
		Value:             "value",
		CreateTime:        "create_time",
		ModifyTime:        "modify_time",
		DataTimestamp:     "data_timestamp",
	}
}

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

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

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

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

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

func (m *FactorEdbSeriesCalculateDataQjjs) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	_, err = o.Raw(sql, pars).Exec()
	return
}

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

func (m *FactorEdbSeriesCalculateDataQjjs) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *FactorEdbSeriesCalculateDataQjjs, 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 *FactorEdbSeriesCalculateDataQjjs) 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 *FactorEdbSeriesCalculateDataQjjs) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*FactorEdbSeriesCalculateDataQjjs, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *FactorEdbSeriesCalculateDataQjjs) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*FactorEdbSeriesCalculateDataQjjs, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
	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
}

// FactorEdbSeriesCalculateDataQjjsItem 因子指标系列-计算数据信息
type FactorEdbSeriesCalculateDataQjjsItem struct {
	DataId            int     `description:"数据ID"`
	FactorEdbSeriesId int     `description:"因子指标系列ID"`
	EdbInfoId         int     `description:"指标ID"`
	EdbCode           string  `description:"指标编码"`
	DataTime          string  `description:"数据日期"`
	Value             float64 `description:"数据值"`
}

func (m *FactorEdbSeriesCalculateDataQjjs) Format2Item() (item *FactorEdbSeriesCalculateDataQjjsItem) {
	item = new(FactorEdbSeriesCalculateDataQjjsItem)
	item.DataId = m.FactorEdbSeriesCalculateDataId
	item.FactorEdbSeriesId = m.FactorEdbSeriesId
	item.EdbInfoId = m.EdbInfoId
	item.EdbCode = m.EdbCode
	return
}

// TransEdbSeriesCalculateDataQjjs2EdbDataList 转换数据格式
func TransEdbSeriesCalculateDataQjjs2EdbDataList(items []*FactorEdbSeriesCalculateDataQjjs) (list []*EdbDataList) {
	list = make([]*EdbDataList, 0)
	for _, v := range items {
		list = append(list, &EdbDataList{
			DataTime: v.DataTime.Format(utils.FormatDate),
			Value:    v.Value,
		})
	}
	return
}

func (m *FactorEdbSeriesCalculateDataQjjs) GetEdbDataList(seriesId int, edbInfoId int, startDate, endDate string) (list []*EdbDataList, err error) {
	var pars []interface{}
	sql := `SELECT factor_edb_series_calculate_data_id as edb_data_id  ,edb_info_id,data_time,value,data_timestamp FROM %s WHERE edb_info_id=? and factor_edb_series_id=? `
	pars = append(pars, edbInfoId, seriesId)
	if startDate != "" {
		sql += ` AND data_time>=? `
		pars = append(pars, startDate)
	}
	if endDate != "" {
		sql += ` AND data_time<=? `
		pars = append(pars, endDate)
	}

	sql += ` ORDER BY data_time ASC `
	sql = fmt.Sprintf(sql, m.TableName())
	o := orm.NewOrmUsingDB("data")
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}
