package data_manage

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

// ChartInfoCorrelation 相关性图表-扩展信息
type ChartInfoCorrelation struct {
	CorrelationChartInfoId int       `orm:"column(correlation_chart_info_id);pk" description:"相关性图表ID(chart_info表source=3的)"`
	LeadValue              int       `description:"领先值"`
	LeadUnit               string    `description:"领先单位"`
	CalculateValue         int       `description:"计算窗口"`
	CalculateUnit          string    `description:"计算频度"`
	BaseCalculateValue     int       `description:"基础计算窗口（滚动相关性的时候用到）"`
	BaseCalculateUnit      string    `description:"基础计算频度（滚动相关性的时候用到）"`
	DateType               int       `description:"日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间,6:起始日期至今"`
	StartDate              time.Time `description:"开始日期"`
	EndDate                time.Time `description:"结束日期"`
	EdbInfoIdFirst         int       `description:"A指标ID"`
	EdbInfoIdSecond        int       `description:"B指标ID"`
	PeriodData             string    `description:"X轴-期数数据"`
	CorrelationData        string    `description:"Y轴-相关性系数"`
	CreateTime             time.Time `description:"创建时间"`
	ModifyTime             time.Time `description:"更新时间"`
}

type CorrelationInfo struct {
	LeadValue       int    `description:"领先值"`
	LeadUnit        string `description:"领先单位"`
	CalculateValue  int    `description:"计算窗口"`
	CalculateUnit   string `description:"计算频度"`
	StartDate       string `description:"开始日期"`
	EndDate         string `description:"结束日期"`
	EdbInfoIdFirst  int    `description:"A指标ID"`
	EdbInfoIdSecond int    `description:"B指标ID"`
	PeriodData      string `description:"X轴-期数数据"`
	CorrelationData string `description:"Y轴-相关性系数"`
}

func (m *ChartInfoCorrelation) TableName() string {
	return "chart_info_correlation"
}

func (m *ChartInfoCorrelation) Create() (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Insert(m)
	if err != nil {
		return
	}
	//m.CorrelationChartInfoId = int(id)
	return
}

func (m *ChartInfoCorrelation) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(m, cols...)
	return
}

func (m *ChartInfoCorrelation) Delete() (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE correlation_chart_info_id = ? LIMIT 1`, m.TableName())
	_, err = o.Raw(sql, m.CorrelationChartInfoId).Exec()
	return
}

func (m *ChartInfoCorrelation) GetItemById(id int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE correlation_chart_info_id = ? LIMIT 1`, m.TableName())
	err = o.Raw(sql, id).QueryRow(&m)
	return
}

func (m *ChartInfoCorrelation) GetItemByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s LIMIT 1`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&m)
	return
}

func (m *ChartInfoCorrelation) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ChartInfoCorrelation, err error) {
	o := orm.NewOrmUsingDB("data")
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := ``
	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
}

// CreateCorrelationChartAndEdb 新增相关性图表
func CreateCorrelationChartAndEdb(chartInfo *ChartInfo, edbMappingList []*ChartEdbMapping, correlationInfo *ChartInfoCorrelation) (chartInfoId int, err error) {
	o := orm.NewOrmUsingDB("data")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 新增图表信息
	newId, err := tx.Insert(chartInfo)
	if err != nil {
		return
	}
	// 指标mapping
	chartInfo.ChartInfoId = int(newId)
	chartInfoId = int(newId)
	if len(edbMappingList) > 0 {
		for i := range edbMappingList {
			edbMappingList[i].ChartInfoId = chartInfoId
		}
		_, err = tx.InsertMulti(len(edbMappingList), edbMappingList)
		if err != nil {
			return
		}
	}
	// 相关性信息
	correlationInfo.CorrelationChartInfoId = chartInfoId
	if _, err = tx.Insert(correlationInfo); err != nil {
		return
	}
	return
}
