package data

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/utils"
	"fmt"
)

type BloombergIndexSource2EdbReq struct {
	EdbCode       string
	EdbName       string
	Frequency     string
	Unit          string
	ClassifyId    int
	AdminId       int
	AdminRealName string
}

// BloombergIndexSource2Edb 新增彭博数据源到指标库
func BloombergIndexSource2Edb(req BloombergIndexSource2EdbReq, lang string) (edb *data_manage.EdbInfo, err error, errMsg string, skip bool) {
	if req.EdbCode == "" {
		err = fmt.Errorf("指标ID为空")
		return
	}
	defer func() {
		if err != nil {
			tips := fmt.Sprintf("BloombergIndexSource2Edb新增失败, Err: %s", err.Error())
			fmt.Println(tips)
			utils.FileLog.Info(tips)
		}
	}()
	source := utils.DATA_SOURCE_BLOOMBERG

	// 是否已有指标数据
	dataList, e := data_manage.GetEdbDataAllByEdbCode(req.EdbCode, source, utils.DATA_SUB_SOURCE_EDB, utils.EDB_DATA_LIMIT)
	if e != nil {
		err = fmt.Errorf("获取指标数据失败, Err: %s", e.Error())
		return
	}

	// 新增指标数据
	if len(dataList) == 0 {
		res, e := AddEdbData(source, req.EdbCode, req.Frequency)
		if e != nil {
			err = fmt.Errorf("index_lib: 新增指标数据失败, Err: %s", e.Error())
			return
		}
		if res == nil {
			err = fmt.Errorf("index_lib: 新增指标数据失败, res nil")
			return
		}
		if res.Ret != 200 {
			err = fmt.Errorf("index_lib: 新增指标数据失败, Ret: %d", res.Ret)
			return
		}
	}

	// 是否新增过指标
	exist, e := data_manage.GetEdbInfoByEdbCode(source, req.EdbCode)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = fmt.Errorf("获取指标是否存在失败, err: %s", e.Error())
		return
	}
	if exist != nil {
		skip = true
		return
	}

	// 开始结束时间
	var startDate, endDate string
	minMax, e := data_manage.GetEdbInfoMaxAndMinInfo(source, utils.DATA_SUB_SOURCE_EDB, req.EdbCode)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = fmt.Errorf("MinMax: 获取指标极值失败, err: %s", e.Error())
		return
	}
	if minMax != nil {
		startDate = minMax.MinDate
		endDate = minMax.MaxDate
	}

	// 新增指标库
	edbInfo, e, msg, _ := EdbInfoAdd(source, utils.DATA_SUB_SOURCE_EDB, req.ClassifyId, req.EdbCode, req.EdbName, req.Frequency, req.Unit, startDate, endDate, req.AdminId, req.AdminRealName, lang)
	if e != nil {
		errMsg = msg
		err = fmt.Errorf("EdbInfo: 新增指标失败, err: %s", e.Error())
		return
	}
	edb = edbInfo

	// 标记原始指标为已添加
	indexOb := new(data_manage.BaseFromBloombergIndex)
	if e = indexOb.UpdateEdbExist(req.EdbCode); e != nil {
		err = fmt.Errorf("BaseIndex: 标记已添加指标库失败, err: %s", e.Error())
		return
	}

	// 新增es
	go AddOrEditEdbInfoToEs(edbInfo.EdbInfoId)
	return
}
