package data_manage

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_manage/chart_theme"
	"eta/eta_mobile/models/data_manage/chart_theme/request"
	"eta/eta_mobile/services/data"
	"eta/eta_mobile/utils"
	"time"
)

// ChartThemeController
// @Description: 图表主题配置模块
type ChartThemeController struct {
	controllers.BaseAuthController
}

// List
// @Title 获取主题列表
// @Description 获取主题列表接口
// @Param   ChartThemeTypeId   query   int  true       "图表主题类型id"
// @Success 200 {object} []*chart_theme.ChartTheme
// @router /chart/theme/list [get]
func (c *ChartThemeController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	chartThemeTypeId, _ := c.GetInt("ChartThemeTypeId")
	if chartThemeTypeId <= 0 {
		br.Msg = "请选择图表样式类型"
		br.ErrMsg = "请选择图表样式类型"
		br.IsSendEmail = false
		return
	}
	list, err := chart_theme.GetChartThemeItemList(chartThemeTypeId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

	// 兼容历史数据，加入新字段LineOptionList
	for i, v := range list {
		newConfig, e := data.ConvertOldChartOptions(v.Config)
		if e != nil {
			continue
		}
		list[i].Config = newConfig
	}


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

// TypeList
// @Title 获取主题类型列表
// @Description 获取主题类型列表接口
// @Success 200 {object} []*chart_theme.ChartThemeType
// @router /chart/theme/type/list [get]
func (c *ChartThemeController) TypeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	list, err := chart_theme.GetAllChartThemeTypeList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

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

// GetThemePreviewData
// @Title 获取默认的预览图表数据
// @Description 获取默认的预览图表数据接口
// @Param   ChartThemeTypeId   query   int  true       "图表主题类型id"
// @Success 200 {object} data_manage.ChartInfoDetailResp
// @router /chart/theme/preview_data [get]
func (c *ChartThemeController) GetThemePreviewData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	chartThemeTypeId, _ := c.GetInt("ChartThemeTypeId")
	if chartThemeTypeId <= 0 {
		br.Msg = "请选择图表样式类型"
		br.ErrMsg = "请选择图表样式类型"
		br.IsSendEmail = false
		return
	}

	chartThemeType, err := chart_theme.GetChartThemeTypeById(chartThemeTypeId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

	dateType := 3 // 曲线图
	startYear := 5

	chartType := chartThemeType.ChartType

	chartInfo := new(data_manage.ChartInfoView)
	// 图表额外数据参数
	extraConfigStr := ``

	// 开始时间，结束时间
	var tmpStartDate, tmpEndDate string

	edbInfoIdList := make([]int, 0) // 指标列表
	switch chartType {
	case 1: // 曲线图
		edbInfoIdList = []int{1, 2, 3, 4, 5}
		chartInfo.ChartName = "曲线图"
	case 4: // 堆积柱状图
		edbInfoIdList = []int{1, 2, 3, 4, 5}
		chartInfo.ChartName = "堆积柱状图"
		dateType = 5
		tmpStartDate = `2021-03-05`
	case 6: // 组合图
		edbInfoIdList = []int{1, 2, 3, 4, 5}
		chartInfo.ChartName = "组合图"
		dateType = 5
		tmpStartDate = `2021-03-05`
	case 2: // 季节性
		dateType = 20 // 季节性图
		edbInfoIdList = []int{6}
		chartInfo.ChartName = "季节性图"
	case 5: // 散点图
		edbInfoIdList = []int{7, 8}
		chartInfo.ChartName = "散点图"
	case 7: // 柱形图
		edbInfoIdList = []int{1, 2, 3, 4, 5}
		extraConfigStr = `{"EdbInfoIdList":[{"EdbInfoId":1,"Name":"指标1","NameEn":"","Source":0},{"EdbInfoId":2,"Name":"指标2","NameEn":"","Source":0},{"EdbInfoId":3,"Name":"指标3","NameEn":"","Source":0},{"EdbInfoId":4,"Name":"指标4","NameEn":"","Source":0},{"EdbInfoId":5,"Name":"指标5","NameEn":"","Source":0}],"DateList":[{"Type":2,"Date":"","Value":100,"Color":"","Name":""},{"Type":1,"Date":"","Value":0,"Color":"","Name":""}],"Sort":{"Sort":0,"DateIndex":0},"XEdbList":null,"YEdbList":null,"Unit":"千桶","UnitEn":""}`
		chartInfo.ChartName = "柱形图"
	case 10: // 截面散点图
		edbInfoIdList = []int{9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
		extraConfigStr = `{"XName":"123","XNameEn":"123","XUnitName":"无","XUnitNameEn":"none","YName":"321","YNameEn":"321","YUnitName":"无","YUnitNameEn":"none","XMinValue":"230","XMaxValue":"395","YMinValue":"380","YMaxValue":"850","SeriesList":[{"Name":"2021-11-21","NameEn":"2021-11-21","IsNameDefault":true,"Color":"","EdbInfoList":[{"XEdbInfoId":9,"YEdbInfoId":14,"Name":"指标1","NameEn":"","XDateType":1,"XDate":"","XDateValue":0,"YDateType":1,"YDate":"","YDateValue":0,"IsShow":false},{"XEdbInfoId":10,"YEdbInfoId":15,"Name":"指标2","NameEn":"指标2","XDateType":1,"XDate":"","XDateValue":0,"YDateType":1,"YDate":"","YDateValue":0,"IsShow":false},{"XEdbInfoId":11,"YEdbInfoId":16,"Name":"指标3","NameEn":"","XDateType":1,"XDate":"","XDateValue":0,"YDateType":1,"YDate":"","YDateValue":0,"IsShow":false},{"XEdbInfoId":12,"YEdbInfoId":17,"Name":"指标4","NameEn":"指标4","XDateType":1,"XDate":"","XDateValue":0,"YDateType":1,"YDate":"","YDateValue":0,"IsShow":false},{"XEdbInfoId":13,"YEdbInfoId":18,"Name":"指标5","NameEn":"","XDateType":1,"XDate":"","XDateValue":0,"YDateType":1,"YDate":"","YDateValue":0,"IsShow":false}],"ShowTrendLine":false,"ShowFitEquation":false,"ShowRSquare":false}]}`
		chartInfo.ChartName = "截面散点图"
	case utils.CHART_TYPE_RADAR:
		edbInfoIdList = []int{19, 20, 21, 22, 23, 24}
		chartInfo.LeftMin = "10000"
		chartInfo.LeftMax = "60000"
		extraConfigStr = `{"DateList":[{"Type":3,"Date":"2023-11-01","Value":0,"Color":"","Name":""},{"Type":1,"Date":"","Value":0,"Color":"","Name":""}]}`
		chartInfo.ChartName = "雷达图"
	default:
		br.Msg = "暂不支持该类型"
		br.IsSendEmail = false
		return
	}
	calendar := "公历"

	mappingList, err := chart_theme.GetChartEdbMappingListByEdbInfoId(edbInfoIdList)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表，指标信息失败，Err:" + err.Error()
		return
	}
	switch chartType {
	case 6: // 组合图
		mappingList[0].ChartStyle = "spline"
		mappingList[1].ChartStyle = "spline"
		mappingList[2].ChartStyle = "spline"
		mappingList[3].ChartStyle = "column"
		mappingList[4].ChartStyle = "column"
	}
	chartInfo.Source = chartThemeType.ChartSource
	chartInfo.ChartType = chartThemeType.ChartType

	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, tmpStartDate, tmpEndDate, startYear, yearMax)

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

	switch chartType {
	case 6: // 组合图
		edbList[0].MaxData = 1000
	case 4: // 堆积柱状图
		edbList[0].MaxData = 2500
	}

	// 单位
	if chartType == utils.CHART_TYPE_BAR && len(yDataList) > 0 {
		chartInfo.Unit = yDataList[0].Unit
		chartInfo.UnitEn = yDataList[0].UnitEn
	}

	resp := new(data_manage.ChartInfoDetailResp)
	resp.ChartInfo = chartInfo
	resp.EdbInfoList = edbList
	resp.XEdbIdValue = xEdbIdValue
	resp.YDataList = yDataList
	resp.DataResp = dataResp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp

}

// Add
// @Title 新增主题
// @Description
// @Param	request	body request.DeleteThemeConfReq true "type json string"
// @Success 200 Ret=200 添加成功
// @router /chart/theme/add [post]
func (c *ChartThemeController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.AddThemeReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ChartThemeTypeId <= 0 {
		br.Msg = "请选择图表类型"
		br.IsSendEmail = false
		return
	}

	req.ChartThemeName = utils.TrimLRStr(req.ChartThemeName)
	if req.ChartThemeName == `` {
		br.Msg = "请输入主题名称"
		br.IsSendEmail = false
		return
	}

	// 获取系统默认配置
	systemChartTheme, err := chart_theme.GetSystemChartTheme(req.ChartThemeTypeId)
	if err != nil {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，查询系统默认配置异常，Err:" + err.Error()
		return
	}

	chartTheme := &chart_theme.ChartTheme{
		ChartThemeId:     0,
		ChartThemeName:   req.ChartThemeName,
		ChartThemeTypeId: req.ChartThemeTypeId,
		Config:           systemChartTheme.Config,
		ChartImage:       systemChartTheme.ChartImage,
		IsDelete:         0,
		SysUserId:        sysUser.AdminId,
		SysUserRealName:  sysUser.RealName,
		ModifyTime:       time.Now(),
		CreateTime:       time.Now(),
	}

	// 添加入库
	err = chartTheme.Add()
	if err != nil {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "添加成功"
}

// Edit
// @Title 新增主题
// @Description
// @Param	request	body request.DeleteThemeConfReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /chart/theme/edit [post]
func (c *ChartThemeController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.EditThemeReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ChartThemeId < 0 {
		br.Msg = "请选择配置"
		br.IsSendEmail = false
		return
	}

	// 获取配置
	chartTheme, err := chart_theme.GetChartThemeId(req.ChartThemeId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "主题不存在或已删除"
			br.ErrMsg = "主题不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表配置信息失败，Err:" + err.Error()
		}
		return
	}

	// 更新
	if req.ChartThemeName != `` {
		chartTheme.ChartThemeName = req.ChartThemeName
	}
	if req.Config != `` {
		chartTheme.Config = req.Config
	}
	if req.ChartImage != `` {
		chartTheme.ChartImage = req.ChartImage
	}
	chartTheme.ModifyTime = time.Now()
	err = chartTheme.Update([]string{"ChartThemeName", "Config", "ChartImage", "ModifyTime"})
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
}

// Delete
// @Title 删除主题
// @Description
// @Param	request	body request.DeleteThemeConfReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /chart/theme/delete [post]
func (c *ChartThemeController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.DeleteThemeReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ChartThemeId < 0 {
		br.Msg = "请选择配置"
		br.IsSendEmail = false
		return
	}

	// 获取配置
	chartTheme, err := chart_theme.GetChartThemeId(req.ChartThemeId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "主题不存在或已删除"
			br.ErrMsg = "主题不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表配置信息失败，Err:" + err.Error()
		}
		return
	}
	if chartTheme.IsSystemTheme == 1 {
		br.Msg = "系统默认配置，无法删除"
		br.ErrMsg = "系统默认配置，无法删除"
		br.IsSendEmail = false
		return
	}

	// 根据给定的图表主题类型ID获取图表主题类型
	chartThemeType, err := chart_theme.GetChartThemeTypeById(chartTheme.ChartThemeTypeId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表主题类型信息失败，Err:" + err.Error()
		return
	}

	// 判断是否是配置为默认设置，如果已经设置了，那么不能删除
	if chartThemeType.DefaultChartThemeId == chartTheme.ChartThemeId {
		br.Msg = "该主题已经配置为默认设置，不允许删除"
		br.ErrMsg = "该主题已经配置为默认设置，不允许删除"
		br.IsSendEmail = false
		return
	}

	// 更新
	chartTheme.IsDelete = 1
	err = chartTheme.Update([]string{"IsDelete"})
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// SetDefaultTheme
// @Title 配置默认主题
// @Description 配置默认主题
// @Param	request	body request.DeleteThemeConfReq true "type json string"
// @Success 200 Ret=200 配置成功
// @router /chart/theme/set_default [post]
func (c *ChartThemeController) SetDefaultTheme() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.SetDefaultThemeReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ChartThemeId < 0 {
		br.Msg = "请选择配置"
		br.IsSendEmail = false
		return
	}
	if req.ChartThemeTypeId < 0 {
		br.Msg = "请选择图表类型"
		br.IsSendEmail = false
		return
	}

	// 获取图表配置
	chartTheme, err := chart_theme.GetChartThemeId(req.ChartThemeId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "主题不存在或已删除"
			br.ErrMsg = "主题不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表配置信息失败，Err:" + err.Error()
		}
		return
	}

	// 获取图表类型
	chartThemeType, err := chart_theme.GetChartThemeTypeById(req.ChartThemeTypeId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "获取图表类型不存在或已删除"
			br.ErrMsg = "获取图表类型不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表配置信息失败，Err:" + err.Error()
		}
		return
	}

	// 判断主题与图表类型是否相符
	if chartTheme.ChartThemeTypeId != chartThemeType.ChartThemeTypeId {
		br.Msg = "主题与图表类型不符"
		br.ErrMsg = "主题与图表类型不符"
		br.IsSendEmail = false
		return
	}

	// 更新
	chartThemeType.DefaultChartThemeId = chartTheme.ChartThemeId
	chartThemeType.ModifyTime = time.Now()
	err = chartThemeType.Update([]string{"DefaultChartThemeId", "ModifyTime"})
	if err != nil {
		br.Msg = "配置失败"
		br.ErrMsg = "配置失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "配置成功"
}

