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"
	"html"
	"strings"
	"time"
)

// HandleCCFIndex 处理CCF的excel数据
func HandleCCFIndex(req *models.HandleCCFEdbDataReq) (err error) {
	errMsgList := make([]string, 0)
	defer func() {
		if len(errMsgList) > 0 {
			msg := fmt.Sprint("数据源-CCF数据处理失败, 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 = handleCCFIndex(v, req.TerminalCode)
		if err != nil {
			errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常，指标编码：%s, Err: %s", v.IndexCode, err))
			return
		}
	}
	return
}

func handleCCFIndex(req *models.HandleCCFEdbData, terminalCode string) (err error) {
	indexName := req.IndexName
	indexCode := req.IndexCode
	excelDataMap := req.DateData
	errMsgList := make([]string, 0)
	defer func() {
		if len(errMsgList) > 0 {
			msg := fmt.Sprint("数据源-CCF数据处理失败,err:", strings.Join(errMsgList, "\n"))
			utils.FileLog.Info(msg)
			go alarm_msg.SendAlarmMsg(msg, 3)
		}
	}()
	indexObj := new(models.BaseFromCCFIndex)
	dataObj := new(models.BaseFromCCFData)
	//classifyObj := new(models.BaseFromCCFClassify)

	var indexId int64

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

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

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

	//判断指标是否存在
	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.BaseFromCcfIndexId > 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
		if req.Unit == "" {
			req.Unit = "无"
		}
		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("数据源新增CCF指标失败 Err：%s", err)
			return
		}
		indexObj.BaseFromCcfIndexId = indexId
	} else if isAdd == 2 {
		if item.TerminalCode == `` && terminalCode != `` {
			item.TerminalCode = terminalCode
			err = item.Update([]string{"TerminalCode"})
			if err != nil {
				err = fmt.Errorf("数据源更新CCF指标失败 Err：%s", err)
				return
			}
		}

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

	// 遍历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.BaseFromCCFData)
				dataItem.BaseFromCcfIndexId = 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.MultiUpdateBaseFromCCFDataValue(updateDataList)
		if e != nil {
			err = fmt.Errorf("MultiUpdateBaseFromSmmDataValue err: %s", e.Error())
			return
		}
	}

	// 同步刷新ETA指标库的指标
	{
		// 获取指标详情
		baseObj := new(models.BaseFromCCF)
		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
}

// HandleCCFStockTable 处理CCF的表格数据
func HandleCCFStockTable(req *models.HandleCCFStockTableReq) (err error) {
	defer func() {
		if err != nil {
			tips := fmt.Sprintf("数据源-CCF数据装置处理失败, err: %v", err)
			utils.FileLog.Info(tips)
			go alarm_msg.SendAlarmMsg(tips, 3)
		}
	}()
	if req.Table == nil {
		err = fmt.Errorf("表格信息为空")
		return
	}

	// 已存在则更新表格
	excelOb := new(models.CCFStockExcel)
	cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, excelOb.Cols().ClassifyId, excelOb.Cols().ExcelDate)
	pars := make([]interface{}, 0)
	pars = append(pars, req.Table.ClassifyId, req.Table.TableDate.Format(utils.FormatDate))
	exists, e := excelOb.GetItemByCondition(cond, pars, "")
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = fmt.Errorf("获取已存在表格失败, err: %v", e)
		return
	}
	if exists != nil {
		exists.ExcelContent = html.EscapeString(req.Table.TableContent)
		exists.FromPage = req.Table.FromPage
		exists.ModifyTime = time.Now().Local()
		cols := []string{excelOb.Cols().ExcelContent, excelOb.Cols().FromPage, excelOb.Cols().ModifyTime}
		if e = exists.Update(cols); e != nil {
			err = fmt.Errorf("更新已存在表格失败, err: %v", e)
			return
		}
		return
	}

	// 新增表格
	excelOb.ClassifyId = req.Table.ClassifyId
	excelOb.ExcelDate = req.Table.TableDate
	excelOb.ExcelContent = html.EscapeString(req.Table.TableContent)
	excelOb.FromPage = req.Table.FromPage
	excelOb.CreateTime = time.Now().Local()
	excelOb.ModifyTime = time.Now().Local()
	if e = excelOb.Create(); e != nil {
		err = fmt.Errorf("新增表格失败, err: %v", e)
		return
	}
	return
}
