package models

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

// BaseFromThsHfData 同花顺高频数据-指标数据
type BaseFromThsHfData struct {
	BaseFromThsHfDataId  int       `orm:"column(base_from_ths_hf_data_id);pk"`
	BaseFromThsHfIndexId int       `description:"指标ID"`
	IndexCode            string    `description:"指标编码"`
	DataTime             time.Time `description:"数据日期（至时分秒）"`
	Value                float64   `description:"数据值"`
	UniqueCode           string    `description:"唯一编码"`
	CreateTime           time.Time `description:"创建时间"`
	ModifyTime           time.Time `description:"修改时间"`
	DataTimestamp        int64     `description:"数据日期时间戳"`
}

func (m *BaseFromThsHfData) TableName() string {
	return "base_from_ths_hf_data"
}

type BaseFromThsHfDataCols struct {
	PrimaryId            string
	BaseFromThsHfIndexId string
	IndexCode            string
	DataTime             string
	Value                string
	UniqueCode           string
	CreateTime           string
	ModifyTime           string
	DataTimestamp        string
}

func (m *BaseFromThsHfData) Cols() BaseFromThsHfDataCols {
	return BaseFromThsHfDataCols{
		PrimaryId:            "base_from_ths_hf_data_id",
		BaseFromThsHfIndexId: "base_from_ths_hf_index_id",
		IndexCode:            "index_code",
		DataTime:             "data_time",
		Value:                "value",
		UniqueCode:           "unique_code",
		CreateTime:           "create_time",
		ModifyTime:           "modify_time",
		DataTimestamp:        "data_timestamp",
	}
}

func (m *BaseFromThsHfData) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.BaseFromThsHfDataId = int(id)
	return
}

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

func (m *BaseFromThsHfData) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

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

func (m *BaseFromThsHfData) MultiRemove(ids []int) (err error) {
	if len(ids) == 0 {
		return
	}
	o := orm.NewOrm()
	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 *BaseFromThsHfData) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	o := orm.NewOrm()
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	_, err = o.Raw(sql, pars).Exec()
	return
}

func (m *BaseFromThsHfData) GetItemById(id int) (item *BaseFromThsHfData, err error) {
	o := orm.NewOrm()
	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 *BaseFromThsHfData) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *BaseFromThsHfData, err error) {
	o := orm.NewOrm()
	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 *BaseFromThsHfData) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	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 *BaseFromThsHfData) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*BaseFromThsHfData, err error) {
	o := orm.NewOrm()
	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 *BaseFromThsHfData) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*BaseFromThsHfData, err error) {
	o := orm.NewOrm()
	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
}

// BaseFromThsHfDataItem 同花顺高频数据信息
type BaseFromThsHfDataItem struct {
	DataId     int     `description:"数据ID"`
	IndexId    int     `description:"指标ID"`
	IndexCode  string  `description:"指标编码"`
	DataTime   string  `description:"数据日期（至时分秒）"`
	Value      float64 `description:"数据值"`
	UniqueCode string  `description:"唯一编码"`
}

func (m *BaseFromThsHfData) Format2Item() (item *BaseFromThsHfDataItem) {
	item = new(BaseFromThsHfDataItem)
	item.DataId = m.BaseFromThsHfDataId
	item.IndexId = m.BaseFromThsHfIndexId
	item.IndexCode = m.IndexCode
	item.DataTime = utils.TimeTransferString(utils.FormatDateTime, m.DataTime)
	item.Value = m.Value
	item.UniqueCode = m.UniqueCode
	return
}

func (m *BaseFromThsHfData) MultiInsertOrUpdate(inserts, updates []*BaseFromThsHfData) (err error) {
	o := orm.NewOrm()
	if len(inserts) > 0 {
		_, e := o.InsertMulti(600, inserts)
		if e != nil {
			err = fmt.Errorf("insert multi err: %s", e.Error())
			return
		}
	}
	if len(updates) > 0 {
		sql := fmt.Sprintf("UPDATE %s SET %s = ?, modify_time = NOW() WHERE %s = ?", m.TableName(), m.Cols().Value, m.Cols().UniqueCode)
		p, e := o.Raw(sql).Prepare()
		if e != nil {
			err = fmt.Errorf("prepare err: %s", e.Error())
			return
		}
		defer func() {
			_ = p.Close()
		}()
		for _, v := range updates {
			_, e = p.Exec(v.Value, v.UniqueCode)
			if e != nil {
				err = fmt.Errorf("update err: %s", e.Error())
				return
			}
		}
	}
	return
}

func (m *BaseFromThsHfData) GetIndexMinMax(indexCode string) (item *EdbInfoMaxAndMinInfo, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT MIN(%s) AS min_date, MAX(%s) AS max_date, MIN(%s) AS min_value,MAX(%s) AS max_value FROM %s WHERE %s = ?`, m.Cols().DataTime, m.Cols().DataTime, m.Cols().Value, m.Cols().Value, m.TableName(), m.Cols().IndexCode)
	err = o.Raw(sql, indexCode).QueryRow(&item)
	if err != nil {
		return
	}

	// 获取最新值
	var lastVal float64
	sql = fmt.Sprintf(`SELECT %s AS latest_value FROM %s WHERE %s = ? ORDER BY %s DESC LIMIT 1`, m.Cols().Value, m.TableName(), m.Cols().IndexCode, m.Cols().DataTime)
	err = o.Raw(sql, indexCode).QueryRow(&lastVal)
	if err != nil {
		return
	}
	item.LatestValue = lastVal
	return
}
