package models

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

// SavePredictCalculateNh 预测年化值
func SavePredictCalculateNh(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("SavePredictCalculateNh,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	fmt.Println("reqEdbInfoId:", reqEdbInfoId)

	if reqEdbInfoId <= 0 {
		edbInfo = &EdbInfo{
			//EdbInfoId:        0,
			EdbInfoType:   1,
			SourceName:    utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_NH,
			Source:        utils.DATA_SOURCE_PREDICT_CALCULATE_NH,
			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
		//修改指标信息
		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)

		count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
		if tmpErr != nil {
			err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
			return
		}
		if count > 0 { // 指标未被替换，无需重新计算
			return
		}

		//删除，计算指标关联的，基础指标的关联关系
		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
		if err != nil {
			err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
			return
		}

		//清空原有已经入库的数据
		tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
		sql = ` DELETE FROM ` + tableName + ` 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:                   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
			}
		}

	}

	// 计算数据
	latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbCode)

	return
}

// RefreshAllPredictCalculateNh 刷新全部预测年化值数据
func RefreshAllPredictCalculateNh(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula 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("RefreshAllCalculateNh,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	// 计算数据
	latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfoId, source, subSource, fromEdbInfo, edbCode)
	return
}

// refreshAllPredictCalculateNh 刷新预测年化数据
func refreshAllPredictCalculateNh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode string) (latestDateStr string, latestValue float64, err error) {
	edbInfoIdStr := strconv.Itoa(edbInfoId)
	tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NH, subSource)

	//获取年化指标所有数据
	existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
	if err != nil {
		return
	}
	//计算指标的map
	existDataMap := make(map[string]*EdbData, 0)
	removeDateMap := make(map[string]string)
	for _, v := range existDataList {
		existDataMap[v.DataTime] = v
		removeDateMap[v.DataTime] = ``
	}

	//获取源指标数据
	fmt.Println("EdbInfoId:", fromEdbInfo.EdbInfoId)
	fromDataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
	if err != nil {
		return
	}
	// 插值法数据处理
	handleDataMap := make(map[string]float64)
	_, err = HandleDataByLinearRegression(fromDataList, handleDataMap)
	if err != nil {
		return
	}

	var dateArr []string
	dataMap := make(map[string]*EdbInfoSearchData)
	fromDataMap := make(map[string]float64)
	//来源指指标数据
	for _, v := range fromDataList {
		dateArr = append(dateArr, v.DataTime)
		dataMap[v.DataTime] = v
		fromDataMap[v.DataTime] = v.Value
	}
	lenFromDataList := len(fromDataList)
	// 如果来源指标没有数据,那么就直接返回得了
	if lenFromDataList <= 0 {
		sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)

		_, err = to.Raw(sql, edbInfoId).Exec()
		if err != nil {
			err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
			return
		}
		return
	}
	fmt.Println("source:", source)

	// 真实数据的最后日期
	latestDateStr = fromEdbInfo.LatestDate
	// 每年的最后一天的数据值
	yearLastValMap := make(map[int]float64)
	startDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[0].DataTime, time.Local)
	endDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[lenFromDataList-1].DataTime, time.Local)
	for i := startDataTime.Year(); i <= endDataTime.Year(); i++ {
		tmpDateStr := fmt.Sprintf("%d-12-31", i)
		if tmpVal, ok := handleDataMap[tmpDateStr]; ok {
			yearLastValMap[i] = tmpVal
		}
	}

	addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
	var isAdd bool
	//来源指指标数据
	for _, v := range fromDataList {
		currDateStr := v.DataTime
		currDate, _ := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)

		perValMap := make(map[time.Time]float64)
		//前3年当日的数据
		for i := 1; i <= 3; i++ {
			tmpDateTime := currDate.AddDate(-i, 0, 0)
			if tmpVal, ok := handleDataMap[tmpDateTime.Format(utils.FormatDate)]; ok {
				perValMap[tmpDateTime] = tmpVal
			}
		}
		lenPerValMap := len(perValMap)
		// 如果数据少于2年,那么就不参与计算,结束当前循环,进入下一个循环
		if lenPerValMap < 2 {
			continue
		}

		// N年 当前值占全年比重 的值列表
		divValList := make([]decimal.Decimal, 0)
		for tmpDateTime, tmpVal := range perValMap {
			yearLastVal, ok2 := yearLastValMap[tmpDateTime.Year()]
			// 如果当年最后一天没有数据
			if !ok2 {
				continue
			}

			// 当前值占全年比重
			divVal := decimal.NewFromFloat(tmpVal).Div(decimal.NewFromFloat(yearLastVal))
			divValList = append(divValList, divVal)
		}

		lenDivValList := len(divValList)
		// 如果 N年 当前值占全年比重 的值 小于 2个,那么就不参与计算,结束当前循环,进入下一个循环
		if lenDivValList < 2 {
			continue
		}

		divValSum := decimal.NewFromFloat(0)
		for _, divVal := range divValList {
			divValSum = divValSum.Add(divVal)
		}

		// 当前计算出来的结果
		currVal, _ := decimal.NewFromFloat(v.Value).Div(divValSum.Div(decimal.NewFromInt(int64(lenDivValList)))).Round(4).Float64()

		// 给实际日期数据的值赋值
		if fromEdbInfo.LatestDate == currDateStr {
			latestValue = currVal
		}
		// 判断年化指标是否存在数据
		if existData, ok := existDataMap[currDateStr]; ok {
			// 处理年化数据的值
			existValStr := existData.Value
			existValDeci, tmpErr := decimal.NewFromString(existValStr)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existVal, _ := existValDeci.Round(4).Float64()
			// 判断年化数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
			if existVal != currVal {
				err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
				if err != nil {
					return
				}
			}
		} else {
			// 直接入库
			timestamp := currDate.UnixNano() / 1e6
			timestampStr := fmt.Sprintf("%d", timestamp)
			addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
			isAdd = true
		}

		delete(removeDateMap, currDateStr)
	}

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

	// 移除不存在的日期数据
	if len(removeDateMap) > 0 {
		removeDateList := make([]string, 0) //需要移除的日期
		for k := range removeDateMap {
			removeDateList = append(removeDateList, k)
		}
		removeDateStr := strings.Join(removeDateList, `","`)
		removeDateStr = `"` + removeDateStr + `"`
		sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
		_, err = to.Raw(sql, edbInfoId).Exec()
		if err != nil {
			err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
			return
		}
	}

	return
}
