package future_good

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/models/data_manage/future_good"
	"hongze/hz_crm_api/models/data_manage/future_good/request"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/data"
	future_goodServ "hongze/hz_crm_api/services/data/future_good"
	"hongze/hz_crm_api/utils"
	"os"
	"os/exec"
	"sort"
	"strconv"
	"strings"
	"time"
)

// FutureGoodChartInfoController 商品价格图表管理
type FutureGoodChartInfoController struct {
	controllers.BaseAuthController
}

// ChartList
// @Title 商品价格图表列表接口
// @Description 商品价格图表列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ChartClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Success 200 {object} data_manage.ChartListResp
// @router /chart_info/list [get]
func (this *FutureGoodChartInfoController) ChartList() {
	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
	}

	chartClassifyId, _ := this.GetInt("ChartClassifyId")

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

	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{}

	// 商品价格曲线，商品利润曲线
	condition += ` AND source in (?,?) `
	pars = append(pars, utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT)

	if chartClassifyId > 0 {
		chartClassifyId, err := data_manage.GetChartClassify(chartClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取图表信息失败"
			br.ErrMsg = "获取信息失败,GetChartClassify,Err:" + err.Error()
			return
		}
		condition += " AND chart_classify_id IN(" + chartClassifyId + ") "
		//pars = append(pars, chartClassifyId)
	}
	if keyword != "" {
		condition += ` AND  ( chart_name LIKE '%` + keyword + `%' )`
	}

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	if isShowMe {
		condition += ` AND sys_user_id = ? `
		pars = append(pars, sysUser.AdminId)
	}

	// 获取当前账号的不可见指标
	noPermissionChartIdList := make([]int, 0)
	{
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllChartListByAdminId(this.SysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败，Err:" + err.Error()
			return
		}
		for _, v := range confList {
			noPermissionChartIdList = append(noPermissionChartIdList, v.ChartInfoId)
		}
	}

	lenNoPermissionChartIdList := len(noPermissionChartIdList)
	if lenNoPermissionChartIdList > 0 {
		condition += ` AND chart_info_id not in (` + utils.GetOrmInReplace(lenNoPermissionChartIdList) + `) `
		pars = append(pars, noPermissionChartIdList)
	}

	//获取图表信息
	list, err := data_manage.GetChartListByCondition(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	myChartList, err := data_manage.GetMyChartListByAdminId(sysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取我的图表信息失败,Err:" + err.Error()
		return
	}
	myChartMap := make(map[int]*data_manage.MyChartView)
	for _, v := range myChartList {
		myChartMap[v.ChartInfoId] = v
	}
	listLen := len(list)
	chartEdbMap := make(map[int][]*data_manage.ChartEdbInfoMapping)
	if listLen > 0 {
		chartInfoIds := ""
		for _, v := range list {
			chartInfoIds += strconv.Itoa(v.ChartInfoId) + ","
		}
		if chartInfoIds != "" {
			chartInfoIds = strings.Trim(chartInfoIds, ",")
			//判断是否需要展示英文标识
			edbList, e := data_manage.GetChartEdbMappingListByChartInfoIds(chartInfoIds)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + e.Error()
				return
			}
			for _, v := range edbList {
				chartEdbMap[v.ChartInfoId] = append(chartEdbMap[v.ChartInfoId], v)
			}
		}
	}
	for i := 0; i < listLen; i++ {
		//判断是否需要展示英文标识
		if edbTmpList, ok := chartEdbMap[list[i].ChartInfoId]; ok {
			list[i].IsEnChart = data.CheckIsEnChart(list[i].ChartNameEn, edbTmpList, list[i].Source, list[i].ChartType)
		}

		if existItem, ok := myChartMap[list[i].ChartInfoId]; ok {
			list[i].IsAdd = true
			list[i].MyChartId = existItem.MyChartId
			list[i].MyChartClassifyId = existItem.MyChartClassifyId
		}
	}

	resp := new(data_manage.ChartListResp)
	if list == nil || len(list) <= 0 || (err != nil && err.Error() == utils.ErrNoRow()) {
		items := make([]*data_manage.ChartInfoView, 0)
		resp.Paging = page
		resp.List = items
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	dataCount, err := data_manage.GetChartListCountByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, dataCount)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ChartInfoSave
// @Title 保存图表接口
// @Description 保存图表接口
// @Param	request	body data_manage.SaveChartInfoReq true "type json string"
// @Success Ret=200 返回图表id
// @router /chart_info/save [post]
func (this *FutureGoodChartInfoController) ChartInfoSave() {
	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 data_manage.SaveChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartInfoId <= 0 {
		br.Msg = "参数错误！"
		return
	}

	chartItem, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，请刷新页面！"
			br.ErrMsg = "图表已被删除，请刷新页面，ChartInfoId:" + strconv.Itoa(req.ChartInfoId)
			return
		}
		br.Msg = "获取图表信息失败！"
		br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
		return
	}

	if !utils.InArrayByInt([]int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, chartItem.Source) {
		br.Msg = "该图不是商品价格/利润曲线图！"
		br.IsSendEmail = false
		return
	}
	//数据更新
	chartItem.LeftMin = req.LeftMin
	chartItem.LeftMax = req.LeftMax
	err = chartItem.Update([]string{"LeftMin", "LeftMax"})
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	key := utils.HZ_CHART_LIB_DETAIL + chartItem.UniqueCode
	if utils.Re == nil && utils.Rc != nil {
		utils.Rc.Delete(key)
	}

	//修改es数据
	go data.EsAddOrEditChartInfo(chartItem.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "修改商品价格图表配置项"
		chartLog.Method = this.Ctx.Input.URI()
		go data_manage.AddChartInfoLog(chartLog)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.IsAddLog = true
}

// ChartInfoAdd
// @Title 新增图表接口
// @Description 新增图表接口
// @Param	request	body data_manage.AddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /chart_info/add [post]
func (this *FutureGoodChartInfoController) ChartInfoAdd() {
	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
	}
	deleteCache := true
	cacheKey := "CACHE_CHART_INFO_ADD_" + strconv.Itoa(sysUser.AdminId)
	defer func() {
		if deleteCache {
			utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	var req data_manage.AddChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ChartName = strings.Trim(req.ChartName, " ")
	if req.ChartName == "" {
		br.Msg = "请填写图表名称！"
		return
	}

	if req.ChartClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		return
	}

	chartClassify, err := data_manage.GetChartClassifyById(req.ChartClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if chartClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		return
	}

	//日期的配置信息
	barChartConfReq := req.BarChartInfo
	if len(barChartConfReq.DateList) <= 0 {
		br.Msg = "请选择日期"
		br.IsSendEmail = false
		return
	}
	if len(barChartConfReq.EdbInfoIdList) < 2 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	barChartConfByte, err := json.Marshal(barChartConfReq)
	if err != nil {
		br.Msg = "商品价格曲线图信息异常"
		br.ErrMsg = "商品价格曲线图信息异常,Err:" + err.Error()
		return
	}
	barChartConf := string(barChartConfByte)

	var edbInfoIdArr []int
	//edbList := make([]*data_manage.EdbInfo, 0)
	for _, v := range barChartConfReq.EdbInfoIdList {
		edbInfoId := v.EdbInfoId
		if v.Source == utils.CHART_SOURCE_DEFAULT { //ETA指标
			edbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "指标不存在！"
					br.ErrMsg = "指标不存在，edbInfoId:" + strconv.Itoa(edbInfoId)
					return
				} else {
					br.Msg = "获取指标信息失败！"
					br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
					return
				}
			}

			if edbInfo == nil {
				br.Msg = "指标已被删除，请重新选择！"
				br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
				return
			} else {
				if edbInfo.EdbInfoId <= 0 {
					br.Msg = "指标已被删除，请重新选择！"
					br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
					return
				}
			}

			edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
			edbInfo.EdbNameSource = edbInfo.EdbName
		} else { // 商品指标
			edbInfo, err := future_good.GetFutureGoodEdbInfo(edbInfoId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "指标不存在！"
					br.ErrMsg = "指标不存在，edbInfoId:" + strconv.Itoa(edbInfoId)
					return
				} else {
					br.Msg = "获取指标信息失败！"
					br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
					return
				}
			}

			if edbInfo == nil {
				br.Msg = "指标已被删除，请重新选择！"
				br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
				return
			} else {
				if edbInfo.FutureGoodEdbInfoId <= 0 {
					br.Msg = "指标已被删除，请重新选择！"
					br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
					return
				}
			}
			edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
		}
	}

	sort.Ints(edbInfoIdArr)
	var edbInfoIdArrStr []string
	for _, v := range edbInfoIdArr {
		edbInfoIdArrStr = append(edbInfoIdArrStr, strconv.Itoa(v))
	}
	edbInfoIdStr := strings.Join(edbInfoIdArrStr, ",")
	var chartInfoId int

	//判断图表是否存在 （需求池356 研报管理后台-商品价格曲线，允许图表名称重复命名； 更改时间：2023-3-7 14:21:35）
	//var condition string
	//var pars []interface{}
	//condition += " AND chart_name=? AND source = ? "
	//pars = append(pars, req.ChartName, utils.CHART_SOURCE_FUTURE_GOOD)
	//count, err := data_manage.GetChartInfoCountByCondition(condition, pars)
	//if err != nil {
	//	br.Msg = "判断图表名称是否存在失败"
	//	br.ErrMsg = "判断图表名称是否存在失败,Err:" + err.Error()
	//	return
	//}
	//if count > 0 {
	//	br.Msg = "图表已存在，请重新填写"
	//	br.IsSendEmail = false
	//	return
	//}

	disableVal := data.CheckIsDisableChart(edbInfoIdArr)

	chartInfo := new(data_manage.ChartInfo)
	chartInfo.ChartName = req.ChartName
	chartInfo.EdbInfoIds = edbInfoIdStr
	chartInfo.ChartClassifyId = req.ChartClassifyId
	chartInfo.SysUserId = sysUser.AdminId
	chartInfo.SysUserRealName = sysUser.RealName
	chartInfo.CreateTime = time.Now()
	chartInfo.ModifyTime = time.Now()
	chartInfo.IsSetName = 0
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	chartInfo.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp)
	if req.DateType > 0 {
		chartInfo.DateType = req.DateType
	} else {
		chartInfo.DateType = 3
	}
	if req.ChartType == 0 {
		req.ChartType = 1
	}
	chartInfo.ChartType = req.ChartType
	if req.Calendar == "" {
		chartInfo.Calendar = "公历"
	} else {
		chartInfo.Calendar = req.Calendar
	}
	chartInfo.StartDate = req.StartDate
	chartInfo.EndDate = req.EndDate
	chartInfo.SeasonStartDate = req.SeasonStartDate
	chartInfo.SeasonEndDate = req.SeasonEndDate
	chartInfo.LeftMin = req.LeftMin
	chartInfo.LeftMax = req.LeftMax
	chartInfo.RightMin = req.RightMin
	chartInfo.RightMax = req.RightMax
	chartInfo.Disabled = disableVal
	chartInfo.BarConfig = barChartConf
	chartInfo.Source = utils.CHART_SOURCE_FUTURE_GOOD
	newId, err := data_manage.AddChartInfo(chartInfo)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}
	mapList := make([]*data_manage.ChartEdbMapping, 0)
	for _, v := range barChartConfReq.EdbInfoIdList {
		mapItem := new(data_manage.ChartEdbMapping)
		mapItem.ChartInfoId = int(newId)
		mapItem.EdbInfoId = v.EdbInfoId
		mapItem.CreateTime = time.Now()
		mapItem.ModifyTime = time.Now()
		timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
		mapItem.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp + "_" + strconv.Itoa(v.EdbInfoId))
		//mapItem.MaxData = v.MaxData
		//mapItem.MinData = v.MinData
		mapItem.IsOrder = true
		mapItem.IsAxis = 1
		mapItem.EdbInfoType = 1
		//mapItem.LeadValue = v.LeadValue
		//mapItem.LeadUnit = v.LeadUnit
		//mapItem.ChartStyle = v.ChartStyle
		//mapItem.ChartColor = v.ChartColor
		//mapItem.PredictChartColor = v.PredictChartColor
		//mapItem.ChartWidth = v.ChartWidth
		mapItem.Source = v.Source
		mapList = append(mapList, mapItem)
	}
	err = data_manage.AddChartEdbMapping(mapList)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}
	chartInfoId = int(newId)
	resp := new(data_manage.AddChartInfoResp)
	resp.ChartInfoId = chartInfoId
	resp.UniqueCode = chartInfo.UniqueCode
	resp.ChartType = req.ChartType

	//添加es数据
	go data.EsAddOrEditChartInfo(chartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartInfoId = chartInfoId
		chartLog.ChartName = req.ChartName
		chartLog.ChartClassifyId = req.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartInfo.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "新增商品价格图表"
		chartLog.Method = this.Ctx.Input.URI()
		go data_manage.AddChartInfoLog(chartLog)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
	br.IsAddLog = true
}

