package data_manage

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

// N数值移动平均计算
func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	if req.EdbInfoId <= 0 {
		edbInfo := new(EdbInfo)
		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
		edbInfo.SourceName = "N数值移动平均计算"
		edbInfo.EdbCode = edbCode
		edbInfo.EdbName = req.EdbName
		edbInfo.EdbNameSource = req.EdbName
		edbInfo.Frequency = req.Frequency
		edbInfo.Unit = req.Unit
		edbInfo.ClassifyId = req.ClassifyId
		edbInfo.SysUserId = sysUserId
		edbInfo.SysUserRealName = sysUserRealName
		edbInfo.CreateTime = time.Now()
		edbInfo.ModifyTime = time.Now()
		edbInfo.UniqueCode = uniqueCode
		edbInfo.CalculateFormula = req.Formula
		edbInfo.EdbType = 2
		newEdbInfoId, tmpErr := to.Insert(edbInfo)
		if tmpErr != nil {
			return edbInfoId, tmpErr
		}
		edbInfoId = int(newEdbInfoId)

		//calculateItem := new(EdbInfoCalculateNszydpjjs)
		//calculateItem.CreateTime = time.Now()
		//calculateItem.ModifyTime = time.Now()
		//calculateItem.Sort = 1
		//calculateItem.EdbCode = edbCode
		//calculateItem.EdbInfoId = edbInfoId
		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
		//calculateItem.FromEdbName = fromEdbInfo.EdbName
		//calculateItem.FromSource = fromEdbInfo.Source
		//calculateItem.FromSourceName = fromEdbInfo.SourceName
		//
		//_, err = to.Insert(calculateItem)
		//if err != nil {
		//	return edbInfoId, err
		//}

		//关联关系
		{
			calculateMappingItem := new(EdbInfoCalculateMapping)
			calculateMappingItem.CreateTime = time.Now()
			calculateMappingItem.ModifyTime = time.Now()
			calculateMappingItem.Sort = 1
			calculateMappingItem.EdbCode = edbCode
			calculateMappingItem.EdbInfoId = edbInfoId
			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
			calculateMappingItem.FromSource = fromEdbInfo.Source
			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
			calculateMappingItem.FromTag = ""
			calculateMappingItem.Source = edbInfo.Source
			calculateMappingItem.SourceName = edbInfo.SourceName
			_, err = to.Insert(calculateMappingItem)
			if err != nil {
				return
			}
		}
	} else {
		edbInfoId = req.EdbInfoId
		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NSZYDPJJS)
		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
	}

	edbInfoIdStr := strconv.Itoa(edbInfoId)
	//计算数据
	var condition string
	var pars []interface{}
	condition += " AND edb_info_id=? "
	if req.EdbInfoId <= 0 {
		pars = append(pars, req.FromEdbInfoId)
	} else {
		pars = append(pars, fromEdbInfo.EdbInfoId)
	}
	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
	if err != nil {
		return edbInfoId, err
	}
	var dateArr []string
	dataMap := make(map[string]*EdbInfoSearchData)
	for _, v := range dataList {
		dateArr = append(dateArr, v.DataTime)
		dataMap[v.DataTime] = v
	}

	addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
	var isAdd bool

	arrLen := len(dateArr)
	for ak, av := range dateArr {
		//处理第一个值
		var valArr []float64
		if findItem, ok := dataMap[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 := dateArr[arrIndex]
				if findItem, ok := dataMap[arrVal]; ok {
					valArr = append(valArr, findItem.Value)
				} else {
					continue
				}
			}
		}
		valArrLen := len(valArr)
		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()
		currentDate, err := time.Parse(utils.FormatDate, av)
		if err != nil {
			return edbInfoId, err
		}

		timestamp := currentDate.UnixNano() / 1e6
		timestampStr := fmt.Sprintf("%d", timestamp)
		valStr := utils.SubFloatToString(val, 4)
		addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
		isAdd = true
	}

	if isAdd {
		addSql = strings.TrimRight(addSql, ",")
		_, err = to.Raw(addSql).Exec()
		if err != nil {
			return edbInfoId, err
		}
	}
	return
}
