package services

import (
	"errors"
	"eta/eta_index_lib/logic"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/services/alarm_msg"
	"eta/eta_index_lib/utils"
	"fmt"
	"strings"
	"time"
)

func SmmIndexHandle(baseFilePath, renameFilePath, indexName, indexCode, unit, frequency, source string, excelDataMap map[string]string) {
	var err error

	errMsgList := make([]string, 0)
	defer func() {
		if len(errMsgList) > 0 {
			fmt.Println(fmt.Sprint("SMM有色实际数据处理失败,err:", strings.Join(errMsgList, "\n")))
			go alarm_msg.SendAlarmMsg(fmt.Sprint("SMM有色实际数据处理失败,err:", strings.Join(errMsgList, "\n")), 3)
		}
	}()

	indexObj := new(models.BaseFromSmmIndex)
	var indexId int64

	addDataList := make([]*models.BaseFromSmmData, 0)
	updateDataList := make([]*models.BaseFromSmmData, 0)

	exitDataMap := make(map[string]*models.BaseFromSmmData)

	// 修改指标信息
	if indexName == "" {
		utils.FileLog.Info("未刷新到指标数据:indexName:" + indexName)
		return
	}
	//判断指标是否存在
	var isAdd int
	item, err := indexObj.GetSmmIndexItem(indexCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			isAdd = 1
		} else {
			isAdd = -1
			fmt.Println("GetSmmIndexItem Err:" + err.Error())
			return
		}
	}
	if item != nil && item.BaseFromSmmIndexId > 0 {
		fmt.Println("item:", item)
		isAdd = 2
	} else {
		isAdd = 1
	}

	fmt.Println("isAdd:", isAdd)
	if !strings.Contains(frequency, "度") {
		frequency = frequency + "度"
	}

	if isAdd == 1 {
		indexObj.IndexCode = indexCode
		indexObj.IndexName = indexName
		indexObj.Unit = unit
		indexObj.Frequency = frequency
		indexObj.Interface = source
		indexObj.ModifyTime = time.Now()
		indexObj.CreateTime = time.Now()
		indexObj.BaseFileName = baseFilePath
		indexObj.RenameFileName = renameFilePath
		lastId, err := indexObj.AddBaseFromSmmIndex()
		if err != nil {
			fmt.Println("add err:" + err.Error())
			return
		}
		indexId = lastId
		go models.ModifySmmIndexSort(indexId)
	} else if isAdd == 2 {
		//获取已存在的所有数据
		exitDataList, err := models.GetBaseFromSmmDataBySmmCode(indexCode)
		if err != nil {
			fmt.Println("GetIndexDataList Err:" + err.Error())
			return
		}
		fmt.Println("exitDataListLen:", len(exitDataList))
		for _, v := range exitDataList {
			//dateStr := v.DataTime.Format(utils.FormatDate)
			exitDataMap[v.DataTime] = v
		}
		indexId = item.BaseFromSmmIndexId
		//修改指标信息
		updateParams := make(map[string]interface{})
		updateParams["index_name"] = indexName
		updateParams["frequency"] = frequency
		updateParams["unit"] = unit
		updateParams["interface"] = source
		updateParams["modify_time"] = time.Now()

		whereParam := make(map[string]interface{})
		whereParam["index_code"] = indexCode

		smmIndexObj := new(models.BaseFromSmmIndex)
		err = smmIndexObj.Update(updateParams, whereParam)
		if err != nil {
			err = errors.New("smm index update err:" + err.Error())
			return
		}
	}

	// 遍历excel数据，然后跟现有的数据做校验，不存在则入库
	for date, value := range excelDataMap {
		dateTime, e := time.ParseInLocation(utils.FormatDate, date, time.Local)
		if e != nil {
			fmt.Println("time.ParseInLocation Err:" + e.Error())
			return
		}
		if _, ok := exitDataMap[date]; !ok {
			if !strings.Contains(value, "#N/A") {
				var saveDataTime time.Time
				if strings.Contains(date, "00:00:00") {
					saveDataTime, err = time.Parse(utils.FormatDateTime, date)
				} else {
					saveDataTime, err = time.Parse(utils.FormatDate, date)
				}
				if err != nil {
					errMsg := "saveDataTime parse err:" + err.Error() + " dataTime:" + date
					fmt.Println(errMsg)
					continue
				}
				timestamp := saveDataTime.UnixNano() / 1e6

				dataItem := new(models.BaseFromSmmData)
				dataItem.BaseFromSmmIndexId = int(indexId)
				dataItem.IndexCode = indexCode
				dataItem.DataTime = dateTime.Format(utils.FormatDate)
				dataItem.Value = value
				dataItem.CreateTime = time.Now()
				dataItem.ModifyTime = time.Now()
				dataItem.DataTimestamp = timestamp
				addDataList = append(addDataList, dataItem)
			}
		} else {
			// 更新对应日期数据
			if strings.Contains(value, "#N/A") {
				continue
			}

			dataItem := new(models.BaseFromSmmData)
			dataItem.IndexCode = indexCode
			dataItem.DataTime = dateTime.Format(utils.FormatDate)
			dataItem.Value = value
			dataItem.ModifyTime = time.Now()
			updateDataList = append(updateDataList, dataItem)
		}
	}

	if len(addDataList) > 0 {
		err = models.AddBaseFromSmmData(addDataList)
		if err != nil {
			fmt.Println("AddBaseFromSmmData Err:" + err.Error())
			errMsgList = append(errMsgList, "AddBaseFromSmmData err: "+err.Error())
		}
	}

	// 已存在的日期数据更新
	if len(updateDataList) > 0 {
		err = models.MultiUpdateBaseFromSmmDataValue(updateDataList)
		if err != nil {
			fmt.Println("MultiUpdateBaseFromSmmDataValue Err:" + err.Error())
			errMsgList = append(errMsgList, "MultiUpdateBaseFromSmmDataValue err: "+err.Error())
		}
	}

	itemInfo, err := models.GetSmmIndexInfoMaxAndMinInfo(indexCode)
	if err == nil && item != nil {
		e := models.ModifySmmIndexMaxAndMinInfo(indexCode, itemInfo)
		if e != nil {
			fmt.Println("ModifySmmIndexMaxAndMinInfo Err:" + e.Error())
			errMsgList = append(errMsgList, "ModifySmmIndexMaxAndMinInfo err: "+e.Error())
		}
	}

	// 同步刷新ETA图库有色的指标
	{
		// 获取指标详情
		edbInfo, err := models.GetEdbInfoByEdbCode(utils.DATA_SOURCE_YS, indexCode)
		if err != nil && err.Error() != utils.ErrNoRow() {
			errMsgList = append(errMsgList, fmt.Sprint("刷新ETA指标异常，指标编码：", indexCode, err.Error()))
		}

		// 已经加入到指标库的话，那么就去更新ETA指标库吧
		if edbInfo != nil {
			go logic.RefreshBaseEdbInfo(edbInfo, ``)
		}
	}
}