// ChartInfoEdit
// @Title 编辑图表接口
// @Description 编辑图表接口
// @Param	request	body data_manage.EditChartInfoReq true "type json string"
// @Success Ret=200 保存成功
// @router /chart_info/edit [post]
func (this *FutureGoodChartInfoController) ChartInfoEdit() {
	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 data_manage.EditChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ChartName = strings.Trim(req.ChartName, " ")
	if req.ChartClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		return
	}

	chartClassify, err := data_manage.GetChartClassifyById(req.ChartClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if chartClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		return
	}
	chartItem, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，请刷新页面"
			br.ErrMsg = "图表已被删除，请刷新页面"
			return
		}
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	if chartItem.Source != utils.CHART_SOURCE_FUTURE_GOOD {
		br.Msg = "该图不是商品价格曲线图！"
		br.IsSendEmail = false
		return
	}

	//图表操作权限
	ok := data.CheckOpChartPermission(sysUser, chartItem.SysUserId)
	if !ok {
		br.Msg = "没有该图表的操作权限"
		br.ErrMsg = "没有该图表的操作权限"
		return
	}

	var calendar string
	var dateType int
	dateType = req.DateType
	if req.ChartType != chartItem.ChartType {
		if chartItem.ChartType != 2 && chartItem.Calendar == "" { //非季节性图
			calendar = "公历"
		}
		if chartItem.ChartType == 2 && chartItem.DateType <= 0 {
			dateType = 3
		}
	}

	//商品价格曲线图的配置信息
	barChartConfReq := req.BarChartInfo
	if len(barChartConfReq.DateList) <= 0 {
		br.Msg = "请选择日期"
		br.IsSendEmail = false
		return
	}
	if len(barChartConfReq.EdbInfoIdList) < 2 {
		br.Msg = "请选择指标"
		br.IsSendEmail = false
		return
	}
	barChartConfByte, err := json.Marshal(barChartConfReq)
	if err != nil {
		br.Msg = "商品价格曲线图信息异常"
		br.ErrMsg = "商品价格曲线图信息异常,Err:" + err.Error()
		return
	}
	barChartConf := string(barChartConfByte)

	var edbInfoIdArr []int
	for _, v := range barChartConfReq.EdbInfoIdList {
		edbInfoId := v.EdbInfoId
		if v.Source == utils.CHART_SOURCE_DEFAULT { //ETA指标
			edbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "图表不存在！"
					br.ErrMsg = "图表指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
					return
				} else {
					br.Msg = "获取图表信息失败！"
					br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
					return
				}
			}

			if edbInfo == nil {
				br.Msg = "指标不存在！"
				br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
				return
			}
			edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
		} else { //商品指标
			edbInfo, err := future_good.GetFutureGoodEdbInfo(edbInfoId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "指标不存在！"
					br.ErrMsg = "指标不存在，edbInfoId:" + strconv.Itoa(edbInfoId)
					return
				} else {
					br.Msg = "获取指标信息失败！"
					br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
					return
				}
			}

			if edbInfo == nil {
				br.Msg = "指标已被删除，请重新选择！"
				br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
				return
			} else {
				if edbInfo.FutureGoodEdbInfoId <= 0 {
					br.Msg = "指标已被删除，请重新选择！"
					br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoId)
					return
				}
			}
			edbInfoIdArr = append(edbInfoIdArr, edbInfoId)
		}

	}

	sort.Ints(edbInfoIdArr)
	var edbInfoIdArrStr []string
	for _, v := range edbInfoIdArr {
		edbInfoIdArrStr = append(edbInfoIdArrStr, strconv.Itoa(v))
	}
	edbInfoIdStr := strings.Join(edbInfoIdArrStr, ",")

	// 图表启用与否
	disableVal := data.CheckIsDisableChart(edbInfoIdArr)

	err = data_manage.EditFutureGoodChartInfoAndMapping(&req, edbInfoIdStr, calendar, dateType, disableVal, barChartConf)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	resp := new(data_manage.AddChartInfoResp)
	resp.ChartInfoId = chartItem.ChartInfoId
	resp.UniqueCode = chartItem.UniqueCode
	resp.ChartType = req.ChartType

	//添加es数据
	go data.EsAddOrEditChartInfo(chartItem.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "编辑商品价格图表"
		chartLog.Method = this.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
	br.IsAddLog = true
}

