package supply_analysis

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/request"
	"eta/eta_api/models/data_manage/response"
	"eta/eta_api/models/data_manage/supply_analysis"
	"eta/eta_api/services/data"
	supply_analysisServ "eta/eta_api/services/data/supply_analysis"
	"eta/eta_api/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// EdbList
// @Title 指标列表
// @Description 指标列表
// @Param   VarietyId   query   int  true       "品种id"
// @Success 200 {object} response.VarietyEdbListResp
// @router /variety/edb/list [get]
func (this *VarietyController) EdbList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	varietyId, _ := this.GetInt("VarietyId")
	if varietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(varietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}
	if varietyInfo == nil {
		br.Msg = "不存在该品种或该品种已被删除"
		br.ErrMsg = "不存在该品种或该品种已被删除"
		br.IsSendEmail = false
		return
	}

	var hasPermission bool //是否有操作权限
	// 是否有装置的操作权限
	hasPermission, err = supply_analysisServ.HasVarietyPlantPermission(this.SysUser, varietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "查询是否有装置的操作权限失败;ERR:" + err.Error()
		return
	}

	var list []*supply_analysis.VarietyEdbInfoItem
	list, err = supply_analysis.GetAllVarietyEdbInfoByVarietyId(varietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	// ETA指标库的相关信息
	edbInfoAndClassifyMap := make(map[int]*data_manage.EdbAndClassify)
	{
		edbInfoIdList := make([]int, 0)
		for _, v := range list {
			edbInfoIdList = append(edbInfoIdList, v.EdbInfoId)
		}

		edbInfoAndClassifyList, err := data_manage.GetEdbInfoAndClassifyListByEdbIdList(edbInfoIdList)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取ETA指标的信息失败，Err:" + err.Error()
			return
		}
		for _, v := range edbInfoAndClassifyList {
			edbInfoAndClassifyMap[v.EdbInfoId] = v
		}
	}
	for k, v := range list {
		button := supply_analysis.VarietyEdbInfoButton{
			Copy: true,
			Show: true,
		}

		if tmpItem, ok := edbInfoAndClassifyMap[v.EdbInfoId]; ok {
			v.ClassifyName = tmpItem.FirstClassifyName + "/" + tmpItem.SecondClassifyName
			v.ClassifyId = tmpItem.SecondClassifyId
			v.EdbCode = tmpItem.EdbCode
			v.UniqueCode = tmpItem.UniqueCode
		} else {
			button.Show = false
			v.EdbCode = ``
			v.EdbInfoId = 0
			if hasPermission {
				button.Add = true
			}
		}

		v.Button = button
		list[k] = v
	}

	resp := response.VarietyEdbListResp{
		List: list,
	}

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

