package models

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

// EdbDataPredictCalculateLjztbpj 累计值同比拼接数据结构体
type EdbDataPredictCalculateLjztbpj struct {
	EdbDataId     int `orm:"column(edb_data_id);pk"`
	EdbInfoId     int
	EdbCode       string
	DataTime      string
	Value         float64
	Status        int
	CreateTime    time.Time
	ModifyTime    time.Time
	DataTimestamp int64
}

// SavePredictCalculateLjztbpj 新增累计值同比拼接数据
func SavePredictCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("SavePredictCalculateLjztbpj,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	//最近开始的时间
	var lastDateTime time.Time
	var existItemA, existItemB *EdbInfoCalculateMapping
	//获取待拼接指标
	{
		/*var condition string
		var pars []interface{}

		//获取待拼接指标最近的个12月31日有值的年份
		condition += " AND data_time like ? AND edb_info_id=? "
		pars = append(pars, "%12-31", firstEdbInfo.EdbInfoId)

		lastEdbData, tmpErr := GetLastEdbData(condition, pars, firstEdbInfo.Source)
		if tmpErr != nil {
			err = tmpErr
			return
		}*/
		var firstDataList []*EdbInfoSearchData
		var lastEdbData *EdbInfoSearchData
		firstDataList, err = GetPredictEdbDataListAllByStartDate(firstEdbInfo, 0, "")
		if err != nil {
			return
		}
		for _, v := range firstDataList {
			if strings.Contains(v.DataTime, "-12-31") {
				lastEdbData = v
			}
		}

		if lastEdbData == nil {
			err = errors.New("找不到最近的12月31号")
			return
		}
		lastDateTime, _ = time.ParseInLocation(utils.FormatDate, lastEdbData.DataTime, time.Local)
	}

	if req.EdbInfoId <= 0 {
		edbInfo = &EdbInfo{
			EdbInfoType:      1,
			SourceName:       "预测累计值同比拼接",
			Source:           utils.DATA_SOURCE_PREDICT_CALCULATE_LJZTBPJ,
			EdbCode:          edbCode,
			EdbName:          req.EdbName,
			EdbNameSource:    req.EdbName,
			Frequency:        req.Frequency,
			Unit:             req.Unit,
			StartDate:        firstEdbInfo.StartDate,
			EndDate:          firstEdbInfo.EndDate,
			ClassifyId:       req.ClassifyId,
			SysUserId:        sysUserId,
			SysUserRealName:  sysUserRealName,
			UniqueCode:       uniqueCode,
			CreateTime:       time.Now(),
			ModifyTime:       time.Now(),
			CalculateFormula: lastDateTime.Format(utils.FormatDate),
			EdbType:          2,
		}
		newEdbInfoId, tmpErr := to.Insert(edbInfo)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		edbInfo.EdbInfoId = int(newEdbInfoId)
		//关联关系
		{
			existItemA = &EdbInfoCalculateMapping{
				EdbInfoCalculateMappingId: 0,
				EdbInfoId:                 edbInfo.EdbInfoId,
				Source:                    edbInfo.Source,
				SourceName:                edbInfo.SourceName,
				EdbCode:                   edbInfo.EdbCode,
				FromEdbInfoId:             firstEdbInfo.EdbInfoId,
				FromEdbCode:               firstEdbInfo.EdbCode,
				FromEdbName:               firstEdbInfo.EdbName,
				FromSource:                firstEdbInfo.Source,
				FromSourceName:            firstEdbInfo.SourceName,
				FromTag:                   "A",
				Sort:                      1,
				CreateTime:                time.Now(),
				ModifyTime:                time.Now(),
			}
			insertId, tmpErr := to.Insert(existItemA)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existItemA.EdbInfoCalculateMappingId = int(insertId)
		}

		//同比值指标
		{
			existItemB = &EdbInfoCalculateMapping{
				EdbInfoCalculateMappingId: 0,
				EdbInfoId:                 edbInfo.EdbInfoId,
				Source:                    edbInfo.Source,
				SourceName:                edbInfo.SourceName,
				EdbCode:                   edbInfo.EdbCode,
				FromEdbInfoId:             secondEdbInfo.EdbInfoId,
				FromEdbCode:               secondEdbInfo.EdbCode,
				FromEdbName:               secondEdbInfo.EdbName,
				FromSource:                secondEdbInfo.Source,
				FromSourceName:            secondEdbInfo.SourceName,
				FromTag:                   "B",
				Sort:                      1,
				CreateTime:                time.Now(),
				ModifyTime:                time.Now(),
			}
			insertId, tmpErr := to.Insert(existItemB)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existItemB.EdbInfoCalculateMappingId = int(insertId)
		}
	} else {
		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
		if err != nil {
			return
		}
		latestDateStr = edbInfo.LatestDate
		latestValue = edbInfo.LatestValue
		nowEdbInfo := *edbInfo // 现在的指标信息

		sql := ``
		//修改指标信息
		edbInfo.EdbNameSource = req.EdbName
		edbInfo.Frequency = req.Frequency
		edbInfo.Unit = req.Unit
		edbInfo.ClassifyId = req.ClassifyId
		edbInfo.CalculateFormula = lastDateTime.Format(utils.FormatDate)
		edbInfo.ModifyTime = time.Now()
		_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
		if err != nil {
			return
		}

		//查询出所有的关联指标
		var existCondition string
		var existPars []interface{}
		existCondition += " AND edb_info_id=? "
		existPars = append(existPars, edbInfo.EdbInfoId)
		var existList []*EdbInfoCalculateMapping
		existList, err = GetEdbInfoCalculateListByCondition(existCondition, existPars)
		if err != nil {
			err = errors.New("判断指标是否改变失败,Err:" + err.Error())
			return
		}
		for _, existItem := range existList {
			if existItem.FromTag == "A" {
				existItemA = existItem
			} else if existItem.FromTag == "B" {
				existItemB = existItem
			}
		}
		if existItemA == nil {
			err = errors.New("原待拼接指标不存在")
			return
		}
		if existItemB == nil {
			err = errors.New("原同比值指标不存在")
			return
		}
		// 是否需要删除数据重新计算
		isNeedCalculateData := false

		// 如果截止日期变更，那么需要重新计算
		if lastDateTime.Format(utils.FormatDate) != nowEdbInfo.CalculateFormula {
			isNeedCalculateData = true
		}

		//待拼接指标数据
		//如果拼接指标变更了，那么需要删除所有的指标进行重新拼接
		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
			//删除之前的A指标关联关系
			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
			_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemA.FromEdbInfoId).Exec()
			if err != nil {
				err = errors.New("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
				return
			}
		}

		//同比值指标
		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
			//删除之前的B指标关联关系
			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
			_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemB.FromEdbInfoId).Exec()
			if err != nil {
				err = errors.New("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
				return
			}
		}
		//添加新的指标关系
		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
			existItemA = &EdbInfoCalculateMapping{
				EdbInfoCalculateMappingId: 0,
				EdbInfoId:                 edbInfo.EdbInfoId,
				Source:                    edbInfo.Source,
				SourceName:                edbInfo.SourceName,
				EdbCode:                   edbInfo.EdbCode,
				FromEdbInfoId:             firstEdbInfo.EdbInfoId,
				FromEdbCode:               firstEdbInfo.EdbCode,
				FromEdbName:               firstEdbInfo.EdbName,
				FromSource:                firstEdbInfo.Source,
				FromSourceName:            firstEdbInfo.SourceName,
				FromTag:                   "A",
				Sort:                      1,
				CreateTime:                time.Now(),
				ModifyTime:                time.Now(),
			}
			insertId, tmpErr := to.Insert(existItemA)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existItemA.EdbInfoCalculateMappingId = int(insertId)

			isNeedCalculateData = true
		}

		//添加新的指标关系
		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
			existItemB = &EdbInfoCalculateMapping{
				EdbInfoCalculateMappingId: 0,
				EdbInfoId:                 edbInfo.EdbInfoId,
				Source:                    edbInfo.Source,
				SourceName:                edbInfo.SourceName,
				EdbCode:                   edbInfo.EdbCode,
				FromEdbInfoId:             secondEdbInfo.EdbInfoId,
				FromEdbCode:               secondEdbInfo.EdbCode,
				FromEdbName:               secondEdbInfo.EdbName,
				FromSource:                secondEdbInfo.Source,
				FromSourceName:            secondEdbInfo.SourceName,
				FromTag:                   "B",
				Sort:                      2,
				CreateTime:                time.Now(),
				ModifyTime:                time.Now(),
			}

			insertId, tmpErr := to.Insert(existItemB)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			existItemB.EdbInfoCalculateMappingId = int(insertId)

			isNeedCalculateData = true
		}

		// 如果需要重新计算，那么先删除所有的指标数据，然后再重新计算
		if isNeedCalculateData {
			// 删除之前所有的指标数据
			tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
			sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
			if err != nil {
				err = errors.New("删除所有的累计值同比拼接指标数据失败,Err:" + err.Error())
				return
			}
		} else {
			return
		}
	}

	// 添加数据
	latestDateStr, latestValue, err = refreshAllPredictCalculateLjztbpj(to, edbInfo, firstEdbInfo, secondEdbInfo, existItemB)

	return
}