// ChartEnInfoEdit
// @Title 编辑图表英文信息接口
// @Description 编辑图表英文信息接口
// @Param	request	body data_manage.EditChartEnInfoReq true "type json string"
// @Success Ret=200 编辑成功
// @router /chart_info/en/edit [post]
func (this *FutureGoodChartInfoController) ChartEnInfoEdit() {
	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.EditChartEnInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ChartNameEn = strings.Trim(req.ChartNameEn, " ")

	if req.ChartInfoId <= 0 {
		br.Msg = "请选择图表"
		return
	}

	chartItem, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，请刷新页面"
			br.ErrMsg = "图表已被删除，请刷新页面"
			return
		}
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	if !utils.InArrayByInt([]int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, chartItem.Source) {
		br.Msg = "该图不是商品价格/利润曲线图！"
		br.IsSendEmail = false
		return
	}

	//图表操作权限
	//ok := data.CheckOpChartPermission(sysUser, chartItem.SysUserId)
	//if !ok {
	//	br.Msg = "没有该图表的操作权限"
	//	br.ErrMsg = "没有该图表的操作权限"
	//	return
	//}

	edbInfoMapping, err := data_manage.GetEtaEdbChartEdbMapping(chartItem.ChartInfoId)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "获取图表现货价格指标信息失败，指标信息失败，Err:" + err.Error()
		return
	}

	//校验指标信息是否存在
	edbInfo, err := data_manage.GetEdbInfoById(edbInfoMapping.EdbInfoId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表不存在！"
			br.ErrMsg = "图表指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoMapping.EdbInfoId)
			return
		} else {
			br.Msg = "获取图表信息失败！"
			br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
			return
		}
	}
	if edbInfo == nil {
		br.Msg = "指标不存在！"
		br.ErrMsg = "指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoMapping.EdbInfoId)
		return
	}

	if req.ChartNameEn != "" {
		var condition string
		var pars []interface{}
		condition += " AND chart_info_id<>? "
		pars = append(pars, req.ChartInfoId)

		/*condition += " AND chart_classify_id=? "
		pars = append(pars, chartItem.ChartClassifyId)*/

		condition += " AND chart_name_en=? "
		pars = append(pars, req.ChartNameEn)

		existItem, err := data_manage.GetChartInfoByCondition(condition, pars)
		if err != nil {
			if err.Error() != utils.ErrNoRow() {
				br.Msg = "判断英文图表名称是否存在失败"
				br.ErrMsg = "判断英文图表名称是否存在失败,Err:" + err.Error()
				return
			}
		}

		if err == nil && existItem.ChartInfoId > 0 {
			br.Msg = existItem.ChartName + "：" + req.ChartNameEn + "图表名称已存在"
			return
		}
	}

	switch chartItem.Source {
	case utils.CHART_SOURCE_FUTURE_GOOD:
		err = data_manage.EditFutureGoodChartEnInfoAndEdbEnInfo(req.ChartInfoId, req.ChartNameEn, edbInfo.EdbInfoId, req.EdbNameEn, req.UnitEn)
		if req.FutureGoodNameEn != `` {
			futureGoodEdbInfoMapping, err := data_manage.GetFutureGoodEdbChartEdbMapping(chartItem.ChartInfoId)
			if err != nil {
				br.Msg = "修改失败"
				br.ErrMsg = "获取图表现货价格指标信息失败，指标信息失败，Err:" + err.Error()
				return
			}
			futureGoodEdbInfo, err := future_good.GetFutureGoodEdbInfo(futureGoodEdbInfoMapping.EdbInfoId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "图表不存在！"
					br.ErrMsg = "图表指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoMapping.EdbInfoId)
					return
				} else {
					br.Msg = "获取图表信息失败！"
					br.ErrMsg = "获取图表的指标信息失败，Err:" + err.Error()
					return
				}
			}
			if futureGoodEdbInfo == nil {
				br.Msg = "期货商品指标不存在！"
				br.ErrMsg = "期货商品指标不存在，ChartInfoId:" + strconv.Itoa(edbInfoMapping.EdbInfoId)
				return
			}

			list, _ := future_good.GetFutureGoodEdbInfoListByParentId(futureGoodEdbInfo.FutureGoodEdbInfoId)
			for _, v := range list {
				if v.FutureGoodEdbNameEn == `` {
					v.FutureGoodEdbNameEn = strings.TrimPrefix(req.FutureGoodNameEn, " ")
					v.FutureGoodEdbNameEn = strings.TrimSuffix(req.FutureGoodNameEn, " ")
				} else {
					v.FutureGoodEdbNameEn = strings.TrimPrefix(strings.Replace(v.FutureGoodEdbNameEn, v.FutureGoodEdbNameEn, req.FutureGoodNameEn, -1), " ")
					v.FutureGoodEdbNameEn = strings.TrimSuffix(req.FutureGoodNameEn, " ")
				}
				v.Update([]string{"FutureGoodEdbNameEn"})
			}
		}
	case utils.CHART_SOURCE_FUTURE_GOOD_PROFIT:
		err = data_manage.EditFutureGoodProfitChartEnInfoAndEdbEnInfo(req.ChartInfoId, req.ChartNameEn, edbInfo.EdbInfoId, req.EdbNameEn, req.UnitEn, req.ProfitNameEn)
	default:
		br.Msg = "错误的图表类型"
		br.ErrMsg = "错误的图表类型"
		br.IsSendEmail = false
		return
	}

	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	//添加es数据
	go data.EsAddOrEditChartInfo(chartItem.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)

	//指标 修改es信息
	go data.AddOrEditEdbInfoToEs(edbInfo.EdbInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "编辑商品价格图表英文信息"
		chartLog.Method = this.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}
	//清除缓存
	if utils.Re == nil && utils.Rc != nil {
		utils.Rc.Delete(utils.HZ_CHART_LIB_DETAIL + chartItem.UniqueCode) //图表分享链接缓存
		utils.Rc.Delete(data.GetChartInfoDataKey(req.ChartInfoId))
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// ChartInfoNewest
// @Title 获取最新图表接口
// @Description 获取最新图表接口
// @Success 200 {object} data_manage.ChartInfoList
// @router /chart_info/newest [get]
func (this *FutureGoodChartInfoController) ChartInfoNewest() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	item, err := data_manage.GetChartInfoByNewest(2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取最新图表失败"
		br.ErrMsg = "获取最新图表失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = item
}

// ChartInfoMove
// @Title 移动图表接口
// @Description 移动图表接口
// @Success 200 {object} data_manage.MoveChartInfoReq
// @router /chart_info/move [post]
func (this *FutureGoodChartInfoController) ChartInfoMove() {
	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 data_manage.MoveChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartInfoId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "图表id小于等于0"
		return
	}

	if req.ChartClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}
	//判断分类是否存在
	count, _ := data_manage.GetChartClassifyCountById(req.ChartClassifyId)
	if count <= 0 {
		br.Msg = "分类已被删除，不可移动，请刷新页面"
		return
	}

	chartInfo, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	if !utils.InArrayByInt([]int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, chartInfo.Source) {
		br.Msg = "该图不是商品价格/利润曲线图！"
		br.IsSendEmail = false
		return
	}

	//如果改变了分类，那么移动该图表数据
	if chartInfo.ChartClassifyId != req.ChartClassifyId {
		//查询需要修改的分类下是否存在同一个图表名称
		tmpChartInfo, tmpErr := data_manage.GetChartInfoByClassifyIdAndName(req.ChartClassifyId, chartInfo.ChartName)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "移动失败,Err:" + tmpErr.Error()
			return
		}
		if tmpChartInfo != nil {
			br.Msg = "移动失败，同一个分类下图表名称不允许重复"
			br.ErrMsg = "移动失败，同一个分类下图表名称不允许重复"
			return
		}
		err = data_manage.MoveChartInfo(req.ChartInfoId, req.ChartClassifyId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "移动失败,Err:" + err.Error()
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	//如果有传入 上一个兄弟节点分类id
	if req.PrevChartInfoId > 0 {
		prevChartInfo, err := data_manage.GetChartInfoById(req.PrevChartInfoId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取上一个兄弟节点分类信息失败,Err:" + err.Error()
			return
		}

		//如果是移动在两个兄弟节点之间
		if req.NextChartInfoId > 0 {
			//下一个兄弟节点
			nextChartInfo, err := data_manage.GetChartInfoById(req.NextChartInfoId)
			if err != nil {
				br.Msg = "移动失败"
				br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
				return
			}
			//如果上一个兄弟与下一个兄弟的排序权重是一致的，那么需要将下一个兄弟（以及下个兄弟的同样排序权重）的排序权重+2，自己变成上一个兄弟的排序权重+1
			if prevChartInfo.Sort == nextChartInfo.Sort || prevChartInfo.Sort == chartInfo.Sort {
				//变更兄弟节点的排序
				updateSortStr := `sort + 2`
				_ = data_manage.UpdateChartInfoSortByClassifyId(prevChartInfo.ChartClassifyId, prevChartInfo.Sort, prevChartInfo.ChartInfoId, []int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, updateSortStr)
			} else {
				//如果下一个兄弟的排序权重正好是上个兄弟节点的下一层，那么需要再加一层了
				if nextChartInfo.Sort-prevChartInfo.Sort == 1 {
					//变更兄弟节点的排序
					updateSortStr := `sort + 1`
					_ = data_manage.UpdateChartInfoSortByClassifyId(prevChartInfo.ChartClassifyId, prevChartInfo.Sort, prevChartInfo.ChartInfoId, []int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, updateSortStr)
				}
			}
		}

		chartInfo.Sort = prevChartInfo.Sort + 1
		chartInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")

	} else {
		firstClassify, err := data_manage.GetFirstChartInfoByClassifyId(req.ChartClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + err.Error()
			return
		}

		//如果该分类下存在其他分类，且第一个其他分类的排序等于0，那么需要调整排序
		if firstClassify != nil && firstClassify.Sort == 0 {
			updateSortStr := ` sort + 1 `
			_ = data_manage.UpdateChartInfoSortByClassifyId(firstClassify.ChartClassifyId, 0, firstClassify.ChartInfoId-1, []int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, updateSortStr)
		}

		chartInfo.Sort = 0 //那就是排在第一位
		chartInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	}

	//更新
	if len(updateCol) > 0 {
		err = chartInfo.Update(updateCol)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "修改失败,Err:" + err.Error()
			return
		}
	}

	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "修改失败,Err:" + err.Error()
		return
	}

	//添加es数据
	go data.EsAddOrEditChartInfo(req.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(req.ChartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartInfo.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartInfo.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartInfo.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "移动商品价格图表"
		chartLog.Method = this.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// ChartInfoDetail
// @Title 获取图表详情
// @Description 获取图表详情接口
// @Param   ChartInfoId   query   int  true       "图表id"
// @Param   DateType   query   int  true       "日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间"
// @Param   StartDate   query   string  true       "自定义开始日期"
// @Param   EndDate   query   string  true       "自定义结束日期"
// @Param   Calendar   query   string  true       "公历/农历"
// @Param   SeasonStartDate   query   string  true       "季节性图开始日期"
// @Param   SeasonEndDate   query   string  true       "季节性图结束日期"
// @Param   EdbInfoId   query   string  true       "指标ID，多个用英文逗号隔开"
// @Param   ChartType   query   int  true       "生成样式:1:曲线图,2:季节性图"
// @Success 200 {object} data_manage.ChartInfoDetailResp
// @router /chart_info/detail [get]
func (this *FutureGoodChartInfoController) ChartInfoDetail() {
	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
	}
	chartInfoId, _ := this.GetInt("ChartInfoId")

	dateType, _ := this.GetInt("DateType")
	if dateType <= 0 {
		dateType = 3
	}

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	seasonStartDate := this.GetString("SeasonStartDate")
	seasonEndDate := this.GetString("SeasonEndDate")

	chartType, _ := this.GetInt("ChartType")

	calendar := this.GetString("Calendar")
	if calendar == "" {
		calendar = "公历"
	}
	switch dateType {
	case 1:
		startDate = "2000-01-01"
	case 2:
		startDate = "2010-01-01"
	case 3:
		startDate = "2015-01-01"
	case 4:
		//startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
		startDate = "2021-01-01"
	case 5:
		startDate = startDate + "-01"
		endDate = endDate + "-01"
	case 6:
		startDate = startDate + "-01"
	case 7:
		startDate = "2018-01-01"
	case 8:
		startDate = "2019-01-01"
	case 9:
		startDate = "2020-01-01"
	case 11:
		startDate = "2022-01-01"
	}

	var err error
	chartInfo := new(data_manage.ChartInfoView)
	if chartInfoId > 0 {
		chartInfo, err = data_manage.GetChartInfoViewById(chartInfoId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "图被删除，请刷新页面"
				br.ErrMsg = "图被删除，请刷新页面，Err:" + err.Error()
				return
			}
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
			return
		}
		chartType = chartInfo.ChartType
	}

	if chartType == 2 {
		if seasonStartDate != "" {
			startDate = seasonStartDate + "-01-01"
		} else {
			fivePre := time.Now().AddDate(-4, 0, 0).Year()
			startDate = strconv.Itoa(fivePre) + "-01-01"
		}
		if seasonEndDate != "" {
			endDate = seasonEndDate + "-12-31"
		} else {
			endDate = "" //time.Now().AddDate(2, 0, 0).Format(utils.FormatDate)
		}
	}

	switch chartInfo.Source {
	case utils.CHART_SOURCE_FUTURE_GOOD:
		getFutureGoodChartInfo(chartInfo, startDate, endDate, sysUser, br)
		return
	case utils.CHART_SOURCE_FUTURE_GOOD_PROFIT:
		getFutureGoodProfitChartInfo(chartInfo, sysUser, br)
		return
	}
}

