package models

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

const (
	FactorEdbSeriesChartCalculateTypeCorrelation = 1 // 相关性计算
	FactorEdbSeriesChartCalculateTypeRange       = 2 // 	区间计算
)

// FactorEdbSeriesChartMapping 因子指标系列-图表关联
type FactorEdbSeriesChartMapping struct {
	FactorEdbSeriesChartMappingId int       `orm:"column(factor_edb_series_chart_mapping_id);pk"`
	ChartInfoId                   int       `description:"图表ID"`
	Source                        int       `description:"图表来源, 同chart_info表source"`
	CalculateType                 int       `description:"计算方式: 1-相关性"`
	CalculatePars                 string    `description:"计算参数-JSON(如计算窗口等)"`
	CalculateData                 string    `description:"计算数据-JSON(如相关性矩阵等)"`
	FactorEdbSeriesId             int       `description:"因子指标系列ID"`
	EdbInfoId                     int       `description:"指标ID"`
	EdbUsed                       int       `description:"指标是否使用: 0-否; 1-是"`
	CreateTime                    time.Time `description:"创建时间"`
	ModifyTime                    time.Time `description:"修改时间"`
}

func (m *FactorEdbSeriesChartMapping) TableName() string {
	return "factor_edb_series_chart_mapping"
}

type MultipleFactorSeriesChartMappingCols struct {
	PrimaryId         string
	ChartInfoId       string
	Source            string
	CalculateType     string
	CalculatePars     string
	CalculateData     string
	FactorEdbSeriesId string
	EdbInfoId         string
	EdbUsed           string
	CreateTime        string
	ModifyTime        string
}

func (m *FactorEdbSeriesChartMapping) Cols() MultipleFactorSeriesChartMappingCols {
	return MultipleFactorSeriesChartMappingCols{
		PrimaryId:         "factor_edb_series_chart_mapping_id",
		ChartInfoId:       "chart_info_id",
		Source:            "source",
		CalculateType:     "calculate_type",
		CalculatePars:     "calculate_pars",
		CalculateData:     "calculate_data",
		FactorEdbSeriesId: "factor_edb_series_id",
		EdbInfoId:         "edb_info_id",
		EdbUsed:           "edb_used",
		CreateTime:        "create_time",
		ModifyTime:        "modify_time",
	}
}

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

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

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

func (m *FactorEdbSeriesChartMapping) 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.FactorEdbSeriesChartMappingId).Exec()
	return
}

func (m *FactorEdbSeriesChartMapping) 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 *FactorEdbSeriesChartMapping) GetItemById(id int) (item *FactorEdbSeriesChartMapping, 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 *FactorEdbSeriesChartMapping) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *FactorEdbSeriesChartMapping, 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 *FactorEdbSeriesChartMapping) 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 *FactorEdbSeriesChartMapping) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*FactorEdbSeriesChartMapping, 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 *FactorEdbSeriesChartMapping) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*FactorEdbSeriesChartMapping, 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
}

// GetDistinctSeriesIdByChartId 获取图表关联的系列ID
func (m *FactorEdbSeriesChartMapping) GetDistinctSeriesIdByChartId(chartId int) (seriesIds []int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT DISTINCT %s FROM %s WHERE %s = ?`, m.Cols().FactorEdbSeriesId, m.TableName(), m.Cols().ChartInfoId)
	_, err = o.Raw(sql, chartId).QueryRows(&seriesIds)
	return
}

// FactorEdbSeriesChartCalculateCorrelationReq 图表相关性计算参数
type FactorEdbSeriesChartCalculateCorrelationReq struct {
	BaseEdbInfoId  int    `description:"标的指标ID"`
	LeadValue      int    `description:"领先期数"`
	LeadUnit       string `description:"频度"`
	CalculateValue int    `description:"计算窗口"`
	CalculateUnit  string `description:"计算频度"`
}