// RefreshAllPredictCalculateLjztbpj 刷新所有 累计值同比拼接 数据
func RefreshAllPredictCalculateLjztbpj(edbInfo *EdbInfo) (latestDateStr string, latestValue float64, err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println("RefreshAllCalculateLjztbpj,Err:" + err.Error())
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()

	//查询关联指标信息
	var existCondition string
	var existPars []interface{}
	existCondition += " AND edb_info_id=? "
	existPars = append(existPars, edbInfo.EdbInfoId)
	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
	if err != nil {
		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
		return
	}

	var existItemA, existItemB *EdbInfoCalculateMapping
	for _, existItem := range existList {
		if existItem.FromTag == "A" {
			existItemA = existItem
		} else if existItem.FromTag == "B" {
			existItemB = existItem
		}
	}
	if existItemA == nil {
		err = errors.New("原待拼接指标不存在")
		return
	}
	if existItemB == nil {
		err = errors.New("原同比值指标不存在")
		return
	}
	fromEdbInfo, err := GetEdbInfoById(existItemA.FromEdbInfoId)
	if err != nil {
		err = fmt.Errorf("GetEdbInfoById Err:" + err.Error())
		return
	}

	secondEdbInfo, err := GetEdbInfoById(existItemB.FromEdbInfoId)
	if err != nil {
		err = fmt.Errorf("GetEdbInfoById Err:" + err.Error())
		return
	}
	// 刷新数据
	latestDateStr, latestValue, err = refreshAllPredictCalculateLjztbpj(to, edbInfo, fromEdbInfo, secondEdbInfo, existItemB)
	return
}