// getFutureGoodChartInfo 获取商品价格曲线的数据
func getFutureGoodChartInfo(chartInfo *data_manage.ChartInfoView, startDate, endDate string, sysUser *system.Admin, br *models.BaseResponse) {
	chartInfoId := chartInfo.ChartInfoId

	var edbInfoMapping, futureGoodEdbInfoMapping *data_manage.ChartEdbInfoMapping
	edbInfoMapping, err := data_manage.GetEtaEdbChartEdbMapping(chartInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	futureGoodEdbInfoMapping, err = data_manage.GetFutureGoodEdbChartEdbMapping(chartInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}

	if edbInfoMapping == nil {
		br.Msg = "请选择ETA指标"
		br.ErrMsg = "请选择ETA指标"
		br.IsSendEmail = false
		return
	}
	if futureGoodEdbInfoMapping == nil {
		br.Msg = "请选择商品指标"
		br.ErrMsg = "请选择商品指标"
		br.IsSendEmail = false
		return
	}

	// 商品价格曲线图的一些配置
	var barConfig data_manage.BarChartInfoReq
	barChartInfoDateList := make([]data_manage.BarChartInfoDateReq, 0)
	barChartInfoSort := data_manage.BarChartInfoSortReq{}

	if chartInfo.BarConfig == `` {
		br.Msg = "商品价格曲线图未配置"
		br.ErrMsg = "商品价格曲线图未配置"
		return
	}
	err = json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
	if err != nil {
		br.Msg = "商品价格曲线图配置异常"
		br.ErrMsg = "商品价格曲线图配置异常"
		return
	}

	barChartInfoDateList = barConfig.DateList
	barChartInfoSort = barConfig.Sort

	// 获取图表中的指标数据
	barConfigEdbInfoIdList, edbList, xEdbIdValue, xDataList, yDataList, err := future_goodServ.GetChartEdbData(chartInfoId, startDate, endDate, edbInfoMapping, futureGoodEdbInfoMapping, barChartInfoDateList, barChartInfoSort)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	warnEdbList := make([]string, 0)
	if len(edbList) <= 0 {
		br.Msg = "商品价格曲线图表指标异常"
		br.ErrMsg = "商品价格曲线图表异常"
		return
	}
	baseEdbInfo := edbList[0] //现货指标

	for _, v := range edbList {
		if v.IsNullData {
			warnEdbList = append(warnEdbList, v.EdbName+"("+v.EdbCode+")")
		}
		// 指标别名
		if barConfigEdbInfoIdList != nil && len(barConfigEdbInfoIdList) > 0 {
			for _, reqEdb := range barConfigEdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
					v.EdbAliasNameEn = reqEdb.NameEn
				}
			}
		}
	}
	if len(warnEdbList) > 0 {
		chartInfo.WarnMsg = `图表引用指标异常，异常指标：` + strings.Join(warnEdbList, "，")
	}
	if chartInfoId > 0 && chartInfo != nil {
		//判断是否加入我的图库
		{
			var myChartCondition string
			var myChartPars []interface{}
			myChartCondition += ` AND a.admin_id=? `
			myChartPars = append(myChartPars, sysUser.AdminId)
			myChartCondition += ` AND a.chart_info_id=? `
			myChartPars = append(myChartPars, chartInfo.ChartInfoId)

			myChartList, err := data_manage.GetMyChartByCondition(myChartCondition, myChartPars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取我的图表信息失败，GetMyChartByCondition，Err:" + err.Error()
				return
			}
			if myChartList != nil && len(myChartList) > 0 {
				chartInfo.IsAdd = true
				chartInfo.MyChartId = myChartList[0].MyChartId
				chartInfo.MyChartClassifyId = myChartList[0].MyChartClassifyId
			}
		}
	}

	//图表操作权限
	chartInfo.IsEdit = data.CheckOpChartPermission(sysUser, chartInfo.SysUserId)
	chartInfo.Button.IsEdit = chartInfo.IsEdit
	chartInfo.Button.IsCopy = true
	//判断是否需要展示英文标识
	chartInfo.IsEnChart = data.CheckIsEnChart(chartInfo.ChartNameEn, edbList[0:1], chartInfo.Source, chartInfo.ChartType)
	chartInfo.UnitEn = baseEdbInfo.UnitEn

	resp := new(data_manage.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.XDataList = xDataList
	resp.BarChartInfo = barConfig
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ChartInfoDetailFromUniqueCode
// @Title 根据编码获取图表详情
// @Description 根据编码获取图表详情接口
// @Param   UniqueCode   query   int  true       "图表唯一编码,如果是管理后台访问，传固定字符串:7c69b590249049942070ae9dcd5bf6dc"
// @Param   IsCache   query   bool  true       "是否走缓存，默认false"
// @Success 200 {object} data_manage.ChartInfoDetailFromUniqueCodeResp
// @router /chart_info/detail/from_unique_code [get]
func (this *FutureGoodChartInfoController) ChartInfoDetailFromUniqueCode() {
	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
	}
	uniqueCode := this.GetString("UniqueCode")
	if uniqueCode == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,uniqueCode is empty"
		return
	}

	//是否走缓存
	isCache, _ := this.GetBool("IsCache")

	status := true
	chartInfo, err := data_manage.GetChartInfoViewByUniqueCode(uniqueCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			status = false
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
			return
		}
	}

	if chartInfo == nil {
		status = false
	}

	if !status {
		resp := new(data_manage.ChartInfoDetailFromUniqueCodeResp)
		endInfoList := make([]*data_manage.ChartEdbInfoMapping, 0)
		resp.EdbInfoList = endInfoList
		resp.ChartInfo = chartInfo
		resp.Status = false
		return
	}

	resp, isOk, msg, errMsg := GetChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
	if !isOk {
		br.Msg = msg
		br.ErrMsg = errMsg
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetChartInfoDetailFromUniqueCode 根据编码获取图表详情
func GetChartInfoDetailFromUniqueCode(chartInfo *data_manage.ChartInfoView, isCache bool, sysUser *system.Admin) (resp *data_manage.ChartInfoDetailFromUniqueCodeResp, isOk bool, msg, errMsg string) {
	resp = new(data_manage.ChartInfoDetailFromUniqueCodeResp)

	adminId := sysUser.AdminId

	//判断是否存在缓存，如果存在缓存，那么直接从缓存中获取
	key := data.GetChartInfoDataKey(chartInfo.ChartInfoId)
	if utils.Re == nil && isCache {
		if utils.Re == nil && utils.Rc.IsExist(key) {
			if chartData, err1 := utils.Rc.RedisBytes(key); err1 == nil {
				err := json.Unmarshal(chartData, &resp)
				if err == nil && resp != nil {
					// 这里跟当前用户相关的信息重新查询写入resp, 不使用缓存中的
					var myCond string
					var myPars []interface{}
					myCond += ` AND a.admin_id=? `
					myPars = append(myPars, adminId)
					myCond += ` AND a.chart_info_id=? `
					myPars = append(myPars, chartInfo.ChartInfoId)
					myList, err := data_manage.GetMyChartByCondition(myCond, myPars)
					if err != nil && err.Error() != utils.ErrNoRow() {
						msg = "获取失败"
						errMsg = "获取我的图表信息失败，GetMyChartByCondition，Err:" + err.Error()
						return
					}
					resp.ChartInfo.IsAdd = false
					resp.ChartInfo.MyChartId = 0
					resp.ChartInfo.MyChartClassifyId = ""
					if myList != nil && len(myList) > 0 {
						resp.ChartInfo.IsAdd = true
						resp.ChartInfo.MyChartId = myList[0].MyChartId
						resp.ChartInfo.MyChartClassifyId = myList[0].MyChartClassifyId
					}

					isOk = true
					fmt.Println("source redis")
					return
				}
			}
		}
	}

	chartInfoId := chartInfo.ChartInfoId

	startDate := chartInfo.StartDate
	endDate := chartInfo.EndDate

	// 兼容日期错误
	{
		if strings.Count(startDate, "-") == 1 {
			startDate = startDate + "-01"
		}
		if strings.Count(endDate, "-") == 1 {
			endDate = endDate + "-01"
		}
	}

	edbInfoMapping, err := data_manage.GetEtaEdbChartEdbMapping(chartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取图表，现货指标信息失败，Err:" + err.Error()
		return
	}
	futureGoodEdbInfoMapping, err := data_manage.GetFutureGoodEdbChartEdbMapping(chartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取图表的期货商品指标信息失败，Err:" + err.Error()
		return
	}

	// 商品价格曲线图的一些配置
	var barConfig data_manage.BarChartInfoReq
	barChartInfoDateList := make([]data_manage.BarChartInfoDateReq, 0)
	barChartInfoSort := data_manage.BarChartInfoSortReq{}

	if chartInfo.BarConfig == `` {
		msg = "商品价格曲线图未配置"
		errMsg = "商品价格曲线图未配置"
		return
	}
	err = json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
	if err != nil {
		msg = "商品价格曲线图配置异常"
		errMsg = "商品价格曲线图配置异常"
		return
	}

	barChartInfoDateList = barConfig.DateList
	barChartInfoSort = barConfig.Sort

	// 获取图表中的指标数据
	barConfigEdbInfoIdList, edbList, xEdbIdValue, xDataList, yDataList, err := future_goodServ.GetChartEdbData(chartInfoId, startDate, endDate, edbInfoMapping, futureGoodEdbInfoMapping, barChartInfoDateList, barChartInfoSort)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	warnEdbList := make([]string, 0)
	if len(edbList) <= 0 {
		msg = "商品价格曲线图表指标异常"
		errMsg = "商品价格曲线图表异常"
		return
	}
	baseEdbInfo := edbList[0] //现货指标

	for _, v := range edbList {
		if v.IsNullData {
			warnEdbList = append(warnEdbList, v.EdbName+"("+v.EdbCode+")")
		}
		// 指标别名
		if barConfigEdbInfoIdList != nil && len(barConfigEdbInfoIdList) > 0 {
			for _, reqEdb := range barConfigEdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
					v.EdbAliasNameEn = reqEdb.NameEn
				}
			}
		}
	}
	if len(warnEdbList) > 0 {
		chartInfo.WarnMsg = `图表引用指标异常，异常指标：` + strings.Join(warnEdbList, "，")
	}
	if chartInfoId > 0 && chartInfo != nil {
		//判断是否加入我的图库
		{
			var myChartCondition string
			var myChartPars []interface{}
			myChartCondition += ` AND a.admin_id=? `
			myChartPars = append(myChartPars, sysUser.AdminId)
			myChartCondition += ` AND a.chart_info_id=? `
			myChartPars = append(myChartPars, chartInfo.ChartInfoId)

			myChartList, err := data_manage.GetMyChartByCondition(myChartCondition, myChartPars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				msg = "获取失败"
				errMsg = "获取我的图表信息失败，GetMyChartByCondition，Err:" + err.Error()
				return
			}
			if myChartList != nil && len(myChartList) > 0 {
				chartInfo.IsAdd = true
				chartInfo.MyChartId = myChartList[0].MyChartId
				chartInfo.MyChartClassifyId = myChartList[0].MyChartClassifyId
			}
		}
	}

	//图表操作权限
	chartInfo.IsEdit = data.CheckOpChartPermission(sysUser, chartInfo.SysUserId)
	chartInfo.Button.IsEdit = chartInfo.IsEdit
	chartInfo.Button.IsCopy = true
	//判断是否需要展示英文标识
	chartInfo.IsEnChart = data.CheckIsEnChart(chartInfo.ChartNameEn, edbList[0:1], chartInfo.Source, chartInfo.ChartType)
	chartInfo.UnitEn = baseEdbInfo.UnitEn

	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.XDataList = xDataList
	resp.BarChartInfo = barConfig
	resp.Status = true

	// 将数据加入缓存
	if utils.Re == nil {
		data, _ := json.Marshal(resp)
		utils.Rc.Put(key, data, 2*time.Hour)
	}
	isOk = true

	return
}

