package data_manage

import (
	"encoding/json"
	"eta/eta_mobile/controllers/data_manage/correlation"
	"eta/eta_mobile/controllers/data_manage/future_good"
	"eta/eta_mobile/controllers/data_manage/line_equation"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_manage/line_feature/request"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services/data"
	lineFeatureServ "eta/eta_mobile/services/data/line_feature"
	"eta/eta_mobile/utils"
	"fmt"
	"strconv"
	"time"
)

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

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

	switch chartInfo.Source {
	case utils.CHART_SOURCE_DEFAULT:
		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
	case utils.CHART_SOURCE_FUTURE_GOOD:
		resp, isOk, msg, errMsg := future_good.GetChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
		if !isOk {
			br.Msg = msg
			br.ErrMsg = errMsg
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	case utils.CHART_SOURCE_FUTURE_GOOD_PROFIT:
		resp, isOk, msg, errMsg := future_good.GetFutureGoodProfitChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
		if !isOk {
			br.Msg = msg
			br.ErrMsg = errMsg
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	case utils.CHART_SOURCE_CORRELATION, utils.CHART_SOURCE_ROLLING_CORRELATION:
		resp, isOk, msg, errMsg := correlation.GetChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
		if !isOk {
			br.Msg = msg
			br.ErrMsg = errMsg
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	case utils.CHART_SOURCE_LINE_EQUATION:
		resp, isOk, msg, errMsg := line_equation.GetChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
		if !isOk {
			br.Msg = msg
			br.ErrMsg = errMsg
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	case utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION, utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE, utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY:
		resp, isOk, msg, errMsg := GetLineFeatureChartInfoDetailFromUniqueCode(chartInfo, isCache, sysUser)
		if !isOk {
			br.Msg = msg
			br.ErrMsg = errMsg
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	default:
		br.Msg = "错误的图表"
		br.ErrMsg = "错误的图表"
		return
	}
}

// GetLineFeatureChartInfoDetailFromUniqueCode 根据编码获取统计特征图表详情
func GetLineFeatureChartInfoDetailFromUniqueCode(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
				}
			}
		}
	}

	if chartInfo.ExtraConfig == `` {
		msg = "获取失败"
		errMsg = "获取配置信息失败，图表的额外配置信息为空"
		return
	}

	// 获取图表关联指标
	edbMappingList, err := data_manage.GetChartEdbMappingList(chartInfo.ChartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取图表关联指标信息失败，Err:" + err.Error()
		return
	}
	if len(edbMappingList) != 1 {
		msg = "获取失败"
		errMsg = fmt.Sprint("获取图表关联指标信息异常，数量:", len(edbMappingList))
		return
	}
	edbMapping := edbMappingList[0]

	var edbList []*data_manage.ChartEdbInfoMapping
	var resultResp interface{}

	switch chartInfo.Source {
	case utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION:
		calculateValue, tmpErr := strconv.Atoi(chartInfo.ExtraConfig)
		if tmpErr != nil {
			msg = "获取失败"
			errMsg = "格式化配置项失败，Err:" + tmpErr.Error()
			return
		}
		startDate, endDate := utils.GetDateByDateType(chartInfo.DateType, chartInfo.StartDate, chartInfo.EndDate)
		edbList, resultResp, err, msg = lineFeatureServ.GetStandardDeviationData(chartInfo.ChartInfoId, startDate, endDate, edbMapping, calculateValue)
	case utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE:
		var percentileConfig request.Percentile
		err = json.Unmarshal([]byte(chartInfo.ExtraConfig), &percentileConfig)
		if err != nil {
			msg = "获取失败"
			errMsg = "格式化配置项失败，Err:" + err.Error()
			return
		}
		startDate, endDate := utils.GetDateByDateType(chartInfo.DateType, chartInfo.StartDate, chartInfo.EndDate)
		edbList, resultResp, err, msg = lineFeatureServ.GetPercentileData(chartInfo.ChartInfoId, startDate, endDate, edbMapping, percentileConfig.CalculateValue, percentileConfig.CalculateUnit)
	case utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY:
		var frequencyDistributionConfig request.FrequencyDistribution
		err = json.Unmarshal([]byte(chartInfo.ExtraConfig), &frequencyDistributionConfig)
		if err != nil {
			msg = "获取失败"
			errMsg = "格式化配置项失败，Err:" + err.Error()
			return
		}
		// 获取图表中的指标数据
		edbList, resultResp, err, errMsg = lineFeatureServ.GetFrequencyDistributionData(0, edbMapping, frequencyDistributionConfig.DateType, frequencyDistributionConfig.FrequencyValue, frequencyDistributionConfig.StartDate, frequencyDistributionConfig.EndDate)
	default:
		msg = `错误的图表`
		errMsg = fmt.Sprint("错误的图表来源，source", chartInfo.Source)
		return
	}
	if err != nil {
		if msg == `` {
			msg = "获取失败"
		}
		errMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}

	if chartInfo.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, []*data_manage.ChartEdbInfoMapping{}, chartInfo.Source, chartInfo.ChartType)
	//chartInfo.UnitEn = edbInfoMappingA.UnitEn

	isSaveAs := true
	// 另存为
	chartInfo.Button = data_manage.ChartViewButton{
		IsEdit:    chartInfo.IsEdit,
		IsEnChart: chartInfo.IsEnChart,
		IsAdd:     chartInfo.IsAdd,
		IsCopy:    isSaveAs,
		IsSetName: chartInfo.IsSetName,
	}

	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.DataResp = resultResp
	resp.Status = true

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