// refreshAllPredictCalculateLjztbpj 刷新所有 累计值同比拼接 数据
func refreshAllPredictCalculateLjztbpj(to orm.TxOrmer, edbInfo, firstEdbInfo, secondEdbInfo *EdbInfo, existItemB *EdbInfoCalculateMapping) (latestDateStr string, latestValue float64, err error) {
	//根据指标id获取全部的数据
	var dataList []*EdbDataPredictCalculateLjztbpj
	sql := ` SELECT * FROM edb_data_predict_calculate_ljztbpj WHERE edb_info_id=? ORDER BY data_time DESC `
	_, err = to.Raw(sql, edbInfo.EdbInfoId).QueryRows(&dataList)
	if err != nil {
		return
	}
	latestDateStr = secondEdbInfo.LatestDate

	//待拼接指标map
	pjDataMap := make(map[string]float64)     //需要入库的数据
	nowEdbDataMap := make(map[string]float64) //当前指标的数据（已经在库里了，不需要重新）
	//拼接指标的日期切片数据
	pjEdbDataTimeList := make([]string, 0)

	dataMap := make(map[string]*EdbDataPredictCalculateLjztbpj)
	for _, v := range dataList {
		pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
		dataMap[v.DataTime] = v
		nowEdbDataMap[v.DataTime] = v.Value
	}

	// 原数据开始计算日期
	startCalculationDate, _ := time.ParseInLocation(utils.FormatDate, edbInfo.CalculateFormula, time.Local)

	//待拼接指标
	{
		/*var condition string
		var pars []interface{}

		condition += " AND data_time <= ? AND edb_info_id=? "
		pars = append(pars, startCalculationDate, existItemA.FromEdbInfoId)

		//第一个指标的数据列表
		firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemA.FromSource, 0)
		if tmpErr != nil {
			err = tmpErr
			return
		}*/
		var firstDataList []*EdbInfoSearchData
		firstDataList, err = GetPredictEdbDataListAllByStartDate(firstEdbInfo, 0, "")
		if err != nil {
			return
		}

		for _, v := range firstDataList {
			if v.DataTime > startCalculationDate.Format(utils.FormatDate) {
				continue
			}
			//时间戳
			if edbData, ok := dataMap[v.DataTime]; ok {
				if edbData.Value != v.Value {
					//更新指标数据
					edbData.Value = v.Value
					_, _ = to.Update(edbData, "Value")
				}
			} else {
				pjDataMap[v.DataTime] = v.Value
				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
			}

			//将新的数据存入已入库指标map里面，以便后续计算
			nowEdbDataMap[v.DataTime] = v.Value
		}
	}

	//同比值指标map
	tbzEdbDataMap := make(map[string]float64)

	//同比值日期切片列表
	tbzEdbDataTimeList := make([]string, 0)

	//同比值指标
	{
		//第二个指标的数据列表
		secondDataList, tmpErr := GetEdbDataListAllByTo(to, existItemB.FromSource, existItemB.FromSubSource, FindEdbDataListAllCond{
			EdbInfoId:         existItemB.FromEdbInfoId,
			StartDataTime:     startCalculationDate.Format(utils.FormatDate),
			StartDataTimeCond: ">",
		}, 0)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		for _, v := range secondDataList {
			tbzEdbDataMap[v.DataTime] = v.Value
			tbzEdbDataTimeList = append(tbzEdbDataTimeList, v.DataTime)
		}
	}

	sort.Strings(tbzEdbDataTimeList)

	// 遍历现有的数据，判断拼接指标中是否存在该日期数据，如果拼接指标无此数据，那么需要删除该日期数据（日期的判断：需要在开始计算日期之后）
	removeDateList := make([]string, 0)
	for nowEdbDate := range nowEdbDataMap {
		nowEdbDateTime, _ := time.ParseInLocation(utils.FormatDate, nowEdbDate, time.Local)
		//校验日期 需要 大于 拼接前日期
		if startCalculationDate.Before(nowEdbDateTime) {
			if _, ok := tbzEdbDataMap[nowEdbDate]; !ok {
				// 同比指标中，不存在该日期数据，那么需要移除 现有数据 中该日期的数据
				removeDateList = append(removeDateList, nowEdbDate)
			}
		}
	}

	//待修改的指标数据map（index：日期，value：值）
	updateEdbDataMap := make(map[string]float64)
	for _, v := range tbzEdbDataTimeList {
		tbzDataTime, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)

		//获取拼接指标上一年同一天的数据
		var pjDataTime time.Time
		if tbzDataTime.Month() == 2 {
			pjDataTime = tbzDataTime.AddDate(0, -11, 0)
			pjDataTime = time.Date(pjDataTime.Year(), pjDataTime.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, -1)
		} else {
			pjDataTime = tbzDataTime.AddDate(-1, 0, 0)
		}

		//校验现有数据中，是否存在该日期的数据，如果存在的话，那么就要去校验 最新计算数据 与 现有数据 是否一致
		if nowEdbDataValue, isHas := nowEdbDataMap[v]; isHas {
			//获取去年今日的数据，获取到后，然后是去修改该日期的数据
			if lastYearEdbDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
				tbzDataValue := tbzEdbDataMap[v] //同比值
				currValue := lastYearEdbDataValue * (1 + tbzDataValue/100)
				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64() //保留4位小数
				//如果计算出来的值与库里面的值不匹配，那么就去修改该值
				if nowEdbDataValue != currValue {
					//将计算后的数据存入待拼接指标map里面，以便后续计算
					updateEdbDataMap[v] = currValue
				}
			}
		} else {
			//因为 现有数据中 不存在该日期数据，那么需要做新增数据处理
			//如果去年今日存在该数据，那么就去计算当前的数据
			if pjDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
				tbzDataValue := tbzEdbDataMap[v] //同比值
				currValue := pjDataValue * (1 + tbzDataValue/100)

				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64()
				//将计算后的数据存入已入库指标map里面，以便后续计算
				nowEdbDataMap[v] = currValue

				//将计算后的数据存入待拼接指标map里面，以便后续入库
				pjDataMap[v] = currValue
				pjEdbDataTimeList = append(pjEdbDataTimeList, v)
			}
		}
	}

	//新增的数据入库
	{
		addDataList := make([]*EdbDataPredictCalculateLjztbpj, 0)
		//日期排序下
		sort.Strings(pjEdbDataTimeList)
		//这么做的目的是为了让数据插入的时候，可以正序插入（业务上没啥卵用，就是为了让我看数据的时候舒服点，手动狗头-_-|）
		for _, dataTime := range pjEdbDataTimeList {
			if dataValue, ok := pjDataMap[dataTime]; ok {
				//时间戳
				currentDate, _ := time.ParseInLocation(utils.FormatDate, dataTime, time.Local)
				timestamp := currentDate.UnixNano() / 1e6

				edbDataLjztbpj := &EdbDataPredictCalculateLjztbpj{
					EdbInfoId:     edbInfo.EdbInfoId,
					EdbCode:       edbInfo.EdbCode,
					DataTime:      dataTime,
					Value:         dataValue,
					Status:        1,
					CreateTime:    time.Now(),
					ModifyTime:    time.Now(),
					DataTimestamp: timestamp,
				}
				addDataList = append(addDataList, edbDataLjztbpj)
			}
		}

		//数据入库
		if len(addDataList) > 0 {
			_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
			if tmpErr != nil {
				err = tmpErr
				return
			}
		}
	}

	//删除已经不存在的累计同比拼接指标数据（由于同比值当日的数据删除了）
	{
		if len(removeDateList) > 0 {
			removeDateStr := strings.Join(removeDateList, `","`)
			removeDateStr = `"` + removeDateStr + `"`
			//如果拼接指标变更了，那么需要删除所有的指标数据
			tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
			sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)

			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
			if err != nil {
				err = errors.New("删除不存在的累计值同比拼接指标数据失败,Err:" + err.Error())
				return
			}
		}
	}

	//修改现有的数据中对应的值
	{
		tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
		for edbDate, edbDataValue := range updateEdbDataMap {
			sql := fmt.Sprintf(` UPDATE  %s set value = ?,modify_time=now() WHERE edb_info_id = ? and data_time = ? `, tableName)
			_, err = to.Raw(sql, edbDataValue, edbInfo.EdbInfoId, edbDate).Exec()
			if err != nil {
				err = errors.New("更新现有的累计值同比拼接指标数据失败,Err:" + err.Error())
				return
			}
		}
	}

	//确定最终值
	var finalLast EdbInfoSearchData
	sql = ` SELECT data_time , value FROM edb_data_predict_calculate_ljztbpj WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `
	tmpErr := to.Raw(sql, edbInfo.EdbInfoId, latestDateStr).QueryRow(&finalLast)
	if tmpErr != nil {
		if tmpErr.Error() != utils.ErrNoRow() {
			err = tmpErr
		}
		return
	} else {
		latestDateStr = finalLast.DataTime
		latestValue = finalLast.Value
	}
	return
}
