package data

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/mgo"
	"eta/eta_api/utils"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
)

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

// BusinessIndexSource2Edb 新增彭博数据源到指标库
func BusinessIndexSource2Edb(req BusinessIndexSource2EdbReq, 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("BusinessIndexSource2Edb新增失败, Err: %s", err.Error())
			fmt.Println(tips)
			utils.FileLog.Info(tips)
		}
	}()
	source := utils.DATA_SOURCE_BUSINESS

	// 是否新增过指标
	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

	// 新增指标库
	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

	return
}

// GetPageBaseBusinessIndexData
// @Description: 获取自有数据的分页数据
// @author: Roc
// @datetime 2024-05-07 11:02:51
// @param indexCode int
// @param startSize int
// @param pageSize int
// @return dataCount int
// @return dataList []*data_manage.BaseFromBusinessIndexDataItem
// @return err error
func GetPageBaseBusinessIndexData(indexCode string, startSize, pageSize int) (dataCount int, dataList []*data_manage.BaseFromBusinessIndexDataItem, err error) {
	dataList = make([]*data_manage.BaseFromBusinessIndexDataItem, 0)

	mogDataObj := mgo.BaseFromBusinessData{}
	// 构建查询条件
	queryConditions := bson.M{
		"index_code": indexCode,
	}

	// 获取数据总量
	tmpCount, tmpErr := mogDataObj.GetCountDataList(queryConditions)
	if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
		err = tmpErr
		return
	}
	dataCount = int(tmpCount)

	// 获取列表数据
	tmpDataList, tmpErr := mogDataObj.GetPageDataList(queryConditions, int64(startSize), int64(pageSize), []string{"-data_time"})
	if tmpErr != nil {
		err = tmpErr
		return
	}
	for _, v := range tmpDataList {
		dataList = append(dataList, &data_manage.BaseFromBusinessIndexDataItem{
			ID:        v.ID.String(),
			IndexCode: v.IndexCode,
			DataTime:  v.DataTime.Format(utils.FormatDate),
			Value:     v.Value,
		})
	}

	return
}