// AddToEdb
// @Title 添加到指标库
// @Description 添加到指标库
// @Param	request	body data_manage.AddEdbInfoReq true "type json string"
// @Success 200 {object} response.VarietyEdbListResp
// @router /variety/edb/add [post]
func (this *VarietyController) AddToEdb() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.AddEdbInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	req.EdbName = strings.Trim(req.EdbName, " ")

	if req.VarietyEdbId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	cacheKey := "VARIETY_ADD_EDB:" + strconv.Itoa(req.VarietyEdbId)
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	defer func() {
		utils.Rc.Delete(cacheKey)
	}()

	if req.EdbName == "" {
		br.Msg = "指标名称不能为空"
		return
	}

	if req.Frequency == "" {
		br.Msg = "频率不能为空"
		return
	}

	if req.Unit == "" {
		br.Msg = "单位不能为空"
		return
	}

	if req.ClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}

	varietyEdbInfo, err := supply_analysis.GetVarietyEdbInfoByVarietyEdbId(req.VarietyEdbId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "找不到该指标"
			br.IsSendEmail = false
		} else {
			br.Msg = "添加失败"
			br.ErrMsg = "添加失败，ERR:" + err.Error()
		}
		return
	}

	var hasPermission bool //是否有操作权限
	// 是否有装置的操作权限
	hasPermission, err = supply_analysisServ.HasVarietyPlantPermission(this.SysUser, varietyEdbInfo.VarietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "查询是否有装置的操作权限失败;ERR:" + err.Error()
		return
	}
	if !hasPermission {
		br.Msg = "无操作权限"
		br.ErrMsg = "无操作权限"
		return
	}

	if varietyEdbInfo.EdbInfoId > 0 {
		tmpEdbInfo, err := data_manage.GetEdbInfoById(varietyEdbInfo.EdbInfoId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "添加失败"
			br.ErrMsg = "查询ETA指标失败，ERR:" + err.Error()
			return
		}
		if tmpEdbInfo != nil {
			br.Msg = "该指标已加入ETA指标库中"
			br.ErrMsg = "该指标已加入ETA指标库中"
			return
		}
	}

	// 指标入库
	randStr := utils.GetRandDigit(4)
	prefixCode := "HZ_V"
	suffixCode := time.Now().Format("060102") + randStr
	edbCode := fmt.Sprint(prefixCode, varietyEdbInfo.Source, suffixCode)
	edbInfo, err, errMsg, isSendEmail := data.EdbInfoAdd(utils.DATA_SOURCE_STOCK_PLANT, req.ClassifyId, edbCode, req.EdbName, req.Frequency, req.Unit, varietyEdbInfo.StartDate.Format(utils.FormatDate), varietyEdbInfo.EndDate.Format(utils.FormatDate), sysUser.AdminId, sysUser.RealName)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	// 修改指标信息
	{
		varietyEdbInfo.EdbInfoId = edbInfo.EdbInfoId
		varietyEdbInfo.EdbCode = edbInfo.EdbCode
		varietyEdbInfo.EdbName = edbInfo.EdbName
		varietyEdbInfo.ModifyTime = time.Now()
		err = varietyEdbInfo.Update([]string{"EdbInfoId", "EdbCode", "EdbName", "ModifyTime"})
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "修改指标信息失败,err:" + err.Error()
			return
		}
	}

	// 更新ETA指标库信息
	{
		data.RefreshEdbData(edbInfo.EdbInfoId, edbInfo.Source, edbInfo.EdbCode, edbInfo.StartDate)
	}

	//新增操作日志
	{
		edbLog := new(data_manage.EdbInfoLog)
		edbLog.EdbInfoId = edbInfo.EdbInfoId
		edbLog.SourceName = edbInfo.SourceName
		edbLog.Source = edbInfo.Source
		edbLog.EdbCode = edbInfo.EdbCode
		edbLog.EdbName = edbInfo.EdbName
		edbLog.ClassifyId = edbInfo.ClassifyId
		edbLog.SysUserId = sysUser.AdminId
		edbLog.SysUserRealName = sysUser.RealName
		edbLog.CreateTime = time.Now()
		edbLog.Content = string(this.Ctx.Input.RequestBody)
		edbLog.Status = "新增指标"
		edbLog.Method = this.Ctx.Input.URI()
		go data_manage.AddEdbInfoLog(edbLog)
	}

	//resp := new(data_manage.AddEdbInfoResp)
	//resp.EdbInfoId = edbInfo.EdbInfoId
	//resp.UniqueCode = edbInfo.UniqueCode
	br.Ret = 200
	br.Success = true
	br.Msg = "添加成功"
	//br.Data = resp
	br.IsAddLog = true
}