// TypeListBySource
// @Title 根据来源获取主题类型列表
// @Description 获取主题类型列表接口
// @Param   Source   query   int  true       "图表主题类型id"
// @Success 200 {object} []*chart_theme.ChartThemeType
// @router /chart/theme/type/list_by_source [get]
func (c *ChartThemeController) TypeListBySource() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	source, _ := c.GetInt("Source")
	if source <= 0 {
		br.Msg = "请选择来源"
		br.ErrMsg = "请选择来源"
		br.IsSendEmail = false
		return
	}

	list, err := chart_theme.GetChartThemeTypeListBySource(source)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

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

// ListBySource
// @Title 根据来源获取主题列表
// @Description 获取主题列表接口
// @Param   ChartType   query   int  true       "图表类型"
// @Param   Source   query   int  true       "来源"
// @Success 200 {object} []*chart_theme.ChartTheme
// @router /chart/theme/list_by_source [get]
func (c *ChartThemeController) ListBySource() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	chartType, _ := c.GetInt("ChartType")
	if chartType < 0 {
		br.Msg = "请选择图表类型"
		br.ErrMsg = "请选择图表类型"
		br.IsSendEmail = false
		return
	}
	source, _ := c.GetInt("Source")
	if chartType < 0 {
		br.Msg = "请选择图表来源"
		br.ErrMsg = "请选择图表来源"
		br.IsSendEmail = false
		return
	}

	chartThemeType, err := chart_theme.GetChartThemeTypeByChartTypeAndSource(chartType, source)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

	list, err := chart_theme.GetChartThemeItemList(chartThemeType.ChartThemeTypeId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表样式类型信息失败，Err:" + err.Error()
		return
	}

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