package open

import (
	"encoding/json"
	"eta/eta_index_lib/controllers"
	"eta/eta_index_lib/models"
	"eta/eta_index_lib/utils"
	"fmt"
)

// EdbInfoController 指标数据
type EdbInfoController struct {
	controllers.BaseAuthController
}

// Detail
// @Title 指标详情接口
// @Description  指标详情接口
// @Success 200 {object} models.EdbInfoDetailReq
// @router /edb/detail [post]
func (this *EdbInfoController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EdbInfoDetailReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.UniqueCode == "" {
		br.Msg = "请输入指标编码！"
		br.ErrMsg = "请输入指标编码，指标编码为空"
		return
	}
	edbInfo, err := models.GetEdbInfoByUniqueCode(req.UniqueCode)
	if err != nil {
		br.Msg = "获取失败"
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "找不到该指标"
		}
		br.ErrMsg = "获取失败，ERR；" + err.Error()
		return
	}

	dataList := make([]*models.EdbInfoSearchData, 0)
	switch edbInfo.EdbInfoType {
	case 0:
		//获取来源指标的数据
		dataList, err = models.GetEdbDataListAll(edbInfo.Source, edbInfo.SubSource, models.FindEdbDataListAllCond{
			EdbInfoId: edbInfo.EdbInfoId,
		}, 1)
	case 1:
		dataList, err = models.GetPredictEdbDataListAllByStartDate(edbInfo, 1, "")
	default:
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取失败,指标base类型异常", edbInfo.EdbInfoType)
		return
	}

	resp := models.EdbInfoDetailResp{
		SourceName:    edbInfo.SourceName,
		EdbCode:       edbInfo.EdbCode,
		EdbName:       edbInfo.EdbName,
		EdbNameSource: edbInfo.EdbNameSource,
		Frequency:     edbInfo.Frequency,
		Unit:          edbInfo.Unit,
		StartDate:     edbInfo.StartDate,
		EndDate:       edbInfo.EndDate,
		UniqueCode:    edbInfo.UniqueCode,
		CreateTime:    edbInfo.CreateTime,
		ModifyTime:    edbInfo.ModifyTime,
		MinValue:      edbInfo.MinValue,
		MaxValue:      edbInfo.MaxValue,
		EdbNameEn:     edbInfo.EdbNameEn,
		UnitEn:        edbInfo.UnitEn,
		LatestDate:    edbInfo.LatestDate,
		LatestValue:   edbInfo.LatestValue,
		ChartImage:    edbInfo.ChartImage,
		DataList:      dataList,
	}

	br.Data = resp

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