// EdbDataExport
// @Title 导出品种的指标数据
// @Description 商品价格图表分类列表接口
// @Param   VarietyId   query   int  true       "品种id"
// @Success 200 {object} response.VarietyEdbListResp
// @router /variety/data/export [get]
func (this *VarietyController) EdbDataExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	varietyId, _ := this.GetInt("VarietyId")
	if varietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}
	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(varietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}
	if varietyInfo == nil {
		br.Msg = "不存在该品种或该品种已被删除"
		br.ErrMsg = "不存在该品种或该品种已被删除"
		br.IsSendEmail = false
		return
	}

	var list []*supply_analysis.VarietyEdbInfoItem
	list, err = supply_analysis.GetAllVarietyEdbInfoByVarietyId(varietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	dataMap := make(map[int]map[time.Time]*supply_analysis.BaseFromStockPlantData)
	idList := make([]int, 0)
	for _, v := range list {
		idList = append(idList, v.VarietyEdbId)
		dataList, err := supply_analysis.GetDataVarietyEdbInfoByVarietyId(v.VarietyEdbId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取数据失败，标识：" + strconv.Itoa(v.VarietyEdbId) + ";err:" + err.Error()
			return
		}

		for _, item := range dataList {
			if dataMap[item.VarietyEdbId] == nil {
				dataMap[item.VarietyEdbId] = make(map[time.Time]*supply_analysis.BaseFromStockPlantData)
			}
			dataMap[item.VarietyEdbId][item.DataTime] = item
		}
	}

	dir, _ := os.Executable()
	exPath := filepath.Dir(dir)

	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}

	sheet, err := xlsxFile.AddSheet("存量装置")
	rowSecName := sheet.AddRow()
	celSecName := rowSecName.AddCell()
	celSecName.SetValue("指标名称")
	rowFrequency := sheet.AddRow()
	celFrequency := rowFrequency.AddCell()
	celFrequency.SetValue("频率")
	rowUnit := sheet.AddRow()
	celUnit := rowUnit.AddCell()
	celUnit.SetValue("单位")
	rowUpdateTime := sheet.AddRow()
	celUpdateTime := rowUpdateTime.AddCell()
	celUpdateTime.SetValue("更新时间")

	// 日度产量
	{
		cellSenName := rowSecName.AddCell()
		cellSenName.SetValue("日度减产量")
		celFrequency := rowFrequency.AddCell()
		celFrequency.SetValue("日度")
		celUnit := rowUnit.AddCell()
		celUnit.SetValue("万吨")
		celUpdateTime := rowUpdateTime.AddCell()
		celUpdateTime.SetValue(time.Now().Format(utils.FormatDateTime))
	}
	for _, v := range list {
		cellSenName := rowSecName.AddCell()
		cellSenName.SetValue(v.EdbName)
		celFrequency := rowFrequency.AddCell()
		celFrequency.SetValue(v.Frequency)
		celUnit := rowUnit.AddCell()
		celUnit.SetValue("万吨")
		celUpdateTime := rowUpdateTime.AddCell()
		celUpdateTime.SetValue(v.ModifyTime)
	}

	// 获取日期数据
	//dateList, err := supply_analysis.GetVarietyEdbDataList(idList)
	//if err != nil {
	//	br.Msg = "获取数据失败"
	//	br.ErrMsg = "获取数据失败,Err:" + err.Error()
	//	return
	//}
	//
	//for _, n := range dateList {
	//	rowData := sheet.AddRow()
	//	celDate := rowData.AddCell()
	//	celDate.SetValue(n.DataTime.Format(utils.FormatDate))
	//
	//	for _, varietyEdbId := range idList {
	//		celData := rowData.AddCell()
	//		if dataMap[varietyEdbId][n.DataTime] != nil {
	//			celData.SetFloat(dataMap[varietyEdbId][n.DataTime].Value)
	//		}
	//	}
	//}

	// 日度数据
	dayDataMap, startDate, lastDate, err := supply_analysisServ.CalculateByDay(varietyInfo)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取日度数据失败,Err:" + err.Error()
		return
	}
	// 最后日期的月份最后一天
	lastMonthDay := time.Date(lastDate.Year(), lastDate.Month(), 1, lastDate.Hour(), lastDate.Minute(), lastDate.Second(), lastDate.Nanosecond(), time.Local).AddDate(0, 1, -1)
	for tmpDate := lastMonthDay; !tmpDate.Before(startDate); tmpDate = tmpDate.AddDate(0, 0, -1) {
		rowData := sheet.AddRow()
		dateCelDate := rowData.AddCell()
		dateCelDate.SetValue(tmpDate.Format(utils.FormatDate))

		// 日度数据
		{
			dayCelDate := rowData.AddCell()
			if tmpVal, ok := dayDataMap[tmpDate]; ok {
				dayCelDate.SetFloat(tmpVal)
			}
		}

		// 计算出来的数据
		for _, varietyEdbId := range idList {
			celData := rowData.AddCell()
			if dataMap[varietyEdbId][tmpDate] != nil {
				celData.SetFloat(dataMap[varietyEdbId][tmpDate].Value)
			}
		}
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		//有指标无数据时先导出一遍空表
		sheet, err := xlsxFile.AddSheet("无数据")
		if err != nil {
			br.Msg = "新增Sheet失败"
			br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
			return
		}
		rowSecName := sheet.AddRow()
		celSecName := rowSecName.AddCell()
		celSecName.SetValue("")
		err = xlsxFile.Save(downLoadnFilePath)
		if err != nil {
			br.Msg = "保存文件失败"
			br.ErrMsg = "保存文件失败"
			return
		}
	}

	fileName := varietyInfo.VarietyName + time.Now().Format("06.01.02") + `.xlsx` //文件名称
	this.Ctx.Output.Download(downLoadnFilePath, fileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "success"
}

