package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/shopspring/decimal"
	"strconv"
	"strings"
)

// AddStaticPredictEdbInfoReq 添加预测指标静态指标请求
type AddStaticPredictEdbInfoReq struct {
	ClassifyId      int    `description:"分类id"`
	SourceEdbInfoId int    `description:"来源指标id"`
	EdbName         string `description:"指标名称"`
	Frequency       string `description:"频率"`
	Unit            string `description:"单位"`
	AdminId         int    `description:"添加人id"`
	AdminName       string `description:"添加人名称"`
}

// AddPredictStaticEdb 添加预测指标
// edbInfo, calculateMappingList, predictEdbConfList,calculateRule9List,trendsMappingList
func AddPredictStaticEdb(edbInfo, sourceEdbInfoItem *EdbInfo, calculateMappingList []*EdbInfoCalculateMapping, predictEdbConfList []*PredictEdbConf) (err error, errMsg string) {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			err = tx.Commit()
		}
	}()
	// 新增预测指标
	edbInfoId, err := tx.Insert(edbInfo)
	if err != nil {
		return
	}
	edbInfo.EdbInfoId = int(edbInfoId)

	// 新增预测指标的关联关系
	lenCalculateMapping := len(calculateMappingList)
	if lenCalculateMapping > 0 {
		for _, calculateMappingItem := range calculateMappingList {
			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
			calculateMappingItem.EdbCode = edbInfo.EdbCode
		}
		_, err = tx.InsertMulti(lenCalculateMapping, calculateMappingList)
		if err != nil {
			return
		}
	}
	if len(predictEdbConfList) > 0 {
		// 新增预测指标配置
		for _, v := range predictEdbConfList {
			v.PredictEdbInfoId = edbInfo.EdbInfoId
			_, tmpErr := tx.Insert(v)
			if tmpErr != nil {
				err = fmt.Errorf(`新增预测指标配置失败:%v`, tmpErr)
				return
			}
		}
	}
	// 新增预测指标数据
	dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
	edbInfoIdStr := strconv.Itoa(int(edbInfoId))
	//获取指标数据(实际已生成)
	fromDataList, err := GetEdbDataListAll(sourceEdbInfoItem.Source, sourceEdbInfoItem.SubSource, FindEdbDataListAllCond{
		EdbInfoId:         sourceEdbInfoItem.EdbInfoId,
		StartDataTime:     "",
		StartDataTimeCond: ">=",
	}, 1)
	if err != nil {
		err = fmt.Errorf(`获取原指标数据失败:%v`, err)
		return
	}

	addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	count := 0
	for _, tmpData := range fromDataList {
		currDateStr := tmpData.DataTime
		timeStr := fmt.Sprintf("%d", tmpData.DataTimestamp)
		// 当前的实际值
		saveValue := decimal.NewFromFloat(tmpData.Value).Round(4).String()
		addSql += GetAddSql(edbInfoIdStr, edbInfo.EdbCode, currDateStr, timeStr, saveValue)
		count += 1
		if count >= 500 {
			addSql = strings.TrimRight(addSql, ",")
			_, err = tx.Raw(addSql).Exec()
			if err != nil {
				err = fmt.Errorf(`新增预测指标数据失败:%v`, err)
				return
			}
			addSql = ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
			count = 0
		}
	}

	if count > 0 {
		addSql = strings.TrimRight(addSql, ",")
		_, err = tx.Raw(addSql).Exec()
		if err != nil {
			err = fmt.Errorf(`新增预测指标数据失败:%v`, err)
			return
		}
	}

	return
}