package data_manage

import (
	"eta/eta_api/utils"
	"github.com/beego/beego/v2/client/orm"
	"time"
	"unsafe"
)

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

type TradePositionDalianTop struct {
	TradePositionTop
}

type TradePositionZhengzhouTop struct {
	TradePositionTop
}

type TradePositionCffexTop struct {
	TradePositionTop
}

type TradePositionShanghaiTop struct {
	TradePositionTop
}

type TradePositionIneTop struct {
	TradePositionTop
}

func InsertMultiTradePositionTop(exchange string, items []*TradePositionTop) (err error) {
	o := orm.NewOrmUsingDB("data")
	if exchange == "dalian" {
		list := make([]*TradePositionDalianTop, 0)
		for _, v := range items {
			tmp := (*TradePositionDalianTop)(unsafe.Pointer(v))
			list = append(list, tmp)
		}
		_, err = o.InsertMulti(len(list), list)
		return
	} else if exchange == "zhengzhou" {
		list := make([]*TradePositionZhengzhouTop, 0)
		for _, v := range items {
			tmp := (*TradePositionZhengzhouTop)(unsafe.Pointer(v))
			list = append(list, tmp)
		}
		_, err = o.InsertMulti(len(list), list)
		return
	} else if exchange == "cffex" {
		list := make([]*TradePositionCffexTop, 0)
		for _, v := range items {
			tmp := (*TradePositionCffexTop)(unsafe.Pointer(v))
			list = append(list, tmp)
		}
		_, err = o.InsertMulti(len(list), list)
		return
	} else if exchange == "shanghai" {
		list := make([]*TradePositionShanghaiTop, 0)
		for _, v := range items {
			tmp := (*TradePositionShanghaiTop)(unsafe.Pointer(v))
			list = append(list, tmp)
		}
		_, err = o.InsertMulti(len(list), list)
		return
	} else if exchange == "ine" {
		list := make([]*TradePositionIneTop, 0)
		for _, v := range items {
			tmp := (*TradePositionIneTop)(unsafe.Pointer(v))
			list = append(list, tmp)
		}
		_, err = o.InsertMulti(len(list), list)
		return
	}

	return
}

func GetTradePositionTopByExchangeDataTime(exchange string, startDate, endDate string) (list []*TradePositionTop, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := "SELECT * FROM trade_position_" + exchange + "_top where data_time >= ? and data_time <= ? and deal_type in (1,2) ORDER BY classify_name, classify_type, deal_type, data_time, deal_value desc"
	_, err = o.Raw(sql, startDate, endDate).QueryRows(&list)
	return
}

func GetTradePositionTopCountByExchangeDataTime(exchange string, startDate, endDate string) (count int64, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := "SELECT count(*) FROM trade_position_" + exchange + "_top where data_time >= ? and data_time <= ? and deal_type in (1,2) ORDER BY classify_name, classify_type, deal_type, data_time, deal_value desc"
	err = o.Raw(sql, startDate, endDate).QueryRow(&count)
	return
}

func GetTradePositionTopByExchangeSourceType(exchange string, dataTime string, sourceType int) (list []*TradePositionTop, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := "SELECT * FROM trade_position_" + exchange + "_top where data_time= ? and source_type = ? ORDER BY classify_name, classify_type, deal_type, deal_value desc"
	_, err = o.Raw(sql, dataTime, sourceType).QueryRows(&list)
	return
}

type TradeTopClassify struct {
	ClassifyName string //分类名称
	ClassifyType string //分类名称下的类型
}

type TradePositionSub struct {
	ClassifyName  string //分类名称
	ClassifyType  string //分类名称下的类型
	DataTime      string //数据日期
	DealShortName string //成交量公司简称
	SubValue      int    //差值
	DealType      int
}

type TradePositionSubList []*TradePositionSub

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

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

func (v TradePositionSubList) Less(i, j int) bool {
	return v[i].SubValue > v[j].SubValue
}

type UpdateDealValueChange struct {
	Id         uint64
	DealValue  int //成交量
	DealChange int
	SourceType int
	ModifyTime time.Time //修改时间
}

func MultiUpdatePositionTop(exchange string, updates []UpdateDealValueChange) (err error) {
	o := orm.NewOrmUsingDB("data")
	p, err := o.Raw("UPDATE trade_position_" + exchange + "_top SET deal_value=?, deal_change=?, source_type=?, modify_time=? WHERE id = ?").Prepare()
	if err != nil {
		return
	}
	defer func() {
		_ = p.Close() // 别忘记关闭 statement
	}()
	for _, v := range updates {
		_, err = p.Exec(v.DealValue, v.DealChange, v.SourceType, v.ModifyTime, v.Id)
		if err != nil {
			return
		}
	}
	return
}

func DeletePositionTopByDataTime(exchange string, dataTime string, dealType int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := "delete from trade_position_" + exchange + "_Top WHERE data_time=? and deal_type=?"
	_, err = o.Raw(sql, dataTime, dealType).Exec()
	return
}

func GetTradePositionTopByExchangeDataTimeType(exchange string, dataTime string, dealType int) (list []TradePositionTop, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := "select * from trade_position_" + exchange + "_Top WHERE data_time=? and deal_type=?"
	_, err = o.Raw(sql, dataTime, dealType).QueryRows(&list)
	return
}

func MultiInsertTradeBaseDataToTop(exchange string, startDate, endDate string) (err error) {
	o := orm.NewOrmUsingDB("data")
	now := time.Now().Format(utils.FormatDateTime)
	sql1 := `INSERT INTO trade_position_` + exchange + `_top(classify_name,classify_type,deal_short_name,deal_value,deal_change,data_time,deal_type,source_type,rank,create_time,modify_time)
	SELECT classify_name,classify_type,buy_short_name,buy_value,buy_change,data_time,1,0,rank,?,? FROM base_from_trade_` + exchange + `_index where rank <50 and buy_short_name !="" and data_time between ? and ?`
	_, err = o.Raw(sql1, now, now, startDate, endDate).Exec()
	if err != nil {
		return
	}
	sql2 := `INSERT INTO trade_position_` + exchange + `_top(classify_name,classify_type,deal_short_name,deal_value,deal_change,data_time,deal_type,source_type,rank,create_time,modify_time)
SELECT classify_name,classify_type,sold_short_name,sold_value,sold_change,data_time,2,0,rank,?,? FROM base_from_trade_` + exchange + `_index where rank <50 and sold_short_name !="" and data_time between ? and ?`
	_, err = o.Raw(sql2, now, now, startDate, endDate).Exec()
	return
}