// EdbDataList
// @Title 指标数据列表接口
// @Description 指标数据列表接口
// @Param   VarietyEdbId   query   int  true       "指标id"
// @Success 200 {object} response.VarietyEdbListResp
// @router /variety/edb/data/list [get]
func (this *VarietyController) EdbDataList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	varietyEdbId, _ := this.GetInt("VarietyEdbId")
	if varietyEdbId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}

	// 根据品种指标id获取所有的数据
	list, err := supply_analysis.GetDataVarietyEdbInfoByVarietyId(varietyEdbId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}

	resp := make([]response.VarietyEdbDataListResp, 0)

	for _, v := range list {
		resp = append(resp, response.VarietyEdbDataListResp{
			DataTime: v.DataTime.Format(utils.FormatDate),
			Value:    v.Value,
		})
	}

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

// EdbInfoDataTb
// @Title 获取指标数据同比值
// @Description 获取指标数据
// @Param   EdbInfoId   query   int  true       "指标ID"
// @Param   DateType   query   int  true       "日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间,6:自定义起始时间至今，7：18年至今,8:19年至今,9:20年至今,10:全部"
// @Param   StartDate   query   string  true       "自定义开始日期"
// @Param   EndDate   query   string  true       "自定义结束日期"
// @Success 200 {object} data_manage.EdbInfoDataResp
// @router /variety/edb/data/tb [get]
func (this *VarietyController) EdbInfoDataTb() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	varietyEdbId, _ := this.GetInt("VarietyEdbId")
	if varietyEdbId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	dateType, _ := this.GetInt("DateType")
	if dateType <= 0 {
		dateType = 3
	}

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	startYear, _ := this.GetInt("StartYear")

	varietyEdbInfo, err := supply_analysis.GetVarietyEdbInfoByVarietyEdbId(varietyEdbId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}
	edbInfo := &data_manage.EdbInfo{
		EdbInfoId:        varietyEdbId,
		EdbInfoType:      0,
		SourceName:       "",
		Source:           0,
		EdbCode:          varietyEdbInfo.EdbCode,
		EdbName:          varietyEdbInfo.EdbName,
		EdbNameEn:        "",
		EdbNameSource:    "",
		Frequency:        varietyEdbInfo.Frequency,
		Unit:             ``,
		UnitEn:           "",
		StartDate:        varietyEdbInfo.StartDate.Format(utils.FormatDate),
		EndDate:          varietyEdbInfo.EndDate.Format(utils.FormatDate),
		ClassifyId:       0,
		SysUserId:        0,
		SysUserRealName:  "",
		UniqueCode:       "",
		CreateTime:       varietyEdbInfo.CreateTime,
		ModifyTime:       varietyEdbInfo.ModifyTime,
		MinValue:         0,
		MaxValue:         0,
		CalculateFormula: "",
		EdbType:          1,
		Sort:             0,
		LatestDate:       varietyEdbInfo.EndDate.Format(utils.FormatDate),
		LatestValue:      varietyEdbInfo.LatestValue,
		MoveType:         0,
		MoveFrequency:    "",
		NoUpdate:         0,
		ServerUrl:        "",
		ChartImage:       "",
		Calendar:         "",
	}

	startDate, endDate = utils.GetDateByDateTypeV2(dateType, startDate, endDate, startYear, varietyEdbInfo.EndDate.Year())

	var startDateTime time.Time
	if startDate != `` {
		startDateTime, err = time.ParseInLocation(utils.FormatDate, startDate, time.Local)
		if err != nil {
			br.Msg = "开始日期异常"
			br.Msg = "开始日期异常,Err:" + err.Error()
			return
		}
		//同比值的计算方式,是需要与去年同期对比,所以如果用户需要某个时间段的数据的话,获取基础数据时,需要往前面推(1年+兼容的日期频度(目前是35天))
		startDate = startDateTime.AddDate(-1, 0, -35).Format(utils.FormatDate)
	}

	// 根据品种指标id获取所有的数据
	tmpDataList, _, _, err := supply_analysisServ.GetCustomEdbData(varietyEdbId, startDate, endDate)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}

	// 计算同比值
	dataList, minValue, maxValue, err := data.GetEdbDataTbz(edbInfo, tmpDataList, startDateTime)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "计算同比值失败,Err:" + err.Error()
		return
	}

	edbInfo.MaxValue = maxValue
	edbInfo.MinValue = minValue

	resp := new(data_manage.EdbInfoDataResp)
	resp.EdbInfo = edbInfo
	resp.DataList = dataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbInfoDataSeasonal
