package chart

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/shopspring/decimal"
	edbDataModel "hongze/hongze_yb/models/tables/edb_data"
	edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
	predictEdbConfModel "hongze/hongze_yb/models/tables/predict_edb_conf"
	predictEdbRuleDataModel "hongze/hongze_yb/models/tables/predict_edb_rule_data"
	"hongze/hongze_yb/utils"
	"strconv"
	"time"
)

// GetChartPredictEdbInfoDataListByConfList 获取图表的预测指标的未来数据
func GetChartPredictEdbInfoDataListByConfList(predictEdbConfList []*predictEdbConfModel.PredictEdbConf, filtrateStartDateStr, latestDateStr, endDateStr, frequency, dataDateType string, realPredictEdbInfoData []*edbDataModel.EdbDataList) (predictEdbInfoData []*edbDataModel.EdbDataList, minValue, maxValue float64, err error) {
	endDate, err := time.ParseInLocation(utils.FormatDate, endDateStr, time.Local)
	if err != nil {
		return
	}

	latestDate, err := time.ParseInLocation(utils.FormatDate, latestDateStr, time.Local)
	if err != nil {
		return
	}

	// 开始预测数据的时间
	startDate := latestDate

	// 如果有筛选时间的话
	if filtrateStartDateStr != `` {
		filtrateStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, filtrateStartDateStr, time.Local)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		//如果筛选时间晚于实际数据时间，那么就以筛选时间作为获取预测数据的时间
		if filtrateStartDate.After(latestDate) {
			startDate = filtrateStartDate.AddDate(0, 0, -1)
		}
	}

	//var dateArr []string
	// 对应日期的值
	existMap := make(map[string]float64)
	for _, v := range realPredictEdbInfoData {
		//dateArr = append(dateArr, v.DataTime)
		existMap[v.DataTime] = v.Value
	}

	predictEdbInfoData = make([]*edbDataModel.EdbDataList, 0)
	//dataValue := lastDataValue
	//预测规则，1：最新，2：固定值，3：同比，4：同差，5：环比，6：环差，7：N期移动均值，8：N期段线性外推值

	for _, predictEdbConf := range predictEdbConfList {
		dataEndTime := endDate
		if predictEdbConf.EndDate.Before(dataEndTime) {
			dataEndTime = predictEdbConf.EndDate
		}

		var tmpMinValue, tmpMaxValue float64 // 当前预测结果中的最大/最小值

		dayList := getPredictEdbDayList(startDate, dataEndTime, frequency, dataDateType)
		if len(dayList) <= 0 { // 如果未来没有日期的话，那么就退出当前循环，进入下一个循环
			continue
		}

		switch predictEdbConf.RuleType {
		case 1: //1：最新
			var lastDataValue float64 //最新值
			tmpAllData := make([]*edbDataModel.EdbDataList, 0)
			tmpAllData = append(tmpAllData, realPredictEdbInfoData...)
			tmpAllData = append(tmpAllData, predictEdbInfoData...)
			lenTmpAllData := len(tmpAllData)
			if lenTmpAllData > 0 {
				lastDataValue = tmpAllData[lenTmpAllData-1].Value
			}
			predictEdbInfoData = GetChartPredictEdbInfoDataListByRule1(int(predictEdbConf.PredictEdbInfoID), lastDataValue, dayList, predictEdbInfoData, existMap)
			tmpMaxValue = lastDataValue
			tmpMinValue = lastDataValue
		case 2: //2：固定值
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			dataValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData = GetChartPredictEdbInfoDataListByRule1(int(predictEdbConf.PredictEdbInfoID), dataValue, dayList, predictEdbInfoData, existMap)

			tmpMaxValue = dataValue
			tmpMinValue = dataValue
		case 3: //3：同比
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			tbValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTb(int(predictEdbConf.PredictEdbInfoID), tbValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 4: //4：同差
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			tcValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTc(int(predictEdbConf.PredictEdbInfoID), tcValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 5: //5：环比
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			hbValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleHb(int(predictEdbConf.PredictEdbInfoID), hbValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 6: //6：环差
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			hcValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleHc(int(predictEdbConf.PredictEdbInfoID), hcValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 7: //7：N期移动均值
			nValue, tmpErr := strconv.Atoi(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleNMoveMeanValue(int(predictEdbConf.PredictEdbInfoID), nValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 8: //8：N期段线性外推值
			nValue, tmpErr := strconv.Atoi(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleNLinearRegression(int(predictEdbConf.PredictEdbInfoID), nValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
			if err != nil {
				return
			}
		case 9: //9：动态环差”预测规则；
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTrendsHC(int(predictEdbConf.PredictEdbInfoID), int(predictEdbConf.ConfigID), startDate, dataEndTime, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 10: //10：根据 给定终值后插值 规则获取预测数据
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			finalValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleFinalValueHc(int(predictEdbConf.PredictEdbInfoID), finalValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)

		case 11: //11：根据 季节性 规则获取预测数据
			var seasonConf SeasonConf
			tmpErr := json.Unmarshal([]byte(predictEdbConf.Value), &seasonConf)
			if tmpErr != nil {
				err = errors.New("季节性配置信息异常:" + tmpErr.Error())
				return
			}
			calendar := "公历"
			if seasonConf.Calendar == "农历" {
				calendar = "农历"
			}
			yearList := make([]int, 0)
			//选择方式，1：连续N年；2：指定年份
			if seasonConf.YearType == 1 {
				if seasonConf.NValue < 1 {
					err = errors.New("连续N年不允许小于1")
					return
				}

				currYear := time.Now().Year()
				for i := 0; i < seasonConf.NValue; i++ {
					yearList = append(yearList, currYear-i-1)
				}
			} else {
				yearList = seasonConf.YearList
			}
			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleSeason(int(predictEdbConf.PredictEdbInfoID), yearList, calendar, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
			if err != nil {
				return
			}
		case 12: //12：根据 移动平均同比 规则获取预测数据
			var moveAverageConf MoveAverageConf
			tmpErr := json.Unmarshal([]byte(predictEdbConf.Value), &moveAverageConf)
			if tmpErr != nil {
				err = errors.New("季节性配置信息异常:" + tmpErr.Error())
				return
			}
			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleMoveAverageTb(int(predictEdbConf.PredictEdbInfoID), moveAverageConf.NValue, moveAverageConf.Year, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
			if err != nil {
				return
			}
		case 13: //13：根据 同比增速差值 规则获取预测数据
			tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			tbEndValue, _ := tmpValDecimal.Float64()
			predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTbzscz(int(predictEdbConf.PredictEdbInfoID), tbEndValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
		case 14: //14：根据 一元线性拟合 规则获取预测数据
			var ruleConf RuleLineNhConf
			err = json.Unmarshal([]byte(predictEdbConf.Value), &ruleConf)
			if err != nil {
				err = errors.New("一元线性拟合配置信息异常:" + err.Error())
				return
			}

			// 规则计算的拟合残差值map
			newNhccDataMap := make(map[string]float64)
			if predictEdbConf.PredictEdbInfoID > 0 { //已经生成的动态数据
				tmpPredictEdbRuleDataList, tmpErr := predictEdbRuleDataModel.GetPredictEdbRuleDataList(int(predictEdbConf.PredictEdbInfoID), int(predictEdbConf.ConfigID), "", "")
				if tmpErr != nil {
					err = tmpErr
					return
				}
				for _, v := range tmpPredictEdbRuleDataList {
					newNhccDataMap[v.DataTime.Format(utils.FormatDate)] = v.Value
				}
			} else { //未生成的动态数据，需要使用外部传入的数据进行计算
				newNhccDataMap, err = getCalculateNhccData(append(realPredictEdbInfoData, predictEdbInfoData...), ruleConf)
				if err != nil {
					return
				}
			}

			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleLineNh(int(predictEdbConf.PredictEdbInfoID), dayList, realPredictEdbInfoData, predictEdbInfoData, newNhccDataMap, existMap)
			if err != nil {
				return
			}

		case 15: //15：N年均值：过去N年同期均值。过去N年可以连续或者不连续，指标数据均用线性插值补全为日度数据后计算；
			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleNAnnualAverage(int(predictEdbConf.PredictEdbInfoID), predictEdbConf.Value, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
			if err != nil {
				return
			}

		case 16: //16：年度值倒推
			predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleAnnualValueInversion(int(predictEdbConf.PredictEdbInfoID), predictEdbConf.Value, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
			if err != nil {
				return
			}
		}

		// 下一个规则的开始日期
		{
			lenPredictEdbInfoData := len(predictEdbInfoData)
			if lenPredictEdbInfoData > 0 {
				tmpDataEndTime, _ := time.ParseInLocation(utils.FormatDate, predictEdbInfoData[lenPredictEdbInfoData-1].DataTime, time.Local)
				if startDate.Before(tmpDataEndTime) {
					startDate = tmpDataEndTime
				}
			}
		}

		if tmpMinValue < minValue {
			minValue = tmpMinValue
		}
		if tmpMaxValue < maxValue {
			maxValue = tmpMaxValue
		}
	}

	return
}

// GetPredictEdbDayList 获取预测指标日期列表
func getPredictEdbDayList(startDate, endDate time.Time, frequency, dataDateType string) (dayList []time.Time) {
	if dataDateType == `` {
		dataDateType = `交易日`
	}
	switch frequency {
	case "日度":
		for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
			// 如果日期类型是交易日的时候，那么需要将周六、日排除
			if dataDateType == `交易日` && (currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday) {
				continue
			}
			dayList = append(dayList, currDate)
		}
	case "周度":
		//nextDate := startDate.AddDate(0, 0, 7)
		for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
			dayList = append(dayList, currDate)
		}
	case "旬度":
		for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
			nextDate := currDate.AddDate(0, 0, 1)
			//每个月的10号、20号、最后一天，那么就写入
			if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
				dayList = append(dayList, currDate)
			}
			currDate = nextDate
		}
	case "月度":
		for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
			currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
			if !currDate.After(endDate) && !currDate.Equal(startDate) {
				dayList = append(dayList, currDate)
			}
			currDate = currDate.AddDate(0, 0, 1)
		}
	case "季度":
		for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
			// 每月的最后一天
			currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
			if !currDate.After(endDate) && !currDate.Equal(startDate) {
				// 季度日期就写入，否则不写入
				if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
					dayList = append(dayList, currDate)
				}
			}
			currDate = currDate.AddDate(0, 0, 1)
		}
	case "半年度":
		for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
			// 每月的最后一天
			currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
			if !currDate.After(endDate) && !currDate.Equal(startDate) {
				// 半年度日期就写入，否则不写入
				if currDate.Month() == 6 || currDate.Month() == 12 {
					dayList = append(dayList, currDate)
				}
			}
			currDate = currDate.AddDate(0, 0, 1)
		}
	case "年度":
		for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
			currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
			if !currDate.After(endDate) && !currDate.Equal(startDate) {
				dayList = append(dayList, currDate)
			}
		}
	}
	return
}

// GetPredictDataListByPredictEdbInfoId 根据预测指标id获取预测指标的数据
func GetPredictDataListByPredictEdbInfoId(edbInfoId int, startDate, endDate string, isTimeBetween bool) (edbInfo *edbInfoModel.EdbInfo, dataList []*edbDataModel.EdbDataList, sourceEdbInfoItem *edbInfoModel.EdbInfo, predictEdbConf *predictEdbConfModel.PredictEdbConf, err error, errMsg string) {
	edbInfo, err = edbInfoModel.GetEdbInfoById(edbInfoId)
	if err != nil {
		errMsg = `获取预测指标信息失败`
		return
	}
	dataList, sourceEdbInfoItem, predictEdbConf, err, errMsg = GetPredictDataListByPredictEdbInfo(edbInfo, startDate, endDate, isTimeBetween)

	return
}

// GetPredictDataListByPredictEdbInfo 根据预测指标信息获取预测指标的数据
func GetPredictDataListByPredictEdbInfo(edbInfo *edbInfoModel.EdbInfo, startDate, endDate string, isTimeBetween bool) (dataList []*edbDataModel.EdbDataList, sourceEdbInfoItem *edbInfoModel.EdbInfo, predictEdbConf *predictEdbConfModel.PredictEdbConf, err error, errMsg string) {
	// 非计算指标，直接从表里获取数据
	if !isTimeBetween {
		endDate = ``
	}
	return GetPredictCalculateDataListByPredictEdbInfo(edbInfo, startDate, endDate)
}

// GetPredictCalculateDataListByPredictEdbInfo 根据预测运算指标信息获取预测指标的数据
func GetPredictCalculateDataListByPredictEdbInfo(edbInfo *edbInfoModel.EdbInfo, startDate, endDate string) (dataList []*edbDataModel.EdbDataList, sourceEdbInfoItem *edbInfoModel.EdbInfo, predictEdbConf *predictEdbConfModel.PredictEdbConf, err error, errMsg string) {
	dataList, err = edbDataModel.GetEdbDataList(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbInfoId, startDate, endDate)
	return
}

// GetChartDataList 通过完整的预测数据 进行 季节性图、公历、农历处理
func GetChartDataList(dataList []*edbDataModel.EdbDataList, chartType int, calendar, latestDateStr, startDate string) (resultDataList interface{}, err error) {
	startDateReal := startDate
	calendarPreYear := 0
	if calendar == "农历" {
		newStartDateReal, err := time.Parse(utils.FormatDate, startDateReal)
		if err != nil {
			fmt.Println("time.Parse:" + err.Error())
		}
		calendarPreYear = newStartDateReal.Year() - 1
		newStartDateReal = newStartDateReal.AddDate(-1, 0, 0)
		startDateReal = newStartDateReal.Format(utils.FormatDate)
	}
	//实际数据的截止日期
	latestDate, tmpErr := time.Parse(utils.FormatDate, latestDateStr)
	if tmpErr != nil {
		err = errors.New(fmt.Sprint("获取最后实际数据的日期失败,Err:" + tmpErr.Error() + ";LatestDate:" + latestDateStr))
		return
	}
	latestDateYear := latestDate.Year() //实际数据截止年份

	// 曲线图
	if chartType == 1 {
		resultDataList = dataList
		return
	}

	if calendar == "农历" {
		if len(dataList) <= 0 {
			resultDataList = edbDataModel.EdbDataResult{}
		} else {
			result, tmpErr := edbDataModel.AddCalculateQuarterV4(dataList)
			if tmpErr != nil {
				err = errors.New("获取农历数据失败,Err:" + tmpErr.Error())
				return
			}
			// 处理季节图的截止日期
			for k, edbDataItems := range result.List {
				var cuttingDataTimestamp int64

				// 切割的日期时间字符串
				cuttingDataTimeStr := latestDate.AddDate(0, 0, edbDataItems.BetweenDay).Format(utils.FormatDate)
				//如果等于最后的实际日期，那么遍历找到该日期对应的时间戳，并将其赋值为 切割时间戳
				if edbDataItems.Year >= latestDateYear {
					for _, tmpData := range edbDataItems.Items {
						if tmpData.DataTime == cuttingDataTimeStr {
							cuttingDataTimestamp = tmpData.DataTimestamp
							break
						}
					}
				}
				edbDataItems.CuttingDataTimestamp = cuttingDataTimestamp
				result.List[k] = edbDataItems
			}

			if result.List[0].Year != calendarPreYear {
				itemList := make([]*edbDataModel.EdbDataList, 0)
				items := new(edbDataModel.EdbDataItems)
				//items.Year = calendarPreYear
				items.Items = itemList

				newResult := new(edbDataModel.EdbDataResult)
				newResult.List = append(newResult.List, items)
				newResult.List = append(newResult.List, result.List...)
				resultDataList = newResult
			} else {
				resultDataList = result
			}
		}

	} else {
		currentYear := time.Now().Year()

		quarterDataList := make([]*edbDataModel.QuarterData, 0)
		quarterMap := make(map[int][]*edbDataModel.EdbDataList)
		var quarterArr []int

		for _, v := range dataList {
			itemDate, tmpErr := time.Parse(utils.FormatDate, v.DataTime)
			if tmpErr != nil {
				err = errors.New("季度指标日期转换,Err:" + tmpErr.Error() + ";DataTime:" + v.DataTime)
				return
			}
			year := itemDate.Year()
			newItemDate := itemDate.AddDate(currentYear-year, 0, 0)
			timestamp := newItemDate.UnixNano() / 1e6
			v.DataTimestamp = timestamp
			if findVal, ok := quarterMap[year]; !ok {
				quarterArr = append(quarterArr, year)
				findVal = append(findVal, v)
				quarterMap[year] = findVal
			} else {
				findVal = append(findVal, v)
				quarterMap[year] = findVal
			}
		}
		for _, v := range quarterArr {
			itemList := quarterMap[v]
			quarterItem := new(edbDataModel.QuarterData)
			quarterItem.Year = strconv.Itoa(v)
			quarterItem.DataList = itemList

			//如果等于最后的实际日期，那么将切割时间戳记录
			if v == latestDateYear {
				var cuttingDataTimestamp int64
				for _, tmpData := range itemList {
					if tmpData.DataTime == latestDateStr {
						cuttingDataTimestamp = tmpData.DataTimestamp
						break
					}
				}
				quarterItem.CuttingDataTimestamp = cuttingDataTimestamp
			} else if v > latestDateYear {
				//如果大于最后的实际日期，那么第一个点就是切割的时间戳
				if len(itemList) > 0 {
					quarterItem.CuttingDataTimestamp = itemList[0].DataTimestamp - 100
				}
			}
			quarterDataList = append(quarterDataList, quarterItem)
		}
		resultDataList = quarterDataList
	}
	return
}
