package future_good

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services/data"
	future_goodServ "eta/eta_mobile/services/data/future_good"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

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

// 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.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
}

// 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")

	//只看我的
	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}, noPermissionChartIdList, startSize, pageSize)
	} else {
		total, searchList, err = data_manage.ChartInfoSearchByEmptyKeyWord(showSysId, []int{utils.CHART_SOURCE_FUTURE_GOOD}, 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 = "刷新成功"
}

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

	//校验图表名称是否重复
	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
	}
	//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, req.ChartClassifyId)

	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
	}

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

	//添加图表
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	chartInfo := &data_manage.ChartInfo{
		ChartInfoId:     0,
		ChartName:       req.ChartName,
		ChartClassifyId: req.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
		}
	}

	//添加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 = "复制商品价格图表"
		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
}