// @Title 获取指标数据(季节性)
// @Description 获取指标数据
// @Param   EdbInfoId   query   int  true       "指标ID"
// @Param   DateType   query   int  true       "日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间,6:自定义起始时间至今，7：18年至今,8:19年至今,9:20年至今,10:全部"
// @Param   StartDate   query   string  true       "自定义开始日期"
// @Param   EndDate   query   string  true       "自定义结束日期"
// @Param   Calendar   query   string  true       "公历/农历"
// @Success 200 {object} data_manage.EdbInfoDataResp
// @router /variety/edb/data/seasonal [get]
func (this *VarietyController) EdbInfoDataSeasonal() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	varietyEdbId, _ := this.GetInt("VarietyEdbId")
	if varietyEdbId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	calendar := this.GetString("Calendar")

	if calendar == "" {
		calendar = "公历"
	}

	dateType, _ := this.GetInt("DateType")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	startYear, _ := this.GetInt("StartYear")

	if dateType == 0 {
		dateType = utils.DateTypeNYears
	}

	// 指标详情
	varietyEdbInfo, err := supply_analysis.GetVarietyEdbInfoByVarietyEdbId(varietyEdbId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}
	edbInfo := &data_manage.EdbInfo{
		EdbInfoId:        varietyEdbId,
		EdbInfoType:      0,
		SourceName:       "",
		Source:           0,
		EdbCode:          varietyEdbInfo.EdbCode,
		EdbName:          varietyEdbInfo.EdbName,
		EdbNameEn:        "",
		EdbNameSource:    "",
		Frequency:        varietyEdbInfo.Frequency,
		Unit:             ``,
		UnitEn:           "",
		StartDate:        varietyEdbInfo.StartDate.Format(utils.FormatDate),
		EndDate:          varietyEdbInfo.EndDate.Format(utils.FormatDate),
		ClassifyId:       0,
		SysUserId:        0,
		SysUserRealName:  "",
		UniqueCode:       "",
		CreateTime:       varietyEdbInfo.CreateTime,
		ModifyTime:       varietyEdbInfo.ModifyTime,
		MinValue:         0,
		MaxValue:         0,
		CalculateFormula: "",
		EdbType:          1,
		Sort:             0,
		LatestDate:       varietyEdbInfo.EndDate.Format(utils.FormatDate),
		LatestValue:      varietyEdbInfo.LatestValue,
		MoveType:         0,
		MoveFrequency:    "",
		NoUpdate:         0,
		ServerUrl:        "",
		ChartImage:       "",
		Calendar:         "",
	}

	startDate, endDate = utils.GetDateByDateTypeV2(dateType, startDate, endDate, startYear, varietyEdbInfo.EndDate.Year())

	dataList, minVal, maxVal, err := supply_analysisServ.GetChartEdbSeasonalData(varietyEdbId, calendar, startDate, endDate, edbInfo.LatestDate)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	edbInfo.MinValue = minVal
	edbInfo.MaxValue = maxVal
	resp := new(data_manage.EdbInfoDataSeasonalResp)
	resp.EdbInfo = edbInfo
	resp.DataList = dataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbDataListV2
