package data_manage

import (
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/services/data"
	"eta/eta_mobile/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
)

// PredictEdbInfoController 预测指标
type PredictEdbInfoController struct {
	controllers.BaseAuthController
}

// List
// @Title 指标数据列表接口
// @Description 指标数据列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   EdbInfoId   query   int  true       "指标id"
// @Param   KeyWord   query   string  false       "搜索关键词:指标ID/指标名称"
// @Success 200 {object} data_manage.EdbInfoListResp
// @router /predict_edb_info/list [get]
func (this *PredictEdbInfoController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	edbInfoId, _ := this.GetInt("EdbInfoId")
	keyWord := this.GetString("KeyWord")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	// 指标类型，0：普通指标，1：预测指标
	condition += " AND edb_info_type=? "
	pars = append(pars, 1)

	if edbInfoId > 0 {
		condition += " AND edb_info_id=? "
		pars = append(pars, edbInfoId)
	}

	if keyWord != "" {
		condition += ` AND  ( edb_code LIKE '%` + keyWord + `%'  OR  edb_name LIKE '%` + keyWord + `%' )`
		//pars = append(pars, keyWord)
		//pars = append(pars, keyWord)
	}

	resp := data_manage.EdbInfoListResp{}
	if condition == "" {
		item := new(data_manage.EdbInfoList)
		resp.Paging = page
		resp.Item = item
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	//获取指标信息
	edbInfoItem, err := data_manage.GetEdbInfoByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标信息失败,Err:" + err.Error()
		return
	}

	if edbInfoItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
		item := new(data_manage.EdbInfoList)
		resp.Paging = page
		resp.Item = item
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	//获取英文频度
	edbInfoItem.FrequencyEn = data.GetFrequencyEn(edbInfoItem.Frequency)

	// 未来的指标预测数据
	predictDataList := make([]*data_manage.EdbData, 0)

	var existCondition string
	var existPars []interface{}
	existCondition += " AND edb_info_id=? "
	existPars = append(existPars, edbInfoId)

	//查询出所有的关联指标
	sourceEdbInfoCalculateMappingList, err := data_manage.GetEdbInfoCalculateListByCondition(existCondition, existPars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取预测指标关联信息失败，Err:" + err.Error()
		return
	}
	if len(sourceEdbInfoCalculateMappingList) <= 0 {
		br.Msg = "获取失败"
		br.ErrMsg = "查找预测指标关联信息失败"
		return
	}
	if edbInfoItem.EdbType == 1 { //普通的预测指标
		// 查找该预测指标配置
		predictEdbConfList, err := data_manage.GetPredictEdbConfListById(edbInfoId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取预测指标配置信息失败，Err:" + err.Error()
			return
		}
		if len(predictEdbConfList) == 0 {
			br.Msg = "找不到该预测指标配置"
			br.ErrMsg = "找不到该预测指标配置"
			return
		}
		predictEdbConf := predictEdbConfList[0]

		//预测数据的配置
		edbInfoItem.RuleType = predictEdbConf.RuleType
		edbInfoItem.FixedValue = predictEdbConf.FixedValue

		// 来源指标
		//sourceEdbInfoId := sourceEdbInfoCalculateMappingList[0].FromEdbInfoId
		sourceEdbInfoId := predictEdbConf.SourceEdbInfoId
		sourceEdbInfoItem, err := data_manage.GetEdbInfoById(sourceEdbInfoId)
		if err != nil {
			br.Msg = "获取来源指标信息失败"
			br.ErrMsg = "获取来源指标信息失败"
			if err.Error() != utils.ErrNoRow() {
				br.ErrMsg = "获取来源指标信息失败,Err:" + err.Error()
			}
			br.Success = true
			return
		}

		//获取指标数据（实际已生成）
		{
			var dataCondition string
			var dataPars []interface{}

			dataCondition += ` AND edb_info_id=? `
			dataPars = append(dataPars, sourceEdbInfoItem.EdbInfoId)

			dataCount, err := data_manage.GetEdbDataCountByCondition(dataCondition, dataPars, sourceEdbInfoItem.Source)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
				return
			}
			page = paging.GetPaging(currentIndex, pageSize, dataCount)
			dataList, err := data_manage.GetEdbDataListByCondition(dataCondition, dataPars, sourceEdbInfoItem.Source, pageSize, startSize)
			if err != nil {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标数据失败,Err:" + err.Error()
				return
			}
			edbInfoItem.DataList = dataList
		}

		// 第一页才需要 获取预测指标未来的数据
		if currentIndex == 1 {
			allDataList, err := data_manage.GetEdbDataList(sourceEdbInfoItem.Source, sourceEdbInfoItem.EdbInfoId, "", "")
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取失败,Err:" + err.Error()
				return
			}
			predictEdbConfDataList := make([]data_manage.PredictEdbConfAndData, 0)
			for _, v := range predictEdbConfList {
				predictEdbConfDataList = append(predictEdbConfDataList, data_manage.PredictEdbConfAndData{
					ConfigId:         v.ConfigId,
					PredictEdbInfoId: v.PredictEdbInfoId,
					SourceEdbInfoId:  v.SourceEdbInfoId,
					RuleType:         v.RuleType,
					FixedValue:       v.FixedValue,
					Value:            v.Value,
					EndDate:          v.EndDate,
					ModifyTime:       v.ModifyTime,
					CreateTime:       v.CreateTime,
					DataList:         make([]*data_manage.EdbDataList, 0),
				})
			}
			tmpPredictDataList, _, _, err, _ := data.GetChartPredictEdbInfoDataListByConfList(predictEdbConfDataList, sourceEdbInfoItem.LatestDate, sourceEdbInfoItem.LatestDate, edbInfoItem.EndDate, sourceEdbInfoItem.Frequency, edbInfoItem.DataDateType, allDataList)
			if err != nil {
				br.Msg = "获取预测指标数据失败"
				br.ErrMsg = "获取预测指标数据失败" + err.Error()
				return
			}
			lenTmpPredictDataList := len(tmpPredictDataList)
			if lenTmpPredictDataList > 0 {
				for i := lenTmpPredictDataList - 1; i >= 0; i-- {
					v := tmpPredictDataList[i]
					predictDataList = append(predictDataList, &data_manage.EdbData{
						EdbDataId: v.EdbDataId,
						EdbInfoId: v.EdbInfoId,
						DataTime:  v.DataTime,
						Value:     v.Value,
					})
				}
			}
		}
	} else {
		//获取指标数据（实际已生成）
		{
			var dataCondition string
			var dataPars []interface{}

			dataCondition += ` AND edb_info_id=? AND data_time <= ? `
			dataPars = append(dataPars, edbInfoItem.EdbInfoId, edbInfoItem.LatestDate)

			dataCount, err := data_manage.GetEdbDataCountByCondition(dataCondition, dataPars, edbInfoItem.Source)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
				return
			}
			page = paging.GetPaging(currentIndex, pageSize, dataCount)
			dataList, err := data_manage.GetEdbDataListByCondition(dataCondition, dataPars, edbInfoItem.Source, pageSize, startSize)
			if err != nil {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标数据失败,Err:" + err.Error()
				return
			}
			edbInfoItem.DataList = dataList
		}

		// 第一页才需要 获取预测指标未来的数据
		if currentIndex == 1 {
			var dataCondition string
			var dataPars []interface{}

			dataCondition += ` AND edb_info_id=? AND data_time > ? `
			dataPars = append(dataPars, edbInfoItem.EdbInfoId, edbInfoItem.LatestDate)

			predictDataList, err = data_manage.GetAllEdbDataListByCondition(dataCondition, dataPars, edbInfoItem.Source)
			if err != nil {
				br.Msg = "获取指标信息失败"
				br.ErrMsg = "获取指标数据失败,Err:" + err.Error()
				return
			}
			if err != nil {
				br.Msg = "获取预测指标数据失败"
				br.ErrMsg = "获取预测指标数据失败" + err.Error()
				return
			}
		}
	}

	// 如果预测数据没有，那么返回空数组
	if predictDataList == nil {
		predictDataList = make([]*data_manage.EdbData, 0)
	}
	edbInfoItem.PredictDataList = predictDataList

	// 如果实际数据没有，那么返回空数组
	if edbInfoItem.DataList == nil {
		edbInfoItem.DataList = make([]*data_manage.EdbData, 0)
	}
	//查询目录
	classifyList, err, errMsg := data.GetFullClassifyByClassifyId(edbInfoItem.ClassifyId)
	if err != nil {
		br.Msg = err.Error()
		br.ErrMsg = errMsg
		return
	}
	resp.Paging = page
	resp.Item = edbInfoItem
	resp.ClassifyList = classifyList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
