package models

// 企业风管期货商品相关

import (
	"fmt"
	"mtp2_if/db"
	"time"
)

// Goodssortbypreposition 合约昨持仓排序表 - 同一品种内按昨持仓量倒排序
// 行情服务清盘前生成此表，供交易服务风控规则使用；生成前先删除此表数据；
type Goodssortbypreposition struct {
	Tradedate      string    `json:"tradedate"  xorm:"'TRADEDATE'" binding:"required"` // 交易日
	Goodscode      string    `json:"goodscode"  xorm:"'GOODSCODE'" binding:"required"` // 合约代码 - 易盛接口:合约代码=品种代码+合约代码
	Goodsgroupcode string    `json:"goodsgroupcode"  xorm:"'GOODSGROUPCODE'"`          // 品种代码
	Sortindex      int64     `json:"sortindex"  xorm:"'SORTINDEX'"`                    // 排序
	Prepositionqty int64     `json:"prepositionqty"  xorm:"'PREPOSITIONQTY'"`          // 昨持仓量
	Updatetime     time.Time `json:"updatetime"  xorm:"'UPDATETIME'"`                  // 更新时间
}

// TableName is GOODSSORTBYPREPOSITION
func (Goodssortbypreposition) TableName() string {
	return "GOODSSORTBYPREPOSITION"
}

// GetErmcpGoodses 企业风管专用获取商品信息的方法
func GetErmcpGoodses(lastUpdateTime string) ([]Goods, error) {
	engine := db.GetEngine()

	goodses := make([]Goods, 0)
	session := engine.Table("GOODS").Where("GOODSSTATUS in (3, 7)")
	// if lastID != 0 {
	// 	session = session.And("GOODSID > ?", lastID)
	// }
	// session = session.Asc("GOODSID")
	if len(lastUpdateTime) != 0 {
		session = session.And(fmt.Sprintf("MODIFYTIME > to_date('%s','yyyy-MM-dd hh24:mi:ss')", lastUpdateTime))
	}
	if err := session.Find(&goodses); err != nil {
		return nil, err
	}

	return goodses, nil
}

// GetGoodsLastUpdateTime 获取商品表最后更新(Update)时间
func GetGoodsLastUpdateTime() (*time.Time, error) {
	engine := db.GetEngine()

	var lastUpdateTimes time.Time
	sql := `SELECT VERSIONS_STARTTIME LASTUPDATETIME
			FROM GOODS VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE WHERE
			VERSIONS_STARTTIME IS NOT NULL and VERSIONS_OPERATION = 'U' order by LASTUPDATETIME desc`
	has, err := engine.SQL(sql).Get(&lastUpdateTimes)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}

	return &lastUpdateTimes, nil
}

// GetGoodsSortByPrePositions 获取查询主力+次主力商品
func GetGoodsSortByPrePositions(sortIndex string) ([]Goodssortbypreposition, error) {
	rst := make([]Goodssortbypreposition, 0)
	session := db.GetEngine().Table("GOODSSORTBYPREPOSITION T")
	if len(sortIndex) > 0 {
		session = session.Where(fmt.Sprintf("T.SORTINDEX in (%s)", sortIndex))
	}
	session = session.Asc("T.SORTINDEX")
	if err := session.Find(&rst); err != nil {
		return nil, err
	}

	return rst, nil
}