// @Title 指标数据列表接口
// @Description 指标数据列表接口
// @Param   VarietyEdbId   query   int  true       "指标id"
// @Success 200 {object} response.VarietyEdbListResp
// @router /variety/edb/data/list/v2 [get]
func (this *VarietyController) EdbDataListV2() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	varietyEdbId, _ := this.GetInt("VarietyEdbId")
	if varietyEdbId <= 0 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	dateType, _ := this.GetInt("DateType")
	if dateType <= 0 {
		dateType = 3
	}

	edbInfoType, _ := this.GetInt("EdbInfoType")
	if edbInfoType < 0 {
		edbInfoType = 1
	}

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	startYear, _ := this.GetInt("StartYear")

	varietyEdbInfo, err := supply_analysis.GetVarietyEdbInfoByVarietyEdbId(varietyEdbId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}
	edbInfo := &data_manage.EdbInfo{
		EdbInfoId:        varietyEdbId,
		EdbInfoType:      0,
		SourceName:       "",
		Source:           0,
		EdbCode:          varietyEdbInfo.EdbCode,
		EdbName:          varietyEdbInfo.EdbName,
		EdbNameEn:        "",
		EdbNameSource:    "",
		Frequency:        varietyEdbInfo.Frequency,
		Unit:             ``,
		UnitEn:           "",
		StartDate:        varietyEdbInfo.StartDate.Format(utils.FormatDate),
		EndDate:          varietyEdbInfo.EndDate.Format(utils.FormatDate),
		ClassifyId:       0,
		SysUserId:        0,
		SysUserRealName:  "",
		UniqueCode:       "",
		CreateTime:       varietyEdbInfo.CreateTime,
		ModifyTime:       varietyEdbInfo.ModifyTime,
		MinValue:         0,
		MaxValue:         0,
		CalculateFormula: "",
		EdbType:          1,
		Sort:             0,
		LatestDate:       varietyEdbInfo.EndDate.Format(utils.FormatDate),
		LatestValue:      varietyEdbInfo.LatestValue,
		MoveType:         0,
		MoveFrequency:    "",
		NoUpdate:         0,
		ServerUrl:        "",
		ChartImage:       "",
		Calendar:         "",
	}

	startDate, endDate = utils.GetDateByDateTypeV2(dateType, startDate, endDate, startYear, varietyEdbInfo.EndDate.Year())

	var startDateTime time.Time
	if startDate != `` {
		startDateTime, err = time.ParseInLocation(utils.FormatDate, startDate, time.Local)
		if err != nil {
			br.Msg = "开始日期异常"
			br.Msg = "开始日期异常,Err:" + err.Error()
			return
		}
		//同比值的计算方式,是需要与去年同期对比,所以如果用户需要某个时间段的数据的话,获取基础数据时,需要往前面推(1年+兼容的日期频度(目前是35天))
		startDate = startDateTime.AddDate(-1, 0, -35).Format(utils.FormatDate)
	}

	// 根据品种指标id获取所有的数据
	dataList, minVal, maxVal, err := supply_analysisServ.GetCustomEdbData(varietyEdbId, startDate, endDate)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}
	edbInfo.MinValue = minVal
	edbInfo.MaxValue = maxVal

	resp := new(data_manage.EdbInfoDataResp)
	resp.EdbInfo = edbInfo
	resp.DataList = dataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