// ChartInfoEdbInfoSearch
// @Title 图表指标模糊搜索
// @Description 图表指标模糊搜索接口
// @Param   KeyWord   query   string  true       "指标名称/ID"
// @Success 200 {object} data_manage.ChartEdbInfo
// @router /chart_info/edb_info/search [get]
func (this *FutureGoodChartInfoController) ChartInfoEdbInfoSearch() {
	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
	}
	KeyWord := this.GetString("KeyWord")
	//if KeyWord == "" {
	//	br.Msg = "请输入指标名称/指标ID"
	//	return
	//}
	var err error
	searchList := make([]*data_manage.ChartEdbInfo, 0)
	searchList, err = data_manage.EdbInfoSearchByKeyWord(KeyWord)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
		return
	}
	if searchList == nil {
		searchList = make([]*data_manage.ChartEdbInfo, 0)
	}

	lenSearchList := len(searchList)
	for i := 0; i < lenSearchList; i++ {
		searchList[i].EdbNameAlias = searchList[i].EdbName
	}

	for i := 0; i < lenSearchList; i++ {
		for j := 0; j < lenSearchList; j++ {
			if (searchList[i].EdbNameAlias == searchList[j].EdbNameAlias) &&
				(searchList[i].EdbInfoId != searchList[j].EdbInfoId) &&
				!(strings.Contains(searchList[i].EdbName, searchList[i].SourceName)) {
				searchList[i].EdbName = searchList[i].EdbName + "(" + searchList[i].SourceName + ")"
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = searchList
}

// ChartInfoEdbInfoDetail
// @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年至今"
// @Param   StartDate   query   string  true       "自定义开始日期"
// @Param   EndDate   query   string  true       "自定义结束日期"
// @Param   EdbInfoType  query int  true     "1:标准指标,0:领先指标，默认为标准指标"
// @Param   LeadValue    query   int  true       "领先值"
// @Param   LeadUnit     query   string  true        "领先单位:天，月，季，周"
// @Success 200 {object} data_manage.ChartEdbInfoDetailResp
// @router /chart_info/edb_info/detail [get]
func (this *FutureGoodChartInfoController) ChartInfoEdbInfoDetail() {
	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
	}
	edbInfoId, _ := this.GetInt("EdbInfoId")
	if edbInfoId <= 0 {
		br.Msg = "参数错误"
		return
	}
	dateType, _ := this.GetInt("DateType")
	if dateType <= 0 {
		dateType = 3
	}

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

	leadValue, _ := this.GetInt("LeadValue")
	if leadValue < 0 {
		leadValue = 0
	}

	leadUnit := this.GetString("LeadUnit")

	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")

	isTimeBetween := false //是否是时间区间
	switch dateType {
	case 1:
		startDate = "2000-01-01"
		endDate = ""
	case 2:
		startDate = "2010-01-01"
		endDate = ""
	case 3:
		startDate = "2015-01-01"
		endDate = ""
	case 4:
		//startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
		startDate = "2021-01-01"
		endDate = ""
	case 5:
		startDate = startDate + "-01"
		endDate = endDate + "-01"
		isTimeBetween = true
	case 6:
		//startDate = startDate + "-01"
		endDate = ""
	case 7:
		startDate = "2018-01-01"
		endDate = ""
	case 8:
		startDate = "2019-01-01"
		endDate = ""
	case 9:
		startDate = "2020-01-01"
		endDate = ""
	case 11:
		startDate = "2022-01-01"
		endDate = ""
	default:
		startDate = startDate + "-01"
		endDate = endDate + "-01"
	}

	// 兼容日期错误
	{
		if strings.Count(startDate, "-") == 1 {
			startDate = startDate + "-01"
		}
		if strings.Count(endDate, "-") == 1 {
			endDate = endDate + "-01"
		}
	}

	if startDate == "" {
		br.Msg = "参数错误"
		br.Msg = "参数错误,无效的查询日期"
		return
	}

	var startDateReal string
	var diffSeconds int64
	if leadValue > 0 && leadUnit != "" {
		var startTimeRealTemp time.Time
		startDateParse, err := time.Parse(utils.FormatDate, startDate)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取数据失败,日期格式错误：startDate:" + startDate
			return
		}
		switch leadUnit {
		case "天":
			startTimeRealTemp = startDateParse.AddDate(0, 0, -leadValue)
		case "月":
			startTimeRealTemp = startDateParse.AddDate(0, -leadValue, 0)
		case "季":
			startTimeRealTemp = startDateParse.AddDate(0, -3*leadValue, 0)
		case "周":
			startTimeRealTemp = startDateParse.AddDate(0, 0, -7*leadValue)
		case "年":
			startTimeRealTemp = startDateParse.AddDate(-leadValue, 0, 0)
		}

		if startTimeRealTemp.Before(startDateParse) {
			startDateReal = startTimeRealTemp.Format(utils.FormatDate)
			diffSeconds = (int64(startTimeRealTemp.UnixNano()) - int64(startDateParse.UnixNano())) / 1e6
		} else {
			startDateReal = startDate
			diffSeconds = 0
		}
	} else {
		startDateReal = startDate
	}

	edbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取失败,Err:" + err.Error()
		return
	}

	var dataList []*data_manage.EdbDataList
	var minData, maxData float64

	switch edbInfo.EdbInfoType {
	case 0: //普通源指标
		dataList, err = data_manage.GetEdbDataList(edbInfo.Source, edbInfoId, startDateReal, endDate)
		if err != nil {
			br.Msg = "获取失败"
			br.Msg = "获取失败,Err:" + err.Error()
			return
		}
		//查询区间内最大最小值
		minData, maxData, err = data_manage.GetEdbDataListMinAndMax(edbInfo.Source, edbInfoId, startDateReal, endDate)
		if err != nil {
			br.Msg = "获取失败"
			br.Msg = "获取指标最新的最大最小值失败,Err:" + err.Error()
			return
		}
	case 1: //预测指标
		tmpDataList, sourceEdbInfoItem, _, err, _ := data.GetPredictDataListByPredictEdbInfo(edbInfo, startDateReal, endDate, isTimeBetween)
		if err != nil {
			br.Msg = "获取失败"
			br.Msg = "获取失败,Err:" + err.Error()
			return
		}
		dataList = tmpDataList
		// 有预测数据，且为普通的预测指标
		if len(dataList) > 0 && edbInfo.EdbInfoType == 0 {
			//查询区间内最大最小值
			minData, maxData, err = data_manage.GetEdbDataListMinAndMax(sourceEdbInfoItem.Source, sourceEdbInfoItem.EdbInfoId, startDateReal, endDate)
			if err != nil {
				br.Msg = "获取失败"
				br.Msg = "获取指标最新的最大最小值失败,Err:" + err.Error()
				return
			}

			tmpValue := dataList[len(dataList)-1]

			// 如果最大值 小于 预测值，那么将预测值作为最大值数据返回
			if edbInfo.MaxValue < tmpValue.Value {
				maxData = tmpValue.Value
			}

			// 如果最小值 大于 预测值，那么将预测值作为最小值数据返回
			if edbInfo.MinValue > tmpValue.Value {
				minData = tmpValue.Value
			}
		}
	}

	if diffSeconds != 0 {
		dataListLen := len(dataList)
		for i := 0; i < dataListLen; i++ {
			dataList[i].DataTimestamp = dataList[i].DataTimestamp - diffSeconds
		}
	}
	mapping := new(data_manage.ChartEdbInfoMapping)
	mapping.EdbInfoId = edbInfo.EdbInfoId
	mapping.EdbInfoCategoryType = edbInfo.EdbInfoType
	mapping.SourceName = edbInfo.SourceName
	mapping.Source = edbInfo.Source
	mapping.EdbCode = edbInfo.EdbCode
	mapping.EdbName = edbInfo.EdbName
	mapping.EdbType = edbInfo.EdbType
	mapping.Frequency = edbInfo.Frequency
	mapping.Unit = edbInfo.Unit
	mapping.StartDate = edbInfo.StartDate
	mapping.EndDate = edbInfo.EndDate
	mapping.ChartEdbMappingId = 0
	mapping.ChartInfoId = 0
	mapping.MaxData = maxData
	mapping.MinData = minData
	mapping.IsOrder = false
	mapping.IsAxis = 1
	mapping.EdbInfoType = 1
	mapping.LeadValue = 0
	mapping.LeadUnit = ""
	mapping.LeadUnitEn = ""
	mapping.ChartStyle = ""
	mapping.ChartColor = ""
	mapping.PredictChartColor = ""
	mapping.ChartWidth = 0
	mapping.DataList = dataList

	resp := new(data_manage.ChartEdbInfoDetailResp)
	resp.EdbInfo = mapping
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ChartInfoSearchByEs
// @Title 图表模糊搜索（从es获取）
// @Description  图表模糊搜索（从es获取）
// @Param   Keyword   query   string  true       "图表名称"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Success 200 {object} data_manage.ChartInfo
// @router /chart_info/search_by_es [get]
func (this *FutureGoodChartInfoController) ChartInfoSearchByEs() {
	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
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

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

	keyword := this.GetString("Keyword")
	if keyword == `` {
		keyword = this.GetString("KeyWord")
	}

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	showSysId := 0
	if isShowMe {
		showSysId = sysUser.AdminId
	}

	var searchList []*data_manage.ChartInfo
	var total int64
	var err error

	// 获取当前账号的不可见指标
	noPermissionChartIdList := make([]int, 0)
	{
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllChartListByAdminId(this.SysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败，Err:" + err.Error()
			return
		}
		for _, v := range confList {
			noPermissionChartIdList = append(noPermissionChartIdList, v.ChartInfoId)
		}
	}

	if keyword != "" {
		searchList, total, err = data.EsSearchChartInfo(keyword, showSysId, []int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, noPermissionChartIdList, startSize, pageSize)
	} else {
		total, searchList, err = data_manage.ChartInfoSearchByEmptyKeyWord(showSysId, []int{utils.CHART_SOURCE_FUTURE_GOOD, utils.CHART_SOURCE_FUTURE_GOOD_PROFIT}, noPermissionChartIdList)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
			return
		}
	}

	finalList := make([]*data_manage.ChartInfoMore, 0)
	if len(searchList) > 0 {
		chartInfoIds := ""
		chartEdbMap := make(map[int][]*data_manage.ChartEdbInfoMapping)
		for _, v := range searchList {
			chartInfoIds += strconv.Itoa(v.ChartInfoId) + ","
		}
		if chartInfoIds != "" {
			chartInfoIds = strings.Trim(chartInfoIds, ",")
			//判断是否需要展示英文标识
			edbList, e := data_manage.GetChartEdbMappingListByChartInfoIds(chartInfoIds)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + e.Error()
				return
			}
			for _, v := range edbList {
				chartEdbMap[v.ChartInfoId] = append(chartEdbMap[v.ChartInfoId], v)
			}
		}

		for _, v := range searchList {
			tmp := new(data_manage.ChartInfoMore)
			tmp.ChartInfo = *v
			//判断是否需要展示英文标识
			if edbTmpList, ok := chartEdbMap[v.ChartInfoId]; ok {
				tmp.IsEnChart = data.CheckIsEnChart(v.ChartNameEn, edbTmpList, v.Source, v.ChartType)
			}
			finalList = append(finalList, tmp)
		}
	}
	//新增搜索词记录
	{
		searchKeyword := new(data_manage.SearchKeyword)
		searchKeyword.KeyWord = keyword
		searchKeyword.CreateTime = time.Now()
		go data_manage.AddSearchKeyword(searchKeyword)
	}

	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp := data_manage.ChartInfoListByEsResp{
		Paging: page,
		List:   finalList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ChartInfoRefresh
// @Title 图表刷新接口
// @Description 图表刷新接口
// @Param   ChartInfoId   query   int  true       "图表id"
// @Param   UniqueCode   query   string  true       "唯一code"
// @Success Ret=200 刷新成功
// @router /chart_info/refresh [get]
func (this *FutureGoodChartInfoController) ChartInfoRefresh() {
	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
	}
	chartInfoId, _ := this.GetInt("ChartInfoId")
	uniqueCode := this.GetString("UniqueCode")
	if chartInfoId <= 0 && uniqueCode == `` {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误:chartInfoId:" + strconv.Itoa(chartInfoId) + ",UniqueCode:" + uniqueCode
		return
	}

	var chartInfo *data_manage.ChartInfo
	var err error
	if chartInfoId > 0 {
		chartInfo, err = data_manage.GetChartInfoById(chartInfoId)
	} else {
		chartInfo, err = data_manage.GetChartInfoByUniqueCode(uniqueCode)
	}
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，无需刷新"
			br.ErrMsg = "获取指标信息失败，Err:" + err.Error()
			return
		}
		br.Msg = "刷新失败"
		br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
		return
	}
	err = future_goodServ.FutureGoodChartInfoRefresh(chartInfo.ChartInfoId)
	if err != nil {
		br.Msg = "刷新失败"
		br.ErrMsg = "刷新图表关联指标信息失败，Err:" + err.Error()
		return
	}

	//清除图表缓存
	{
		key := utils.HZ_CHART_LIB_DETAIL + chartInfo.UniqueCode
		_ = utils.Rc.Delete(key)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

// ChartInfoImageSet
// @Title 设置商品价格图表图片
// @Description 设置商品价格图表图片
// @Param	request	body data_manage.SetChartInfoImageReq true "type json string"
// @Success Ret=200 保存成功
// @router /chart_info/image/set [post]
func (this *FutureGoodChartInfoController) ChartInfoImageSet() {
	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 data_manage.SetChartInfoImageReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartInfoId > 0 && req.ImageUrl != "" {
		err = data_manage.EditChartInfoImage(&req)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}

		//修改es数据
		go data.EsAddOrEditChartInfo(req.ChartInfoId)
		//修改my eta es数据
		go data.EsAddOrEditMyChartInfoByChartInfoId(req.ChartInfoId)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

//
//// @Param   Img   query   string  true       "图片"
//// @Success 200 {object} models.ResourceResp
//// @router /chart_info/base64Upload [post]
//func (this *FutureGoodChartInfoController) ChartInfoBase64Upload() {
//
//	br := new(models.BaseResponse).Init()
//	defer func() {
//		this.Data["json"] = br
//		this.ServeJSON()
//	}()
//
//	var err error
//	ext := ".png"
//	uploadDir := "./static"
//	randStr := utils.GetRandStringNoSpecialChar(28)
//	fileName := randStr + ext
//	fpath := uploadDir + "/" + fileName
//
//	image := this.Ctx.Request.FormValue("Img")
//	if image == "" {
//		resp := new(models.ResourceResp)
//		resp.Id = 0
//		resp.ResourceUrl = ""
//		br.Msg = "上传成功"
//		br.Ret = 200
//		br.Success = true
//		br.Data = resp
//		return
//	}
//	b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, image)
//	if !b {
//		br.Msg = "图片格式不正确"
//		br.ErrMsg = "图片格式不正确"
//		return
//	}
//	re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
//	base64Str := re.ReplaceAllString(image, "")
//	base64Str = strings.Replace(base64Str, " ", "", -1)
//
//	err = utils.SaveBase64ToFile(base64Str, fpath)
//	if err != nil {
//		br.Msg = "图片保存失败"
//		br.ErrMsg = "图片保存失败,Err:" + err.Error()
//		return
//	}
//	fmt.Println("end")
//
//	defer os.Remove(fpath)
//
//	hzUploadDir := "static/images/"
//	savePath := hzUploadDir + time.Now().Format("200601/20060102/")
//	savePath += fileName
//	//上传到阿里云
//	err = services.UploadFileToAliyun(fileName, fpath, savePath)
//	if err != nil {
//		br.Msg = "文件上传失败"
//		br.ErrMsg = "文件上传失败，Err:" + err.Error()
//		return
//	}
//	utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
//	utils.FileLog.Info("end update oss ")
//
//	fileHost := "https://hzstatic.hzinsights.com/"
//
//	resourceUrl := fileHost + savePath
//
//	item := new(models.Resource)
//	item.ResourceUrl = resourceUrl
//	item.ResourceType = 1
//	item.CreateTime = time.Now()
//	newId, err := models.AddResource(item)
//	if err != nil {
//		br.Msg = "资源上传失败"
//		br.ErrMsg = "资源上传失败,Err:" + err.Error()
//		return
//	}
//	resp := new(models.ResourceResp)
//	resp.Id = newId
//	resp.ResourceUrl = resourceUrl
//	br.Msg = "上传成功"
//	br.Ret = 200
//	br.Success = true
//	br.Data = resp
//
//	//br := new(models.BaseResponse).Init()
//	//defer func() {
//	//	this.Data["json"] = br
//	//	this.ServeJSON()
//	//}()
//	//imgData := this.GetString("Img")
//	//if imgData == "" {
//	//	br.Msg = "图片参数错误"
//	//	br.ErrMsg = "图片参数错误,Img Is Empty"
//	//	return
//	//}
//
//	//dateDir := time.Now().Format("20060102")
//	//uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
//	//
//	//if !utils.FileIsExist(uploadDir) {
//	//	err := os.MkdirAll(uploadDir, 777)
//	//	if err != nil {
//	//		br.Msg = "存储目录创建失败"
//	//		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
//	//		return
//	//	}
//	//}
//	//var resourceUrl string
//	//param := url.Values{}
//	//param.Add("Sign", "dIGi2M0VN21s3dKS")
//	//param.Add("Img", imgData)
//	//svgToPngUrl := `http://8.136.199.33:8086/v1/image/svg_to_png`
//	//respBody, err := http.Post(svgToPngUrl, param.Encode(), "")
//	//if err != nil {
//	//	br.Msg = "文件上传失败"
//	//	br.ErrMsg = "图片格式转换失败，Err:" + err.Error()
//	//	return
//	//}
//	//fmt.Println(string(respBody))
//	//respItem := new(data_manage.ImageSvgToPngResp)
//	//err = json.Unmarshal(respBody, &respItem)
//	//if err != nil {
//	//	br.Msg = "文件上传失败"
//	//	br.ErrMsg = "图片格式转换失败，Unmarshal Err:" + err.Error()
//	//	return
//	//}
//	//resourceUrl = respItem.Data.ResourceURL
//	//resp := new(models.ResourceResp)
//	//resp.ResourceUrl = resourceUrl
//	//br.Msg = "上传成功"
//	//br.Ret = 200
//	//br.Success = true
//	//br.Data = resp
//
//
//
//	/*
//		svg 转 png
//
//		uploadDir := "static/images/"
//		if !utils.FileIsExist(uploadDir) {
//			err := os.MkdirAll(uploadDir, 777)
//			if err != nil {
//				br.Msg = "图表保存失败"
//				br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
//				return
//			}
//		}
//
//		var saveToOssPath string
//		randStr := utils.GetRandStringNoSpecialChar(28)
//		var fileName, outFileName string
//		fileName = randStr + ".txt"
//		//saveSvgPath = uploadDir + fileName
//		err := utils.SaveToFile(imgData, fileName)
//		if err != nil {
//			br.Msg = "图片保存失败"
//			br.ErrMsg = "图片保存失败,Err:" + err.Error()
//			return
//		}
//
//		outFileName = randStr + ".png"
//		cd := exec.Command("highcharts-export-server", "--infile", fileName, "--constr", "Chart", "--scale", "2", "--workers", "5", "--workLimit", "5", "--outfile", outFileName)
//		str, err := cd.Output()
//		fmt.Println(string(str))
//		if err != nil {
//			fmt.Println("Command Err:" + err.Error())
//			return
//		}
//		fmt.Println("end convert", time.Now())
//
//		defer func() {
//			os.Remove(fileName)
//			os.Remove(outFileName)
//		}()
//		saveToOssPath = uploadDir + time.Now().Format("200601/20060102/")
//		saveToOssPath += outFileName
//		//上传到阿里云
//		fmt.Println("upload:", outFileName, saveToOssPath)
//		err = services.UploadFileToAliyun("", outFileName, saveToOssPath)
//		if err != nil {
//			br.Msg = "文件上传失败"
//			br.ErrMsg = "文件上传失败，Err:" + err.Error()
//			return
//		}
//		fileHost := "https://hzstatic.hzinsights.com/"
//		resourceUrl := fileHost + saveToOssPath
//
//		resp := new(models.ResourceResp)
//		resp.ResourceUrl = resourceUrl
//		br.Msg = "上传成功"
//		br.Ret = 200
//		br.Success = true
//		br.Data = resp
//	*/
//	return
//}

// @Param   Img   query   string  true       "图片"
// @Success 200 {object} models.ResourceResp
// @router /chart_info/base64Upload [post]
func (this *FutureGoodChartInfoController) ChartInfoBase64Upload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	imgData := this.GetString("Img")
	if imgData == "" {
		br.Msg = "图片参数错误"
		br.ErrMsg = "图片参数错误,Img Is Empty"
		return
	}
	resp := new(models.ResourceResp)

	uploadDir := "static/images/"
	if !utils.FileIsExist(uploadDir) {
		err := os.MkdirAll(uploadDir, 777)
		if err != nil {
			br.Msg = "图表保存失败"
			br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
			return
		}
	}

	var saveToOssPath string
	randStr := utils.GetRandStringNoSpecialChar(28)
	var fileName, outFileName string
	fileName = randStr + ".txt"
	//saveSvgPath = uploadDir + fileName
	err := utils.SaveToFile(imgData, fileName)
	if err != nil {
		br.Msg = "图片保存失败"
		br.ErrMsg = "图片保存失败,Err:" + err.Error()
		return
	}
	outFileName = randStr + ".png"

	doneChannel := make(chan bool, 1)
	errorChannel := make(chan error, 1)

	cmd := exec.Command("highcharts-export-server", "--infile", fileName, "--constr", "Chart", "--scale", "2", "--workers", "10", "--workLimit", "3", "--outfile", outFileName)

	go func() {
		output, err := cmd.CombinedOutput()
		if err != nil {
			utils.FileLog.Info("execute command failed, output: , error: \n" + string(output) + err.Error())
			errorChannel <- err
			return
		}
		doneChannel <- true
	}()

	select {
	case <-time.After(30 * time.Second):
		utils.FileLog.Info("执行超过30秒 杀死超时进程")
		cmd.Process.Kill()
		fmt.Println("timeout kill process")
	case <-doneChannel:
		fmt.Println("done")
	case err := <-errorChannel:
		fmt.Println("execute command failure err:" + err.Error())
		return
	}

	defer func() {
		os.Remove(fileName)
	}()

	saveToOssPath = uploadDir + time.Now().Format("200601/20060102/")
	saveToOssPath += outFileName
	err = services.UploadFileToAliyun("", outFileName, saveToOssPath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}
	fileHost := "https://hzstatic.hzinsights.com/"
	resourceUrl := fileHost + saveToOssPath
	resp.ResourceUrl = resourceUrl
	resp.Source = "convert"
	//resp.CacheKey = imgDataKey
	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
	return
}

// BatchChartInfoRefresh
// @Title 批量刷新图表接口
// @Description 批量刷新图表接口
// @Param	request	body data_manage.BatchChartRefreshReq true "type json string"
// @Success Ret=200 刷新成功
// @router /chart_info/batch_refresh [post]
//func (this *EdbInfoController) BatchChartInfoRefresh() {
//	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 data_manage.BatchChartRefreshReq
//	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
//	if err != nil {
//		br.Msg = "参数解析异常！"
//		br.ErrMsg = "参数解析失败，Err:" + err.Error()
//		return
//	}
//
//	//获取所有的图表列表
//	_, chartInfoList, err := data_manage.GetChartInfoListByUniqueCodeSlice(req.ChartInfoCode)
//	if len(chartInfoList) <= 0 {
//		br.Ret = 200
//		br.Success = true
//		br.Msg = "刷新成功"
//		return
//	}
//
//	err = data.BatchChartInfoRefreshV2(chartInfoList)
//	if err != nil {
//		br.Msg = "刷新失败"
//		br.ErrMsg = "刷新图表关联指标信息失败，Err:" + err.Error()
//		return
//	}
//
//	//清除图表缓存
//	for _, v := range chartInfoList {
//		key := utils.HZ_CHART_LIB_DETAIL + v.UniqueCode
//		_ = utils.Rc.Delete(key)
//	}
//	br.Ret = 200
//	br.Success = true
//	br.Msg = "刷新成功"
//}

// CopyChartInfo
// @Title 复制并新增图表接口
// @Description 新增图表接口
// @Param	request	body data_manage.CopyAddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /chart_info/copy [post]
func (this *FutureGoodChartInfoController) CopyChartInfo() {
	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
	}
	deleteCache := true
	cacheKey := "CACHE_CHART_INFO_ADD_" + strconv.Itoa(sysUser.AdminId)
	defer func() {
		if deleteCache {
			utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	var req data_manage.CopyAddChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	// 获取原图表信息
	oldChartInfo, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		br.Msg = "获取原图表信息失败"
		br.ErrMsg = "获取原图表信息失败,Err:" + err.Error()
		return
	}

	opStatus := ``
	var chartInfo *data_manage.ChartInfo
	switch oldChartInfo.Source {
	case utils.CHART_SOURCE_FUTURE_GOOD:
		chartInfo = copyChartInfo(oldChartInfo, req.ChartClassifyId, req.ChartName, sysUser, br)
		opStatus = `复制商品价格图表`
	case utils.CHART_SOURCE_FUTURE_GOOD_PROFIT:
		chartInfo = copyProfitChartInfo(oldChartInfo, req.ChartClassifyId, req.ChartName, sysUser, br)
		opStatus = `复制商品利润图表`
	default:
		br.Msg = "错误的图表类型"
		br.ErrMsg = "错误的图表类型"
		br.IsSendEmail = false
		return
	}

	//添加es数据
	go data.EsAddOrEditChartInfo(chartInfo.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartInfo.ChartInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartInfoId = chartInfo.ChartInfoId
		chartLog.ChartName = req.ChartName
		chartLog.ChartClassifyId = req.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartInfo.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = opStatus
		chartLog.Method = this.Ctx.Input.URI()
		go data_manage.AddChartInfoLog(chartLog)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = data_manage.AddChartInfoResp{
		ChartInfoId: chartInfo.ChartInfoId,
		UniqueCode:  chartInfo.UniqueCode,
		ChartType:   chartInfo.ChartType,
	}
	br.IsAddLog = true
}

// copyChartInfo 复制商品价格曲线图
func copyChartInfo(oldChartInfo *data_manage.ChartInfo, chartClassifyId int, chartName string, sysUser *system.Admin, br *models.BaseResponse) (chartInfo *data_manage.ChartInfo) {
	chartInfoId := oldChartInfo.ChartInfoId

	//校验图表名称是否重复
	chartName = strings.Trim(chartName, " ")
	if chartName == "" {
		br.Msg = "请填写图表名称！"
		return
	}
	if chartClassifyId <= 0 {
		br.Msg = "分类参数错误！"
		return
	}
	chartClassify, err := data_manage.GetChartClassifyById(chartClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			br.ErrMsg = "分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	if chartClassify == nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "分类不存在"
		return
	}
	//count, err := data_manage.ChartInfoExist("", edbInfoIdStr)
	//if err != nil && err.Error() != utils.ErrNoRow() {
	//	br.Msg = "保存失败"
	//	br.ErrMsg = "判断图表名称是否存在失败,Err:" + err.Error()
	//	return
	//}
	//if count > 0 {
	//	br.Msg = "所选指标已存在相同指标"
	//	return
	//}
	//判断图表是否存在
	var condition string
	var pars []interface{}
	condition += " AND chart_classify_id=? "
	pars = append(pars, chartClassifyId)

	condition += " AND chart_name=? AND source = ? "
	pars = append(pars, chartName, utils.CHART_SOURCE_FUTURE_GOOD)

	count, err := data_manage.GetChartInfoCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "判断图表名称是否存在失败"
		br.ErrMsg = "判断图表名称是否存在失败,Err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "图表已存在，请重新填写"
		br.IsSendEmail = false
		return
	}

	//获取原图表关联的指标信息列表
	edbMappingList, err := data_manage.GetChartEdbMappingListV2(chartInfoId)
	if err != nil {
		br.Msg = "获取图表关联的指标信息失败！"
		return
	}

	//添加图表
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	chartInfo = &data_manage.ChartInfo{
		ChartInfoId:     0,
		ChartName:       chartName,
		ChartClassifyId: chartClassifyId,
		SysUserId:       sysUser.AdminId,
		SysUserRealName: sysUser.RealName,
		UniqueCode:      utils.MD5(utils.CHART_PREFIX + "_" + timestamp),
		CreateTime:      time.Now(),
		ModifyTime:      time.Now(),
		DateType:        oldChartInfo.DateType,
		StartDate:       oldChartInfo.StartDate,
		EndDate:         oldChartInfo.EndDate,
		IsSetName:       oldChartInfo.IsSetName,
		EdbInfoIds:      oldChartInfo.EdbInfoIds,
		ChartType:       oldChartInfo.ChartType,
		Calendar:        oldChartInfo.Calendar,
		SeasonStartDate: oldChartInfo.SeasonStartDate,
		SeasonEndDate:   oldChartInfo.SeasonEndDate,
		ChartImage:      oldChartInfo.ChartImage,
		BarConfig:       oldChartInfo.BarConfig,
		//Sort:     sort,
		LeftMin:  oldChartInfo.LeftMin,
		LeftMax:  oldChartInfo.LeftMax,
		RightMin: oldChartInfo.RightMin,
		RightMax: oldChartInfo.RightMax,
		Disabled: oldChartInfo.Disabled,
		Source:   oldChartInfo.Source,
	}
	newId, err := data_manage.AddChartInfo(chartInfo)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}
	chartInfo.ChartInfoId = int(newId)

	// 添加图表与指标的关联关系
	{
		mapList := make([]*data_manage.ChartEdbMapping, 0)
		for _, v := range edbMappingList {
			timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
			mapItem := &data_manage.ChartEdbMapping{
				//ChartEdbMappingId: 0,
				ChartInfoId: chartInfo.ChartInfoId,
				EdbInfoId:   v.EdbInfoId,
				CreateTime:  time.Now(),
				ModifyTime:  time.Now(),
				UniqueCode:  utils.MD5(utils.CHART_PREFIX + "_" + strconv.Itoa(v.EdbInfoId) + timestamp),
				MaxData:     v.MaxData,
				MinData:     v.MinData,
				IsOrder:     v.IsOrder,
				IsAxis:      v.IsAxis,
				EdbInfoType: v.EdbInfoType,
				LeadValue:   v.LeadValue,
				LeadUnit:    v.LeadUnit,
				ChartStyle:  v.ChartStyle,
				ChartColor:  v.ChartColor,
				ChartWidth:  v.ChartWidth,
				Source:      v.Source,
			}
			mapList = append(mapList, mapItem)
		}
		err = data_manage.AddChartEdbMapping(mapList)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败，Err:" + err.Error()
			return
		}
	}

	return
}

