package models

import (
	"errors"
	"eta/eta_index_lib/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/shopspring/decimal"
	"strconv"
	"strings"
	"time"
)

// SavePredictCalculateNszydpjjs 新增/编辑 预测 N数值移动平均计算指标
func SavePredictCalculateNszydpjjs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("SavePredictCalculateNszydpjjs,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	var formulaInt int
	formulaInt, _ = strconv.Atoi(formula)
	if formulaInt <= 0 {
		err = errors.New("N值输入错误,请重新输入")
		return
	}

	if reqEdbInfoId <= 0 {
		edbInfo = &EdbInfo{
			//EdbInfoId:        0,
			EdbInfoType:   1,
			SourceName:    "预测N数值移动平均计算",
			Source:        utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS,
			EdbCode:       edbCode,
			EdbName:       edbName,
			EdbNameSource: edbName,
			Frequency:     frequency,
			Unit:          unit,
			//StartDate:        "",
			//EndDate:          "",
			ClassifyId:       classifyId,
			SysUserId:        sysUserId,
			SysUserRealName:  sysUserRealName,
			UniqueCode:       uniqueCode,
			CreateTime:       time.Now(),
			ModifyTime:       time.Now(),
			MinValue:         0,
			MaxValue:         0,
			CalculateFormula: formula,
			EdbType:          2,
			Sort:             0,
			MoveType:         0,
			MoveFrequency:    "",
			NoUpdate:         0,
			ServerUrl:        "",
			EdbNameEn:        edbName,
			UnitEn:           unit,
			LatestDate:       "",
			LatestValue:      0,
			ChartImage:       "",
		}
		newEdbInfoId, tmpErr := to.Insert(edbInfo)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		edbInfo.EdbInfoId = int(newEdbInfoId)

		// 添加关联关系
		{
			calculateMappingItem := &EdbInfoCalculateMapping{
				EdbInfoCalculateMappingId: 0,
				EdbInfoId:                 edbInfo.EdbInfoId,
				Source:                    edbInfo.Source,
				SourceName:                edbInfo.SourceName,
				EdbCode:                   edbCode,
				FromEdbInfoId:             fromEdbInfo.EdbInfoId,
				FromEdbCode:               fromEdbInfo.EdbCode,
				FromEdbName:               fromEdbInfo.EdbName,
				FromSource:                fromEdbInfo.Source,
				FromSourceName:            fromEdbInfo.SourceName,
				FromTag:                   "",
				Sort:                      1,
				CreateTime:                time.Now(),
				ModifyTime:                time.Now(),
			}
			_, err = to.Insert(calculateMappingItem)
			if err != nil {
				return
			}
		}

	} else {
		edbInfo, err = GetEdbInfoById(reqEdbInfoId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = `获取指标信息失败`
			}
			return
		}
		if edbInfo.EdbInfoType != 1 {
			errMsg = `该指标不是预测指标`
			err = errors.New(errMsg)
			return
		}
		latestDateStr = edbInfo.LatestDate
		latestValue = edbInfo.LatestValue
		oldCalculateFormula := edbInfo.CalculateFormula //原先的n值

		switch lang {
		case utils.EnLangVersion:
			edbInfo.EdbNameEn = edbName
			edbInfo.UnitEn = unit
		default:
			edbInfo.EdbName = edbName
			edbInfo.Unit = unit
			edbInfo.EdbNameSource = edbName
		}

		edbInfo.Frequency = frequency
		edbInfo.ClassifyId = classifyId
		edbInfo.CalculateFormula = formula
		edbInfo.ModifyTime = time.Now()
		_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
		if err != nil {
			return
		}

		//判断计算指标是否被更换
		var existCondition string
		var existPars []interface{}
		existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
		existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)

		latestDateStr = edbInfo.LatestDate
		latestValue = edbInfo.LatestValue

		count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
		if tmpErr != nil {
			err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
			return
		}
		if count > 0 && oldCalculateFormula == formula { // 指标未被替换，同时N值未修改，无需重新计算
			return
		}
		if count <= 0 {
			// 需要删除原先的 计算指标关联的，基础指标的关联关系
			sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
			if err != nil {
				return
			}

			// 添加新的关联关系
			{
				calculateMappingItem := &EdbInfoCalculateMapping{
					EdbInfoCalculateMappingId: 0,
					EdbInfoId:                 edbInfo.EdbInfoId,
					Source:                    edbInfo.Source,
					SourceName:                edbInfo.SourceName,
					EdbCode:                   edbInfo.EdbCode,
					FromEdbInfoId:             fromEdbInfo.EdbInfoId,
					FromEdbCode:               fromEdbInfo.EdbCode,
					FromEdbName:               fromEdbInfo.EdbName,
					FromSource:                fromEdbInfo.Source,
					FromSourceName:            fromEdbInfo.SourceName,
					FromTag:                   "",
					Sort:                      1,
					CreateTime:                time.Now(),
					ModifyTime:                time.Now(),
				}
				_, err = to.Insert(calculateMappingItem)
				if err != nil {
					return
				}
			}
		}

		// 删除该指标所有的同比数据
		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS, utils.DATA_SUB_SOURCE_EDB)
		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
		_, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
		if err != nil {
			return
		}
	}

	latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")

	return
}

