package models

import (
	sql2 "database/sql"
	"eta/eta_index_lib/global"
	"eta/eta_index_lib/utils"
	"fmt"
	"strings"
	"time"
)

// BaseFromThsHfData 同花顺高频数据-指标数据
type BaseFromThsHfData struct {
	BaseFromThsHfDataId  int       `gorm:"column:base_from_ths_hf_data_id;type:int(10) UNSIGNED;primaryKey;not null;"`
	BaseFromThsHfIndexId int       `gorm:"column:base_from_ths_hf_index_id;type:int(10) UNSIGNED;comment:指标id;not null;"`      // 指标id
	IndexCode            string    `gorm:"column:index_code;type:varchar(255);comment:指标编码;not null;"`                         // 指标编码
	DataTime             time.Time `gorm:"column:data_time;type:datetime;comment:数据日期(至时分秒);default:NULL;"`                    // 数据日期(至时分秒)
	Value                float64   `gorm:"column:value;type:double;comment:数据值;default:NULL;"`                                 // 数据值
	UniqueCode           string    `gorm:"column:unique_code;type:varchar(64);comment:唯一编码;not null;"`                         // 唯一编码
	CreateTime           time.Time `gorm:"column:create_time;type:datetime;comment:创建时间;default:NULL;"`                        // 创建时间
	ModifyTime           time.Time `gorm:"column:modify_time;type:datetime;comment:修改时间;default:NULL;"`                        // 修改时间
	DataTimestamp        int64     `gorm:"column:data_timestamp;type:bigint(20) UNSIGNED;comment:数据日期时间戳;not null;default:0;"` // 数据日期时间戳
}

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) {
	err = global.DEFAULT_DB.Create(m).Error

	return
}

func (m *BaseFromThsHfData) CreateMulti(items []*BaseFromThsHfData) (err error) {
	if len(items) == 0 {
		return
	}
	err = global.DEFAULT_DB.CreateInBatches(items, utils.MultiAddNum).Error

	return
}

func (m *BaseFromThsHfData) Update(cols []string) (err error) {
	err = global.DEFAULT_DB.Select(cols).Updates(m).Error

	return
}

func (m *BaseFromThsHfData) Remove() (err error) {
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = global.DEFAULT_DB.Exec(sql, m.BaseFromThsHfDataId).Error

	return
}

func (m *BaseFromThsHfData) MultiRemove(ids []int) (err error) {
	if len(ids) == 0 {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.Cols().PrimaryId, utils.GetOrmInReplace(len(ids)))
	err = global.DEFAULT_DB.Exec(sql, ids).Error

	return
}

func (m *BaseFromThsHfData) RemoveByCondition(condition string, pars []interface{}) (err error) {
	if condition == "" {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
	err = global.DEFAULT_DB.Exec(sql, pars).Error

	return
}

func (m *BaseFromThsHfData) GetItemById(id int) (item *BaseFromThsHfData, err error) {
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
	err = global.DEFAULT_DB.Raw(sql, id).First(&item).Error

	return
}

func (m *BaseFromThsHfData) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *BaseFromThsHfData, err error) {
	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 = global.DEFAULT_DB.Raw(sql, pars...).First(&item).Error

	return
}

func (m *BaseFromThsHfData) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = global.DEFAULT_DB.Raw(sql, pars...).Scan(&count).Error

	return
}

func (m *BaseFromThsHfData) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*BaseFromThsHfData, err error) {
	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 = global.DEFAULT_DB.Raw(sql, pars...).Find(&items).Error

	return
}

func (m *BaseFromThsHfData) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*BaseFromThsHfData, err error) {
	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)
	pars = append(pars, startSize, pageSize)

	err = global.DEFAULT_DB.Raw(sql, pars...).Find(&items).Error

	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) {
	tx := global.DEFAULT_DB.Begin()
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()
	if len(inserts) > 0 {
		e := tx.CreateInBatches(inserts, utils.MultiAddNum).Error
		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)
		for _, v := range updates {
			e := tx.Exec(sql, v.Value, v.UniqueCode).Error
			if e != nil {
				err = fmt.Errorf("update err: %s", e.Error())
				return
			}
		}
	}
	return
}

func (m *BaseFromThsHfData) GetIndexMinMax(indexCode string) (item *EdbInfoMaxAndMinInfo, err error) {
	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 = global.DEFAULT_DB.Raw(sql, indexCode).First(&item).Error
	if err != nil {
		return
	}

	// 获取最新值
	var latestValueNull sql2.NullFloat64
	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 = global.DEFAULT_DB.Raw(sql, indexCode).Scan(&latestValueNull).Error
	if err == nil && latestValueNull.Valid {
		item.LatestValue = latestValueNull.Float64
	}

	return
}