package trade_analysis

import (
	"hongze/hongze_yb/global"
	"time"
)

// 上期能源持仓榜单表
type TradePositionTop struct {
	Id            uint64    `gorm:"primaryKey;column:id" json:"id"`
	ClassifyName  string    `gorm:"column:classify_name" json:"classify_name"`     //分类名称
	ClassifyType  string    `gorm:"column:classify_type" json:"classify_type"`     //分类名称下的类型
	DealShortName string    `gorm:"column:deal_short_name" json:"deal_short_name"` //成交量公司简称
	DealValue     int       `gorm:"column:deal_value" json:"deal_value"`           //成交量
	DealChange    int       `gorm:"column:deal_change" json:"deal_change"`         //成交变化量
	DataTime      time.Time `gorm:"column:data_time" json:"data_time"`             //数据日期
	CreateTime    time.Time `gorm:"column:create_time" json:"create_time"`         //插入时间
	ModifyTime    time.Time `gorm:"column:modify_time" json:"modify_time"`         //修改时间
	DealType      int       `gorm:"column:deal_type" json:"deal_type"`             //交易类型：1多单，2空单，3净多单，4净空单
	SourceType    int       `gorm:"column:source_type" json:"source_type"`         //数据来源，0是原始数据的值，1是由T+1日推算出的值，2是由T日的榜单数据推算出的值
	Rank          int       `gorm:"column:rank" json:"rank"`                       //排名
}

type TradeClassifyNameList struct {
	Exchange string                      `description:"交易所" json:"exchange"`
	Sort     int                         `description:"排序字段" json:"sort"`
	Num      int                         `description:"品种数量" json:"num"`
	DataTime string                      `description:"最新更新时间" json:"data_time"`
	CurrDate string                      `description:"当前日期" json:"curr_date"`
	Items    []TradeClassifyNameListItem `description:"子类" json:"items"`
}
type TradeClassifyNameListSort []TradeClassifyNameList

func (v TradeClassifyNameListSort) Len() int {
	return len(v)
}

func (v TradeClassifyNameListSort) Swap(i, j int) {
	v[i], v[j] = v[j], v[i]
}

func (v TradeClassifyNameListSort) Less(i, j int) bool {
	return v[i].Sort < v[j].Sort
}

type TradeClassifyNameListItemSort []TradeClassifyNameListItem

func (v TradeClassifyNameListItemSort) Len() int {
	return len(v)
}

func (v TradeClassifyNameListItemSort) Swap(i, j int) {
	v[i], v[j] = v[j], v[i]
}

func (v TradeClassifyNameListItemSort) Less(i, j int) bool {
	return v[i].ClassifyName < v[j].ClassifyName
}

type TradeClassifyNameListItem struct {
	ClassifyName string                          `description:"交易分类" json:"classify_name"`
	Items        []TradeClassifyNameListItemItem `description:"合约代码" json:"items"`
}

type TradeClassifyNameListItemItemSort []TradeClassifyNameListItemItem

func (v TradeClassifyNameListItemItemSort) Len() int {
	return len(v)
}

func (v TradeClassifyNameListItemItemSort) Swap(i, j int) {
	v[i], v[j] = v[j], v[i]
}

func (v TradeClassifyNameListItemItemSort) Less(i, j int) bool {
	return v[i].ClassifyType < v[j].ClassifyType
}

type TradeClassifyNameListItemItem struct {
	ClassifyType string `json:"classify_type"` //分类名称下的类型
}

type TradeClassifyName struct {
	ClassifyName string //分类名称
	ClassifyType string //分类名称下的类型
	LatestDate   string //分类下最晚日期
}

func GetExchangeClassify(exchange string) (list []TradeClassifyName, err error) {
	tableName := "base_from_trade_" + exchange + "_index"
	orderStr := "classify_name DESC, classify_type asc"
	if exchange == "zhengzhou" {
		orderStr = "classify_name asc"
	}
	err = global.MYSQL["data"].
		Table(tableName).
		Select("classify_name, classify_type").
		Group("classify_name, classify_type").
		Where("rank <=20 and rank > 0 ").
		Order(orderStr).Scan(&list).Error
	return
}

type LastTimeItem struct {
	CreateTime time.Time
}

