package future_good

import (
	"fmt"
	"hongze/hongze_yb/models/tables/future_good_edb_info"
	"hongze/hongze_yb/services/alarm_msg"
	"hongze/hongze_yb/utils"
	"time"
)

// FutureGoodEdbInfoRefreshAllFromBase 批量刷新商品期货指标
// @author Roc
// @datetime 2022-09-16 11:04:44
// @description 将原有的单个指标刷新，调整为批量多个指标刷新
func FutureGoodEdbInfoRefreshAllFromBase(futureGoodEdbInfoList []*future_good_edb_info.FutureGoodEdbInfo, refreshAll bool) (err error) {
	var errMsg string
	defer func() {
		if err != nil {
			fmt.Println("FutureGoodEdbInfoRefreshAllFromBase Err:" + err.Error() + ";errMsg:" + errMsg)
			go alarm_msg.SendAlarmMsg("FutureGoodEdbInfoRefreshAllFromBase,Err"+err.Error()+";errMsg:"+errMsg, 3)
		}
	}()
	var startDate string
	for _, bv := range futureGoodEdbInfoList {
		if bv.StartDate.IsZero() {
			continue
		}
		//开始时间
		startDate = ``
		if refreshAll { //刷新所有数据，用开始时间作为起始日期去刷新
			startDate = bv.StartDate.Format(utils.FormatDate)
		} else {
			limitDay := utils.DATA_REFRESH
			startDate = bv.StartDate.AddDate(0, 0, -limitDay).Format(utils.FormatDate)
		}
		result, err := RefreshEdbData(int(bv.FutureGoodEdbInfoID), bv.FutureGoodEdbCode, startDate)
		if err != nil {
			fmt.Println(bv.FutureGoodEdbInfoID, "FutureGoodRefreshBaseEdbData err", time.Now())
			errMsg = "FutureGoodRefreshBaseEdbData Err:" + err.Error()
			return err
		}
		if result.Ret != 200 {
			fmt.Println(bv.FutureGoodEdbInfoID, "FutureGoodRefreshBaseEdbData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
			errMsg = fmt.Sprint(bv.FutureGoodEdbInfoID, "FutureGoodRefreshBaseEdbData err;msg:", result.Msg, ";errMsg:", result.ErrMsg)
			return fmt.Errorf("刷新失败, err:%s", errMsg)
		}
	}

	// 刷新商品期货指标相关的数据
	for _, bv := range futureGoodEdbInfoList {
		if bv.ParentID == 0 {
			RefreshEdbRelation(int(bv.FutureGoodEdbInfoID))
		}
	}
	return err
}
