package future_good

import (
	"eta_gn/eta_api/models/data_manage/future_good"
	"eta_gn/eta_api/services/alarm_msg"
	"eta_gn/eta_api/utils"
	"fmt"
	"time"
)

// FutureGoodEdbInfoRefreshAllFromBase 批量刷新商品期货指标
// @author Roc
// @datetime 2022-09-16 11:04:44
// @description 将原有的单个指标刷新,调整为批量多个指标刷新
func FutureGoodEdbInfoRefreshAllFromBase(futureGoodEdbInfoList []*future_good.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 == "0000-00-00" {
			continue
		}
		//开始时间
		startDate = ``
		if refreshAll { //刷新所有数据,用开始时间作为起始日期去刷新
			sTime, err := time.Parse(utils.FormatDate, bv.StartDate)
			if err != nil {
				return err
			}
			startDate = sTime.Format(utils.FormatDate)
		} else {
			sTime, err := time.Parse(utils.FormatDate, bv.EndDate)
			if err != nil {
				return err
			}
			limitDay := utils.DATA_START_REFRESH_LIMIT
			startDate = sTime.AddDate(0, 0, -limitDay).Format(utils.FormatDate)
		}
		result, err := RefreshEdbData(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(bv.FutureGoodEdbInfoId)
		}
	}
	return err
}