func GetExchangeLastTime(exchange string) (item LastTimeItem, err error) {
	tableName := "base_from_trade_" + exchange + "_index"
	err = global.MYSQL["data"].
		Table(tableName).
		Select("create_time").
		Order("create_time desc").First(&item).Error
	return
}

type GetPositionTopReq struct {
	Exchange     string `json:"exchange" form:"exchange"`           //交易所
	ClassifyName string `json:"classify_name" form:"classify_name"` //分类名称
	ClassifyType string `json:"classify_type" form:"classify_type"` //具体合约名称
	DataTime     string `json:"data_time" form:"data_time"`         //请求日期，如果为空，则返回最新的榜单日期
}

type GetPositionTopResp struct {
	BuyList       GetPositionTopList `json:"buy_list"`        //多单列表
	SoldList      GetPositionTopList `json:"sold_list"`       //空单列表
	CleanBuyList  GetPositionTopList `json:"clean_buy_list"`  //净多单列表
	CleanSoldList GetPositionTopList `json:"clean_sold_list"` //净空单列表
	DataTime      string             `json:"data_time"`       //最新日期或者请求日期
	LastDataTime  string             `json:"last_data_time" description:"最新日期"`
}

type GetPositionTopList struct {
	TotalDealValue  int                      `json:"total_deal_value"`  //总计成交量
	TotalDealChange int                      `json:"total_deal_change"` //校昨日变化
	List            []GetPositionTopListItem `json:"list"`              //榜单详情列表
}

type GetPositionTopListItem struct {
	DealShortName   string `json:"deal_short_name"`   //成交量公司简称
	DealValue       int    `json:"deal_value"`        //成交量
	DealChange      int    `json:"deal_change"`       //成交变化量
	Rank            int    `json:"rank"`              //当前名次
	Rate            string `json:"rate"`              //当前占比
	BeforeAllRate   string `json:"before_all_rate"`   //排在前面的成交量总计占比（包含）
	BeforeAllValue  int    `json:"before_all_value"`  //排在前面的成交量总计
	BeforeAllChange int    `json:"before_all_change"` //排在前面的成交量增减总计
}

func GetTradePositionTop(exchange string, classifyName, classifyType, dataTime string) (list []TradePositionTop, err error) {
	tableName := "trade_position_" + exchange + "_top"
	err = global.MYSQL["data"].
		Table(tableName).
		Where("classify_name=? and classify_type=? and data_time=? and rank <=20 and rank > 0", classifyName, classifyType, dataTime).
		Order("deal_value desc").Scan(&list).Error
	return
}

// BaseFromTradeClassify 交易所分类表
type BaseFromTradeClassify struct {
	Id           uint64    `orm:"column(id);pk"`
	ClassifyName string    //分类名称
	ClassifyType string    //分类名称下的类型
	Exchange     string    //交易所
	LatestDate   time.Time //数据最近的日期
	CreateTime   time.Time //插入时间
	ModifyTime   time.Time //修改时间
}

// GetAllBaseFromTradeClassify 获取所有的交易所分类列表
func GetAllBaseFromTradeClassify() (list []*BaseFromTradeClassify, err error) {
	err = global.MYSQL["data"].Table("base_from_trade_classify").Find(&list).Error

	return
}

func GetTradeTopLastDataTime(exchange string, classifyName, classifyType string) (item *BaseFromTradeClassify, err error) {
	tableName := "base_from_trade_classify"
	if exchange == "zhengzhou" {
		err = global.MYSQL["data"].
			Table(tableName).
			Where("exchange = ? AND classify_name=? ", exchange, classifyType).
			Order("latest_date desc").First(&item).Error
	} else {
		err = global.MYSQL["data"].
			Table(tableName).
			Where("exchange = ? AND classify_name=? and classify_type=?", exchange, classifyName, classifyType).
			Order("latest_date desc").First(&item).Error
	}

	return
}

func GetZhengzhouClassifyTypeByClassifyName(classifyName string) (item *TradeClassifyName, err error) {
	tableName := "base_from_trade_zhengzhou_index"
	err = global.MYSQL["data"].
		Table(tableName).
		Select("classify_name, classify_type").
		Where("classify_name=?", classifyName).Limit(1).Find(&item).Error
	return
}