// RefreshAllPredictCalculateNszydpjjs 刷新所有 N数值移动平均计算指标 数据
func RefreshAllPredictCalculateNszydpjjs(edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("RefreshAllPredictCalculateNszydpjjs,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfoId, source, subSource, formulaInt, fromEdbInfo, edbCode, startDate)

	return
}

// refreshAllPredictCalculateNszydpjjs 更新全部N数值移动平均计算
func refreshAllPredictCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
	edbInfoIdStr := strconv.Itoa(edbInfoId)
	fmt.Println(edbInfoIdStr)
	fmt.Println("refreshAllCalculateNszydpjjs startDate:", startDate)

	// 获取关联指标数据
	existDataList := make([]*EdbData, 0)
	dataTableName := GetEdbDataTableName(source, subSource)
	fmt.Println("dataTableName:", dataTableName)

	sql := `SELECT * FROM %s WHERE edb_info_id=? `
	sql = fmt.Sprintf(sql, dataTableName)
	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)

	existDataMap := make(map[string]*EdbData)
	removeDataTimeMap := make(map[string]int) //需要移除的日期数据
	for _, v := range existDataList {
		existDataMap[v.DataTime] = v
		removeDataTimeMap[v.DataTime] = 1
	}

	//计算来源数据
	var fromCondition string
	var fromPars []interface{}
	fromCondition += " AND edb_info_id=? "
	fromPars = append(fromPars, fromEdbInfo.EdbInfoId)
	if startDate != `` {
		fromCondition += " AND data_time>=? "
		fromPars = append(fromPars, startDate)
	}

	//fmt.Println("fromPars:", fromPars)
	fromDataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
	if err != nil {
		return
	}
	latestDateStr = fromEdbInfo.LatestDate

	var fromDateArr []string
	fromDataMap := make(map[string]*EdbInfoSearchData)
	for _, v := range fromDataList {
		fromDateArr = append(fromDateArr, v.DataTime)
		fromDataMap[v.DataTime] = v
	}

	addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	var isAdd bool
	arrLen := len(fromDateArr)
	existAddDataMap := make(map[string]string)
	for ak, av := range fromDateArr {
		//处理第一个值
		var valArr []float64
		if findItem, ok := fromDataMap[av]; ok {
			valArr = append(valArr, findItem.Value)
		} else {
			continue
		}
		if ak+1 != arrLen {
			//处理除第一个值之外的N-1个值
			for i := 1; i < formulaInt; i++ {
				arrIndex := ak + i
				if arrIndex >= arrLen {
					break
				}
				arrVal := fromDateArr[arrIndex]
				if findItem, ok := fromDataMap[arrVal]; ok {
					valArr = append(valArr, findItem.Value)
				} else {
					continue
				}
			}
		}
		valArrLen := len(valArr)
		//var totalVal float64
		totalVal := decimal.NewFromFloat(0.00)
		for _, v := range valArr {
			newDecimal := decimal.NewFromFloat(v)
			totalVal = totalVal.Add(newDecimal)
		}
		af := totalVal //decimal.NewFromFloat(totalVal)
		bf := decimal.NewFromFloat(float64(valArrLen))
		val, _ := af.Div(bf).Float64()
		valStr := decimal.NewFromFloat(val).RoundCeil(4).String()

		// 实际数据的值
		if fromEdbInfo.LatestDate == av {
			latestValue = val
		}

		if existVal, existOk := existDataMap[av]; !existOk {
			currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			timestamp := currentDate.UnixNano() / 1e6
			timestampStr := fmt.Sprintf("%d", timestamp)
			if _, existOk := existAddDataMap[av]; !existOk {
				addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
				isAdd = true
			}
			existAddDataMap[av] = av
		} else {
			//校验待删除日期数据里面是否存在该元素，如果存在的话，那么移除该日期
			delete(removeDataTimeMap, av)

			existValDecimal, _ := decimal.NewFromString(existVal.Value)
			existStr := existValDecimal.String()
			fmt.Println(existStr, valStr, av)
			if existStr != valStr {
				sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
				sql = fmt.Sprintf(sql, dataTableName)
				_, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
				if err != nil {
					return
				}
			}
		}
	}

	//删除已经不存在的指标数据（由于该指标当日的数据删除了）
	{
		removeDateList := make([]string, 0)
		for dateTime := range removeDataTimeMap {
			removeDateList = append(removeDateList, dateTime)
		}
		removeNum := len(removeDateList)
		if removeNum > 0 {
			sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
			_, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
			if err != nil {
				fmt.Println("refreshAllPredictCalculateNszydpjjs add data ;delete Err", err.Error())
				err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
				return
			}
		}
	}

	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		//utils.FileLog.Info("addSql:" + addSql)
		_, err = to.Raw(addSql).Exec()
		if err != nil {
			return
		}
	}
	return
}