// PreviewBarChartInfo
// @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年至今"
// @Param   StartDate   query   string  true       "自定义开始日期"
// @Param   EndDate   query   string  true       "自定义结束日期"
// @Param   EdbInfoType  query int  true     "1:标准指标,0:领先指标，默认为标准指标"
// @Param   LeadValue    query   int  true       "领先值"
// @Param   LeadUnit     query   string  true        "领先单位:天，月，季，周"
// @Success 200 {object} data_manage.ChartEdbInfoDetailResp
// @router /chart_info/preview_bar [post]
func (this *FutureGoodChartInfoController) PreviewBarChartInfo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req data_manage.BarChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	if len(req.EdbInfoIdList) <= 0 {
		br.Msg = "请选择指标"
		return
	}
	if len(req.DateList) <= 0 {
		br.Msg = "请选择日期"
		return
	}
	chartInfo := new(data_manage.ChartInfoView)

	if len(req.EdbInfoIdList) != 2 {
		br.Msg = "指标数量异常"
		return
	}
	var edbInfoMapping, futureGoodEdbInfoMapping *data_manage.ChartEdbInfoMapping
	for _, v := range req.EdbInfoIdList {
		if v.Source == utils.CHART_SOURCE_DEFAULT {
			edbInfoMapping, err = data_manage.GetChartEdbMappingByEdbInfoId(v.EdbInfoId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
				return
			}
		} else if v.Source == utils.CHART_SOURCE_FUTURE_GOOD {
			futureGoodEdbInfoMapping, err = data_manage.GetChartEdbMappingByFutureGoodEdbInfoId(v.EdbInfoId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
				return
			}
		} else {
			br.Msg = "指标异常"
			br.ErrMsg = "指标异常"
			br.IsSendEmail = false
			return
		}
	}

	if edbInfoMapping == nil {
		br.Msg = "请选择ETA指标"
		br.ErrMsg = "请选择ETA指标"
		br.IsSendEmail = false
		return
	}
	if futureGoodEdbInfoMapping == nil {
		br.Msg = "请选择商品指标"
		br.ErrMsg = "请选择商品指标"
		br.IsSendEmail = false
		return
	}

	// 获取图表中的指标数据
	barConfigEdbInfoIdList, edbList, xEdbIdValue, xDataList, yDataList, err := future_goodServ.GetChartEdbData(0, "", "", edbInfoMapping, futureGoodEdbInfoMapping, req.DateList, req.Sort)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	warnEdbList := make([]string, 0)
	for _, v := range edbList {
		if v.IsNullData {
			warnEdbList = append(warnEdbList, v.EdbName+"("+v.EdbCode+")")
		}
		for _, reqEdb := range barConfigEdbInfoIdList {
			if v.EdbInfoId == reqEdb.EdbInfoId {
				v.EdbAliasName = reqEdb.Name
				v.EdbAliasNameEn = reqEdb.NameEn
			}
		}
	}
	if len(warnEdbList) > 0 {
		chartInfo.WarnMsg = `图表引用指标异常，异常指标：` + strings.Join(warnEdbList, "，")
	}

	//图表操作权限
	chartInfo.IsEdit = data.CheckOpChartPermission(sysUser, chartInfo.SysUserId)
	chartInfo.Button.IsEdit = chartInfo.IsEdit
	chartInfo.Button.IsCopy = true
	//判断是否需要展示英文标识
	chartInfo.IsEnChart = data.CheckIsEnChart(chartInfo.ChartNameEn, edbList, chartInfo.Source, chartInfo.ChartType)

	resp := new(data_manage.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.XDataList = xDataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

//
//修复数据时间戳

//func init() {
//	fmt.Println("start")
//	edbInfoList,err:=data_manage.GetEdbInfo()
//	if err!=nil {
//		fmt.Println("Err:",err.Error())
//		return
//	}
//	startDate:=time.Now().AddDate(-40,0,0).Format(utils.FormatDate)
//	endDate:=time.Now().Format(utils.FormatDate)
//	for _,v:=range edbInfoList{
//		dataList,err:=data_manage.GetEdbDataList(v.Source,v.EdbInfoId,startDate,endDate)
//		if err!=nil {
//			fmt.Println("GetEdbDataList Err:",err.Error())
//			return
//		}
//		for _,dv:=range dataList{
//			dataTime,err:=time.Parse(utils.FormatDate,dv.DataTime)
//			if err!=nil {
//				fmt.Println("time.Parse Err:"+err.Error())
//				return
//			}
//			timestamp:=dataTime.UnixNano()/1e6
//			err=data_manage.ModifyEdbDatadTimestamp(v.Source,dv.EdbDataId,timestamp)
//			if err!=nil{
//				fmt.Println("ModifyEdbDatadTimestamp Err:"+err.Error())
//				return
//			}
//			fmt.Println(v.Source,dv.EdbDataId,timestamp)
//		}
//	}
//	//time.Sleep(2*time.Minute)
//
//	//startDate:=time.Now().AddDate(-30,0,0).Format(utils.FormatDate)
//	//endDate:=time.Now().Format(utils.FormatDate)
//	//dataList,err:=data_manage.GetEdbDataList(1,100099,startDate,endDate)
//	//if err!=nil {
//	//	fmt.Println("GetEdbDataList Err:",err.Error())
//	//	return
//	//}
//	//for _,dv:=range dataList{
//	//	dataTime,err:=time.Parse(utils.FormatDate,dv.DataTime)
//	//	if err!=nil {
//	//		fmt.Println("time.Parse Err:"+err.Error())
//	//		return
//	//	}
//	//	timestamp:=dataTime.UnixNano()/1e6
//	//	err=data_manage.ModifyEdbDatadTimestamp(2,dv.EdbDataId,timestamp)
//	//	if err!=nil{
//	//		fmt.Println("ModifyEdbDatadTimestamp Err:"+err.Error())
//	//		return
//	//	}
//	//	fmt.Println(2,dv.EdbDataId,timestamp)
//	//}
//
//	fmt.Println("end")
//}

//修复指标配置数据
//func init() {
//	fmt.Println("start")
//	edbInfo, err := data_manage.GetEdbInfoAll()
//	fmt.Println(err)
//	for k, v := range edbInfoAll {
//		fmt.Println(k, v.EdbInfoId)
//		item, err := data_manage.GetEdbInfoMaxAndMinInfo(v.Source, v.EdbCode)
//		fmt.Println(item, err)
//		err = data_manage.ModifyEdbInfoMaxAndMinInfo(v.EdbInfoId, item)
//		if err != nil {
//			fmt.Println("ModifyEdbInfoMaxAndMinInfo Err:" + err.Error())
//		}
//	}
//	fmt.Println("end")
//}

//func init() {
//	fmt.Println("start")
//	var yearArr []int
//	yearArr = append(yearArr, 2021)
//	yearArr = append(yearArr, 2010)
//	yearArr = append(yearArr, 2020)
//	yearArr = append(yearArr, 2017)
//	yearArr = append(yearArr, 2019)
//	sort.Sort(sort.Reverse(sort.IntSlice(yearArr)))
//	fmt.Println(yearArr)
//	fmt.Println("end")
//}

//季度指标数据计算(公历转农历)
//func init() {
//	fmt.Println("start AddCalculateQuarter")
//	list:=make([]*data_manage.EdbDataList,0)
//	data_manage.AddCalculateQuarterV4(list)
//	fmt.Println("end AddCalculateQuarter")
//	//return
//}

/*
{
  "ChartClassifyId": 58,
  "ChartName": "公历转农历6",
  "ChartType": 2,
  "ChartEdbInfoList": [
    {
      "ChartColor": "#00f",
      "ChartStyle": "spline",
      "ChartWidth": 3,
      "EdbInfoId": 100466,
      "EdbInfoType": 1,
      "IsAxis": 1,
      "IsOrder": false,
      "LeadUnit": "",
      "LeadValue": 0,
      "MaxData": 0.2943,
      "MinData": -0.2448
    }
  ]
}
*/
//func init() {
//	fmt.Println("start")
//	data_manage.AddCalculateQuarter(100466,6,"C2108252836")
//	fmt.Println("end")
//}

//func init() {
//	data.AddAllChartInfo()
//}
