package controllers

import (
	"encoding/json"
	"eta/eta_chart_lib/models"
	"eta/eta_chart_lib/models/data_manage"
	"eta/eta_chart_lib/services/data"
	"eta/eta_chart_lib/utils"
	"fmt"
	"strings"
	"time"
)

// 图表
type ChartController struct {
	BaseAuthController
}

// ChartInfoDetail
// @Title 获取图表详情
// @Description 获取图表详情接口
// @Param   UniqueCode   query   string  true       "图表唯一编码,如果是管理后台访问,传固定字符串:7c69b590249049942070ae9dcd5bf6dc"
// @Success 200 {object} data_manage.ChartInfoDetailResp
// @router /detail [get]
func (this *ChartController) ChartInfoDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	uniqueCode := this.GetString("UniqueCode")
	if uniqueCode == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,uniqueCode is empty"
		return
	}
	key := utils.HZ_CHART_LIB_DETAIL + uniqueCode
	resp := new(models.ChartInfoDetailResp)
	//判断是否有缓存
	if utils.Re == nil {
		if utils.Re == nil && utils.Rc.IsExist(key) {
			if data, err1 := utils.Rc.RedisBytes(key); err1 == nil {
				err := json.Unmarshal(data, &resp)
				if err == nil && resp != nil {
					br.Ret = 200
					br.Success = true
					br.Msg = "获取成功"
					br.Data = resp
					fmt.Println("source redis")
					return
				}
			}
		}
	}

	chartInfo, err := models.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
	}
	chartInfoId := chartInfo.ChartInfoId

	dateType := chartInfo.DateType
	if dateType <= 0 {
		dateType = 3
	}
	startDate := chartInfo.StartDate
	endDate := chartInfo.EndDate
	//seasonStartDate := chartInfo.SeasonStartDate
	//seasonEndDate := chartInfo.SeasonEndDate
	calendar := chartInfo.Calendar
	chartType := chartInfo.ChartType
	startYear := chartInfo.StartYear

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

	mappingList, err := models.GetChartEdbMappingList(chartInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表,指标信息失败,Err:" + err.Error()
		return
	}

	yearMax := 0
	if dateType == utils.DateTypeNYears {
		for _, v := range mappingList {
			if v.LatestDate != "" {
				lastDateT, tErr := time.Parse(utils.FormatDate, v.LatestDate)
				if tErr != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取图表日期信息失败,Err:" + tErr.Error()
					return
				}
				if lastDateT.Year() > yearMax {
					yearMax = lastDateT.Year()
				}
			}
		}
	}
	// 开始/结束日期
	startDate, endDate = utils.GetDateByDateTypeV2(dateType, startDate, endDate, startYear, yearMax)

	extraConfigStr := chartInfo.ExtraConfig
	// 柱方图的一些配置
	var barConfig data_manage.BarChartInfoReq
	if chartInfo != nil && chartInfo.ChartType == 7 {
		if chartInfo.BarConfig == `` {
			br.Msg = "柱方图未配置"
			br.ErrMsg = "柱方图未配置"
			return
		}
		err := json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
		if err != nil {
			br.Msg = "柱方图配置异常"
			br.ErrMsg = "柱方图配置异常"
			return
		}
		extraConfigStr = chartInfo.BarConfig
	}

	edbList, xEdbIdValue, yDataList, dataResp, err, errMsg := data.GetChartEdbData(chartInfoId, chartType, calendar, startDate, endDate, mappingList, extraConfigStr, chartInfo.SeasonExtraConfig)
	if err != nil {
		br.Msg = "获取失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "获取图表,指标信息失败,Err:" + err.Error()
		return
	}

	for _, v := range edbList {
		// 指标别名
		if barConfig.EdbInfoIdList != nil && len(barConfig.EdbInfoIdList) > 0 {
			for _, reqEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
				}
			}
		}
	}

	// 图表的指标来源
	sourceNameList, sourceNameEnList := data.GetEdbSourceByEdbInfoIdList(edbList)
	chartInfo.ChartSource = strings.Join(sourceNameList, ",")
	chartInfo.ChartSourceEn = strings.Join(sourceNameEnList, ",")

	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.DataResp = dataResp

	if utils.Re == nil {
		data, _ := json.Marshal(resp)
		utils.Rc.Put(key, data, 10*time.Minute)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ChartInfoRefresh
// @Title 图表刷新接口
// @Description 图表刷新接口
// @Param   UniqueCode   query   string  true       "图表唯一编码,如果是管理后台访问,传固定字符串:7c69b590249049942070ae9dcd5bf6dc"
// @Success Ret=200 刷新成功
// @router /refresh [get]
func (this *ChartController) ChartInfoRefresh() {
	br := new(models.BaseResponse).Init()
	chartId := 0
	defer func() {
		// 添加日志
		if chartId > 0 {
			shareChartRefreshLogInfo := &models.ShareChartRefreshLog{
				Ip:         this.Ctx.Input.IP(),
				ChartId:    chartId,
				CreateTime: time.Now(),
			}
			models.AddShareChartRefreshLog(shareChartRefreshLogInfo)
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	uniqueCode := this.GetString("UniqueCode")
	if uniqueCode == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,uniqueCode is empty"
		return
	}
	chartInfo, err := models.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
	}
	chartId = chartInfo.ChartInfoId

	//err = data.ChartInfoRefresh(chartInfo.ChartInfoId)
	//if err != nil {
	//	br.Msg = "刷新失败"
	//	br.ErrMsg = "刷新图表关联指标信息失败,Err:" + err.Error()
	//	return
	//}

	err = data.ChartInfoRefreshV2(chartInfo.ChartInfoId)
	if err != nil {
		br.Msg = "刷新失败"
		br.ErrMsg = "刷新图表关联指标信息失败,Err:" + err.Error()
		return
	}

	//清除数据缓存
	key := utils.HZ_CHART_LIB_DETAIL + uniqueCode
	if utils.Re == nil {
		utils.Rc.Delete(key)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

// 获取频度的英文版
func GetFrequencyEn(frequency string) (frequencyEn string) {
	switch frequency {
	case "日度":
		frequencyEn = "day"
		return
	case "周度":
		frequencyEn = "week"
		return
	case "旬度":
		frequencyEn = "ten days"
		return
	case "月度":
		frequencyEn = "month"
		return
	case "季度":
		frequencyEn = "quarter"
		return
	case "年度":
		frequencyEn = "year"
		return
	}
	return
}

func GetLeadUnitEn(unit string) (unitEn string) {
	switch unit {
	case "天":
		unitEn = "day"
		return
	case "周":
		unitEn = "week"
		return
	case "月":
		unitEn = "month"
		return
	case "季":
		unitEn = "quarter"
		return
	case "年":
		unitEn = "year"
		return
	}
	return
}

// GetChartInfoDetailFromUniqueCode 根据编码获取图表详情
func GetChartInfoDetailFromUniqueCode(chartInfo *models.ChartInfo, key string) (resp *models.ChartInfoDetailResp, isOk bool, msg, errMsg string) {
	resp = new(models.ChartInfoDetailResp)

	chartInfoId := chartInfo.ChartInfoId

	dateType := chartInfo.DateType
	if dateType <= 0 {
		dateType = 3
	}
	startDate := chartInfo.StartDate
	endDate := chartInfo.EndDate
	startYear := chartInfo.StartYear
	calendar := chartInfo.Calendar
	chartType := chartInfo.ChartType

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

	mappingList, err := models.GetChartEdbMappingList(chartInfoId)
	if err != nil {
		msg = "获取失败"
		errMsg = "获取图表,指标信息失败,Err:" + err.Error()
		return
	}
	yearMax := 0
	if dateType == utils.DateTypeNYears {
		for _, v := range mappingList {
			if v.LatestDate != "" {
				lastDateT, tErr := time.Parse(utils.FormatDate, v.LatestDate)
				if tErr != nil {
					msg = "获取失败"
					errMsg = "获取图表日期信息失败,Err:" + tErr.Error()
					return
				}
				if lastDateT.Year() > yearMax {
					yearMax = lastDateT.Year()
				}
			}
		}
	}
	startDate, endDate = utils.GetDateByDateTypeV2(dateType, startDate, endDate, startYear, yearMax)

	extraConfigStr := chartInfo.ExtraConfig
	// 柱方图的一些配置
	var barConfig data_manage.BarChartInfoReq
	if chartInfo != nil && chartInfo.ChartType == 7 {
		if chartInfo.BarConfig == `` {
			msg = "柱方图未配置"
			errMsg = "柱方图未配置"
			return
		}
		err := json.Unmarshal([]byte(chartInfo.BarConfig), &barConfig)
		if err != nil {
			msg = "柱方图配置异常"
			errMsg = "柱方图配置异常"
			return
		}
		extraConfigStr = chartInfo.BarConfig
	}

	edbList, xEdbIdValue, yDataList, dataResp, err, tmpErrMsg := data.GetChartEdbData(chartInfoId, chartType, calendar, startDate, endDate, mappingList, extraConfigStr, chartInfo.SeasonExtraConfig)
	if err != nil {
		msg = "获取失败"
		if tmpErrMsg != `` {
			msg = tmpErrMsg
		}
		errMsg = "获取图表,指标信息失败,Err:" + err.Error()
		return
	}

	for _, v := range edbList {
		// 指标别名
		if barConfig.EdbInfoIdList != nil && len(barConfig.EdbInfoIdList) > 0 {
			for _, reqEdb := range barConfig.EdbInfoIdList {
				if v.EdbInfoId == reqEdb.EdbInfoId {
					v.EdbAliasName = reqEdb.Name
				}
			}
		}
	}

	// 图表的指标来源
	sourceNameList, sourceNameEnList := data.GetEdbSourceByEdbInfoIdList(edbList)
	chartInfo.ChartSource = strings.Join(sourceNameList, ",")
	chartInfo.ChartSourceEn = strings.Join(sourceNameEnList, ",")

	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.DataResp = dataResp

	if utils.Re == nil {
		jsonData, _ := json.Marshal(resp)
		utils.Rc.Put(key, jsonData, 10*time.Minute)
	}

	isOk = true
	return
}