package services

import (
	"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"
)

// HandleFenweiIndex 处理汾渭数据的excel数据
func HandleFenweiIndex(req *models.HandleFenweiExcelDataReq) (err error) {
	errMsgList := make([]string, 0)
	defer func() {
		if len(errMsgList) > 0 {
			msg := fmt.Sprint("数据源-汾渭数据数据处理失败, err:", strings.Join(errMsgList, "\n"))
			utils.FileLog.Info(msg)
			go alarm_msg.SendAlarmMsg(msg, 3)
		}
	}()
	for _, v := range req.List {
		if v.IndexName == "" || v.IndexCode == "" {
			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常，指标编码%s或者指标ID%s为空：", v.IndexCode, v.IndexName))
			continue
		}
		err = handleFenweiIndex(v, req.TerminalCode)
		if err != nil {
			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常，指标编码：%s, Err: %s", v.IndexCode, err))
			return
		}
	}
	return
}

func handleFenweiIndex(req *models.HandleFenweiExcelData, terminalCode string) (err error) {
	indexName := req.IndexName
	indexCode := req.IndexCode
	excelDataMap := req.ExcelDataMap
	errMsgList := make([]string, 0)
	defer func() {
		if len(errMsgList) > 0 {
			msg := fmt.Sprint("数据源-汾渭数据数据处理失败,err:", strings.Join(errMsgList, "\n"))
			utils.FileLog.Info(msg)
			go alarm_msg.SendAlarmMsg(msg, 3)
		}
	}()
	indexObj := new(models.BaseFromFenweiIndex)
	dataObj := new(models.BaseFromFenweiData)
	//classifyObj := new(models.BaseFromFenweiClassify)

	var indexId int64

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

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

	// 修改指标信息
	if indexName == "" {
		utils.FileLog.Info("未刷新到指标数据:indexName:" + indexName)
		return
	}

	// 判断目录是否存在
	//var classifyId int64
	//now := time.Now()
	//if req.ClassifyName != "" {
	//	classifyObj, err = classifyObj.GetByClassifyName(req.ClassifyName)
	//	if err != nil {
	//		if err.Error() == utils.ErrNoRow() {
	//			//新增分类
	//			classifyObj = &models.BaseFromFenweiClassify{
	//				ClassifyName:    req.ClassifyName,
	//				ParentId:        0,
	//				SysUserId:       0,
	//				SysUserRealName: "",
	//				Level:           1,
	//				Sort:            req.ClassifySort,
	//				ModifyTime:      now,
	//				CreateTime:      now,
	//			}
	//
	//			classifyId, err = classifyObj.Add()
	//			if err != nil {
	//				err = fmt.Errorf("新增分类失败 Err：%s", err)
	//				return
	//			}
	//			classifyObj.ClassifyId = classifyId
	//		} else {
	//			return
	//		}
	//	} else {
	//		classifyId = classifyObj.ClassifyId
	//	}
	//}

	//判断指标是否存在
	var isAdd int
	item, err := indexObj.GetByIndexCode(indexCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			isAdd = 1
			err = nil
		} else {
			isAdd = -1
			err = fmt.Errorf("查询数据源指标库失败 GetByIndexCode Err：%s", err)
			return
		}
	}
	if item != nil && item.FenweiIndexId > 0 {
		fmt.Println("item:", item)
		isAdd = 2
	} else {
		isAdd = 1
	}

	if isAdd == 1 {
		indexObj.IndexCode = indexCode
		indexObj.IndexName = indexName
		indexObj.Frequency = req.Frequency
		indexObj.ClassifyId = req.ClassifyId
		indexObj.Unit = req.Unit
		indexObj.Sort = req.Sort
		indexObj.ModifyTime = time.Now()
		indexObj.CreateTime = time.Now()
		indexObj.TerminalCode = terminalCode
		indexId, err = indexObj.Add()
		if err != nil {
			err = fmt.Errorf("数据源新增涌溢指标失败 Err：%s", err)
			return
		}
		indexObj.FenweiIndexId = indexId
	} else if isAdd == 2 {
		if item.TerminalCode == `` && terminalCode != `` {
			item.TerminalCode = terminalCode
			err = item.Update([]string{"TerminalCode"})
			if err != nil {
				err = fmt.Errorf("数据源更新涌溢指标失败 Err：%s", err)
				return
			}
		}

		//获取已存在的所有数据
		var exitDataList []*models.BaseFromFenweiData
		exitDataList, err = dataObj.GetByIndexCode(indexCode)
		if err != nil {
			err = fmt.Errorf("数据源查询涌溢指标数据失败 Err：%s", err)
			return
		}
		fmt.Println("exitDataListLen:", len(exitDataList))
		for _, v := range exitDataList {
			dateStr := v.DataTime
			exitDataMap[dateStr] = v
		}
		indexId = item.FenweiIndexId
	}

	// 遍历excel数据，然后跟现有的数据做校验，不存在则入库
	for date, value := range excelDataMap {
		if findData, ok := exitDataMap[date]; !ok {
			_, err = time.ParseInLocation(utils.FormatDate, date, time.Local)
			if err != nil {
				err = fmt.Errorf("%s 转换日期格式失败 Err：%s", date, err)
				return
			}
			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 {
					err = fmt.Errorf("%s 转换日期格式失败 Err：%s", date, err)
					continue
				}
				timestamp := saveDataTime.UnixNano() / 1e6

				dataItem := new(models.BaseFromFenweiData)
				dataItem.FenweiIndexId = int(indexId)
				dataItem.IndexCode = indexCode
				dataItem.DataTime = date
				dataItem.Value = value
				dataItem.CreateTime = time.Now()
				dataItem.ModifyTime = time.Now()
				dataItem.DataTimestamp = timestamp
				addDataList = append(addDataList, dataItem)
			}
		} else {
			if findData != nil && findData.Value != value && !strings.Contains(value, "#N/A") { //修改数据
				findData.Value = value
				findData.ModifyTime = time.Now().Local()
				updateDataList = append(updateDataList, findData)
			}
		}
	}

	if len(addDataList) > 0 {
		err = dataObj.AddMulti(addDataList)
		if err != nil {
			err = fmt.Errorf("批量新增指标失败 Err：%s", err)
			return
		}

		var dateItem *models.EdbInfoMaxAndMinInfo
		dateItem, err = dataObj.GetMaxAndMinDateByIndexCode(indexCode)
		if err != nil {
			err = fmt.Errorf("查询指标最新日期失败 Err：%s", err)
			return
		}

		go func() {
			indexObj.ModifyIndexMaxAndMinDate(indexCode, dateItem)
		}()
	}

	// 批量更新数据
	if len(updateDataList) > 0 {
		e := models.MultiUpdateBaseFromFenweiDataValue(updateDataList)
		if e != nil {
			err = fmt.Errorf("MultiUpdateBaseFromSmmDataValue err: %s", e.Error())
			return
		}
	}

	// 同步刷新ETA指标库的指标
	{
		// 获取指标详情
		baseObj := new(models.BaseFromFenwei)
		var edbInfo *models.EdbInfo
		edbInfo, err = models.GetEdbInfoByEdbCode(baseObj.GetSource(), indexCode)
		if err != nil {
			if err.Error() != utils.ErrNoRow() {
				errMsgList = append(errMsgList, fmt.Sprint("刷新ETA指标异常，指标编码：", indexCode, err.Error()))
				return
			} else {
				err = nil
			}
		}

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