package chart

import (
	"encoding/json"
	"hongze/hongze_yb/models/tables/chart_theme"
	"hongze/hongze_yb/models/tables/chart_theme_type"
	"hongze/hongze_yb/utils"
)

// GetChartThemeConfig
// @Description: 根据主题id获取主题信息，如果获取不到的话，那么就获取默认的主题
// @author: Roc
// @datetime 2023-12-19 14:31:17
// @param chartThemeId int
// @param chartType int
// @param source int
// @return chartTheme *chart_theme.ChartTheme
// @return err error
func GetChartThemeConfig(chartThemeId, source, chartType int) (chartTheme *chart_theme.ChartTheme, err error) {
	chartTheme, err = chart_theme.GetChartThemeId(chartThemeId)
	if err != nil && err != utils.ErrNoRow {
		return
	}

	// 如果找到了，那么就返回
	if err == nil {
		// 兼容历史数据，加入新字段LineOptionList
		newConfig, e := ConvertOldChartOptions(chartTheme.Config)
		if e == nil {
			chartTheme.Config = newConfig
		}
		return
	}

	err = nil

	// 没有找到的话，那么就找默认的主题

	// 查找主题类型id
	chartThemeType, err := chart_theme_type.GetChartThemeTypeByChartTypeAndSource(chartType, source)
	if err != nil {
		return
	}

	// 寻找默认的主题id
	chartTheme, err = chart_theme.GetChartThemeId(chartThemeType.DefaultChartThemeID)
	if err != nil && err != utils.ErrNoRow {
		return
	}

	err = nil

	// 如果找到了，那么就返回
	if chartTheme != nil {
		// 兼容历史数据，加入新字段LineOptionList
		newConfig, e := ConvertOldChartOptions(chartTheme.Config)
		if e == nil {
			chartTheme.Config = newConfig
		}
		return
	}

	// 如果还是没找到，那就系统的主题id
	chartTheme, err = chart_theme.GetSystemChartTheme(chartThemeType.ChartThemeTypeID)

	// 兼容历史数据，加入新字段LineOptionList
	newConfig, e := ConvertOldChartOptions(chartTheme.Config)
	if e == nil {
		chartTheme.Config = newConfig
	}
	return
}

// 兼容历史数据，加入新字段LineOptionList
func ConvertOldChartOptions(config string) (newConfig string, err error) {
	var oldTheme chart_theme.OldChartOptions

	var newTheme chart_theme.NewChartOptions
	err = json.Unmarshal([]byte(config), &oldTheme)
	if err != nil {
		return
	}
	if oldTheme.LineOptionList != nil && len(oldTheme.LineOptionList) > 0 {
		newConfig = config
		return
	}
	newTheme.OldChartOptions = oldTheme
	for i := 0; i < 10; i++ {
		newLineOption := chart_theme.NewLineOptions{
			LineOptions: oldTheme.LineOptions,
			Color:       oldTheme.ColorsOptions[i],
			DataMark:    "none",
			MarkType:    "square",
			MarkSize:    5,
			MarkColor:   oldTheme.ColorsOptions[i],
		}
		newTheme.LineOptionList = append(newTheme.LineOptionList, newLineOption)
	}
	newThemeStr, _ := json.Marshal(newTheme)
	newConfig = string(newThemeStr)
	return
}
