package future_good

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_ETA_mobile_api/models/data_manage"
	"hongze/hongze_ETA_mobile_api/models/data_manage/future_good"
	"hongze/hongze_ETA_mobile_api/models/data_manage/future_good/request"
	"hongze/hongze_ETA_mobile_api/models/data_manage/future_good/response"
	"hongze/hongze_ETA_mobile_api/models/system"
	"hongze/hongze_ETA_mobile_api/services/data"
	"hongze/hongze_ETA_mobile_api/utils"
	"strings"
	"time"
)

// GetFutureGoodProfitChartInfoDetailFromUniqueCode 根据编码获取图表详情
func GetFutureGoodProfitChartInfoDetailFromUniqueCode(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

	// 商品利润曲线图的一些配置
	var extraConf request.ChartInfoReq
	err := json.Unmarshal([]byte(chartInfo.ExtraConfig), &extraConf)
	if err != nil {
		msg = "商品利润曲线图配置异常"
		errMsg = "商品利润曲线图配置异常，Err:" + err.Error()
		return
	}

	edbList := make([]*data_manage.ChartEdbInfoMapping, 0)
	edbInfoMapping, err := data_manage.GetEtaEdbChartEdbMapping(chartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取商品利润图表，基础指标信息失败，Err:" + err.Error()
		return
	}
	edbList = append(edbList, edbInfoMapping)
	futureGoodEdbInfoMappingList, err := data_manage.GetFutureGoodEdbChartEdbMappingList(chartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取商品利润图表，商品指标信息失败，Err:" + err.Error()
		return
	}
	edbList = append(edbList, futureGoodEdbInfoMappingList...)
	if len(edbList) <= 0 {
		msg = "商品利润曲线图表指标异常"
		errMsg = "商品利润曲线图表指标异常"
		return
	}

	xDataList := make([]data_manage.XData, 0)
	yDataList := make([]data_manage.YData, 0)

	// 查找商品利润图表的扩展信息
	chartInfoFutureGoodProfit := new(future_good.ChartInfoFutureGoodProfit)
	if err = chartInfoFutureGoodProfit.GetItemById(chartInfo.ChartInfoId); err != nil {
		msg = "获取失败"
		errMsg = "获取基础相关性图表信息失败, Err: " + err.Error()
		return
	}

	err = json.Unmarshal([]byte(chartInfoFutureGoodProfit.XValue), &xDataList)
	if err != nil {
		msg = "获取失败"
		errMsg = "转换X轴数据失败, Err: " + err.Error()
		return
	}

	err = json.Unmarshal([]byte(chartInfoFutureGoodProfit.YValue), &yDataList)
	if err != nil {
		msg = "获取失败"
		errMsg = "转换Y轴数据失败, Err: " + err.Error()
		return
	}

	warnEdbList := make([]string, 0)
	baseEdbInfo := edbList[0] //现货指标

	for _, v := range edbList {
		if v.IsNullData {
			warnEdbList = append(warnEdbList, v.EdbName+"("+v.EdbCode+")")
		}
	}
	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.DataResp = response.ProfitFutureGoodChartResp{
		YDataList:    yDataList,
		XDataList:    xDataList,
		ProfitName:   chartInfoFutureGoodProfit.ProfitName,
		ProfitNameEn: chartInfoFutureGoodProfit.ProfitNameEn,
		Extra:        extraConf,
	}
	resp.Status = true

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

	return
}
