package services

import (
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/services/alarm_msg"
	"eta/eta_index_lib/utils"
	"fmt"
	"time"
)

// FactorEdbStepCalculate 因子指标-多公式计算
func FactorEdbStepCalculate(seriesId, edbInfoId int, edbCode string, edbData []*models.EdbInfoSearchData, calculates []models.CalculatesReq) (err error) {
	if len(edbData) == 0 || len(calculates) == 0 {
		return
	}
	defer func() {
		if err != nil {
			tips := fmt.Sprintf("FactorEdbStepCalculate计算失败, EdbCode: %s, ErrMsg: %v", edbCode, err)
			utils.FileLog.Info(tips)
			go alarm_msg.SendAlarmMsg(tips, 2)
		}
	}()

	// 重新计算-先清除原数据
	calculateDataOb := new(models.FactorEdbSeriesCalculateData)
	{
		cond := fmt.Sprintf("%s = ?", calculateDataOb.Cols().FactorEdbSeriesId)
		pars := make([]interface{}, 0)
		pars = append(pars, seriesId)
		if e := calculateDataOb.RemoveByCondition(cond, pars); e != nil {
			err = fmt.Errorf("清除原数据失败, err: %v", e)
			return
		}
	}

	// 多公式嵌套计算
	dataMap, dateList, _, e := StepCalculate(edbData, calculates)
	if e != nil {
		err = fmt.Errorf("嵌套计算失败, err: %v", e)
		return
	}

	// 计算成功的保存结果
	dataArr := make([]*models.FactorEdbSeriesCalculateData, 0)
	for _, d := range dateList {
		val, ok := dataMap[d]
		if !ok {
			continue
		}
		dataTime, e := time.ParseInLocation(utils.FormatDate, d, time.Local)
		if e != nil {
			err = fmt.Errorf("解析计算结果日期失败, err: %v", e)
			return
		}
		dataArr = append(dataArr, &models.FactorEdbSeriesCalculateData{
			FactorEdbSeriesId: seriesId,
			EdbInfoId:         edbInfoId,
			EdbCode:           edbCode,
			DataTime:          dataTime,
			Value:             val,
			CreateTime:        time.Now().Local(),
			ModifyTime:        time.Now().Local(),
			DataTimestamp:     dataTime.UnixNano() / 1e6,
		})
	}
	if len(dataArr) == 0 {
		//err = fmt.Errorf("计算结果无数据")
		return
	}
	if e = calculateDataOb.CreateMulti(dataArr); e != nil {
		err = fmt.Errorf("保存计算结果失败, err: %v", e)
		return
	}
	return
}
