package edb_info

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/request"
	edbInfoModel "hongze/hongze_yb/models/tables/edb_info"
	"hongze/hongze_yb/services/chart"
	"hongze/hongze_yb/utils"
	"strconv"
	"time"
)

// PredictEdbData 预测指标数据
func PredictEdbData(c *gin.Context) {
	var req request.PredictEdbInfoDataReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.EdbInfoId <= 0 {
		response.Fail("参数错误", c)
		return
	}
	if req.DateType <= 0 {
		req.DateType = 3
	}
	if req.EdbInfoType <= 0 {
		req.EdbInfoType = 1
	}
	if req.ChartType <= 0 {
		req.ChartType = 1
	}
	if req.Calendar == "" {
		req.Calendar = "公历"
	}
	isTimeBetween := false //是否是时间区间

	if req.ChartType == 2 {
		req.DateType = 0
		isTimeBetween = true
	}
	if req.DateType == 5 {
		isTimeBetween = true
	}

	edbInfo, e := edbInfoModel.GetEdbInfoById(req.EdbInfoId)
	if e != nil {
		if e == utils.ErrNoRow {
			response.FailMsg("获取失败", "指标不存在，EdbInfoId:"+strconv.Itoa(req.EdbInfoId), c)
			return
		}
		response.FailMsg("获取失败", "获取指标信息失败，Err:"+e.Error(), c)
		return
	}
	startDate, endDate := utils.GetDateByDateTypeV2(req.DateType, req.StartDate, req.EndDate, req.StartYear, edbInfo.LatestDate)
	if endDate == "" {
		endDate = time.Now().Format(utils.FormatDate)
	}
	if req.DateType == 10 {
		startDate = ""
		endDate = ""
	}

	dataList, _, _, e, _ := chart.GetPredictDataListByPredictEdbInfo(edbInfo, startDate, endDate, isTimeBetween)
	if e != nil {
		response.FailMsg("获取失败", "获取预测指标数据失败, Err: "+e.Error(), c)
		return
	}

	// 季节性图、公历、农历处理
	resultDataList, err := chart.GetChartDataList(dataList, req.ChartType, req.Calendar, edbInfo.LatestDate.Format(utils.FormatDate), startDate)
	if err != nil {
		response.FailMsg("获取失败", "季节性图、公历、农历处理失败, Err: "+e.Error(), c)
		return
	}

	type PredictEdbInfoDataResp struct {
		EdbInfo  *edbInfoModel.EdbInfo
		DataList interface{}
	}
	resp := new(PredictEdbInfoDataResp)
	resp.EdbInfo = edbInfo
	resp.DataList = resultDataList
	response.OkData("获取成功", resp, c)
}
