package data_manage

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/edb_refresh"
	"eta/eta_api/models/data_manage/edb_refresh/request"
	"eta/eta_api/services/data"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
)

// RefreshSourceList
// @Title 获取指标刷新配置的来源接口
// @Description 获取指标刷新配置的来源接口
// @Success Ret=200 获取成功
// @router /edb_info/refresh/source_list [get]
func (c *EdbInfoController) RefreshSourceList() {
	br := new(models.BaseResponse).Init()

	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	item := edb_refresh.EdbRefreshSource{}
	tmpList, err := item.GetAllList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取刷新数据源失败, Err: " + err.Error()
		return
	}

	list := make([]edb_refresh.EdbRefreshSourceList, 0)
	tmpMap := make(map[int]edb_refresh.EdbRefreshSourceList, 0)

	for _, v := range tmpList {
		tmp, ok := tmpMap[v.Source]
		if ok {
			continue
		}
		tmp = edb_refresh.EdbRefreshSourceList{
			Source:       v.Source,
			SourceName:   v.SourceName,
			SourceNameEn: v.SourceNameEn,
			//SubSource:     v.SubSource,
			//SubSourceName: v.SubSourceName,
			Child:    make([]edb_refresh.EdbRefreshSourceList, 0),
			HasChild: v.HasChild,
		}

		if v.HasChild == 1 {
			for _, v2 := range tmpList {
				if v2.Source == v.Source {
					tmp.Child = append(tmp.Child, edb_refresh.EdbRefreshSourceList{
						Source:          v2.Source,
						SourceName:      v2.SourceName,
						SubSource:       v2.SubSource,
						SubSourceName:   v2.SubSourceName,
						SourceNameEn:    v2.SourceNameEn,
						SubSourceNameEn: v2.SubSourceNameEn,
						HasChild:        0,
					})
				}
			}
		}

		tmpMap[v.Source] = tmp
		list = append(list, tmp)
	}

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

// RefreshClassifyList
// @Title 获取指标分类列表接口
// @Description 获取指标分类列表接口
// @Param   Source   query   int  true       "来源:1:同花顺,2:wind,3:彭博"
// @Success Ret=200 获取成功
// @router /edb_info/refresh/classify_list [get]
func (c *EdbInfoController) RefreshClassifyList() {
	br := new(models.BaseResponse).Init()

	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	source, _ := c.GetInt("Source", utils.DATA_SOURCE_MYSTEEL_CHEMICAL)

	list := make([]*edb_refresh.BaseClassifyItems, 0)
	switch source {
	case utils.DATA_SOURCE_MYSTEEL_CHEMICAL: // 钢联
		rootList, err := data_manage.GetBaseFromMysteelChemicalClassifyByParentId(0)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		classifyAll, err := data_manage.GetAllBaseFromMysteelChemicalClassify()
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		rootChildMap := make(map[int][]*edb_refresh.BaseClassifyItems)

		for _, v := range classifyAll {
			//tmpList, ok := rootChildMap[v.ParentId]
			//if !ok {
			//	tmpList = make([]data_manage.BaseClassifyItems, 0)
			//}
			//tmpList = append(tmpList, data_manage.BaseClassifyItems{
			//	ClassifyId:   v.BaseFromMysteelChemicalClassifyId,
			//	ClassifyName: v.ClassifyName,
			//	ParentId:     v.ParentId,
			//	UniqueCode:   fmt.Sprint(v.BaseFromMysteelChemicalClassifyId),
			//	Children:     nil,
			//})
			//rootChildMap[v.ParentId] = tmpList

			rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], &edb_refresh.BaseClassifyItems{
				ClassifyId:   v.BaseFromMysteelChemicalClassifyId,
				ClassifyName: v.ClassifyName,
				ParentId:     v.ParentId,
				UniqueCode:   fmt.Sprint(v.BaseFromMysteelChemicalClassifyId),
				Children:     nil,
			})
		}
		for _, v := range rootList {
			tmp := &edb_refresh.BaseClassifyItems{
				ClassifyId:   v.BaseFromMysteelChemicalClassifyId,
				ClassifyName: v.ClassifyName,
				ParentId:     v.ParentId,
				UniqueCode:   fmt.Sprint(v.BaseFromMysteelChemicalClassifyId),
				Children:     nil,
			}
			if existItems, ok := rootChildMap[v.BaseFromMysteelChemicalClassifyId]; ok {
				tmp.Children = existItems
			} else {
				items := make([]*edb_refresh.BaseClassifyItems, 0)
				tmp.Children = items
			}
			list = append(list, tmp)
		}

	case utils.DATA_SOURCE_YS: // 有色

		list = append(list, &edb_refresh.BaseClassifyItems{
			ClassifyId:   0,
			ClassifyName: "未分类",
			ParentId:     0,
			UniqueCode:   fmt.Sprint(0),
			Children:     nil,
		})
		rootList, err := data_manage.GetBaseFromSmmClassifyByParentId(0)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		classifyAll, err := data_manage.GetAllBaseFromSmmClassify()
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		rootChildMap := make(map[int][]*edb_refresh.BaseClassifyItems)
		for _, v := range classifyAll {
			rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], &edb_refresh.BaseClassifyItems{
				ClassifyId:   v.ClassifyId,
				ClassifyName: v.ClassifyName,
				ParentId:     v.ParentId,
				UniqueCode:   fmt.Sprint(v.ClassifyId),
				Children:     nil,
			})
		}
		for _, v := range rootList {
			tmp := &edb_refresh.BaseClassifyItems{
				ClassifyId:   v.ClassifyId,
				ClassifyName: v.ClassifyName,
				ParentId:     v.ParentId,
				UniqueCode:   fmt.Sprint(v.ClassifyId),
				Children:     nil,
			}
			if existItems, ok := rootChildMap[v.ClassifyId]; ok {
				tmp.Children = existItems
			} else {
				items := make([]*edb_refresh.BaseClassifyItems, 0)
				tmp.Children = items
			}
			list = append(list, tmp)

		}

	default:
		tmpList, err := data_manage.GetAllEdbClassify()
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		for _, v := range tmpList {
			list = append(list, &edb_refresh.BaseClassifyItems{
				ClassifyId:   v.ClassifyId,
				ClassifyName: v.ClassifyName,
				ParentId:     v.ParentId,
				UniqueCode:   fmt.Sprint(v.ClassifyId),
				Children:     nil,
			})
		}
		list = buildTree(list, 0)
		//fmt.Println(result)
	}

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

// 生成多层级列表的递归函数
func buildTree(items []*edb_refresh.BaseClassifyItems, parentId int) []*edb_refresh.BaseClassifyItems {
	var result []*edb_refresh.BaseClassifyItems

	// 遍历所有分类项
	for i := range items {
		// 找到当前节点的子节点
		if items[i].ParentId == parentId {
			// 递归构建子节点的子节点
			items[i].Children = buildTree(items, items[i].ClassifyId)
			// 将当前节点添加到结果中
			result = append(result, items[i])
		}
	}

	return result
}

// RefreshEdbList
// @Title 获取待配置的指标列表接口
// @Description 获取待配置的指标列表接口
// @Param   Source   query   int  true       "来源:1:同花顺,2:wind,3:彭博"
// @Param   SubSource   query   int  true       "来源:0:经济数据库,1:日期序列"
// @Param   ClassifyId   query   string  false             "分类ID，支持多选，用英文,隔开"
// @Param   TerminalCode   query   string  false       "终端编码"
// @Param   SysUserId   query   string  false       "创建人，支持多选，用英文,隔开"
// @Param   Frequency   query   string  false       "频度，支持多选，用英文,隔开"
// @Param   Keyword   query   string  false       "关键词"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'data_time':日期"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} data_manage.RefreshBaseEdbInfoResp
// @router /edb_info/refresh/edb_list [get]
func (c *EdbInfoController) RefreshEdbList() {
	br := new(models.BaseResponse).Init()

	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	source, _ := c.GetInt("Source")
	subSource, _ := c.GetInt("SubSource")
	classifyId := c.GetString("ClassifyId")
	terminalCode := c.GetString("TerminalCode")
	sysUserId := c.GetString("SysUserId")
	frequency := c.GetString("Frequency")
	keyword := c.GetString("Keyword")
	status := c.GetString("Status")

	sortParam := c.GetString("SortParam")
	sortType := c.GetString("SortType")

	switch sortParam {
	case "end_date":
	default:
		sortParam = " end_date "
	}
	switch sortType {
	case "desc", "asc":
	default:
		sortType = "desc"
	}

	pageSize, _ := c.GetInt("PageSize")
	currentIndex, _ := c.GetInt("CurrentIndex")
	var startSize int

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	total, list, err := data.GetList(source, subSource, classifyId, terminalCode, sysUserId, frequency, keyword, status, startSize, pageSize, sortParam, sortType)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)

	resp := data_manage.RefreshBaseEdbInfoResp{
		Paging: page,
		List:   list,
	}

	// 刷新时间格式化
	list, err, errMsg, isSendEmail := data.HandleRefreshTime(source, subSource, list)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "保存失败，Err：" + err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

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

// GetEdbRefreshDefaultConfig
// @Title 获取待配置的指标列表接口
// @Description 获取待配置的指标列表接口
// @Param   Source   query   int  true       "来源:1:同花顺,2:wind,3:彭博"
// @Param   SubSource   query   int  true       "来源:0:经济数据库,1:日期序列"
// @Param   Frequency   query   string  false       "频度"
// @Success 200 {object} data_manage.RefreshBaseEdbInfoResp
// @router /edb_info/refresh/default_config [get]
func (c *EdbInfoController) GetEdbRefreshDefaultConfig() {
	br := new(models.BaseResponse).Init()

	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	source, _ := c.GetInt("Source")
	subSource, _ := c.GetInt("SubSource")
	frequency := c.GetString("Frequency")

	if source <= 0 {
		br.Msg = "来源不能为空"
		br.IsSendEmail = false
		return
	}

	// 非有色的来源，频度不能为空
	if source != utils.DATA_SOURCE_YS && frequency == `` {
		br.Msg = "频度不能为空"
		br.IsSendEmail = false
		return
	}

	list, err := edb_refresh.GetListBySourceAndFrequency(source, subSource, frequency)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = err.Error()
		return
	}

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

// SaveEdbRefreshDefaultConfig
// @Title 设置默认的指标刷新配置接口
// @Description 设置默认的指标刷新配置接口
// @Param	request	body data_manage.SaveEdbRefreshDefaultConfigReq true "type json string"
// @Success Ret=200 保存成功
// @router /edb_info/refresh/default_config/save [post]
func (c *EdbInfoController) SaveEdbRefreshDefaultConfig() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	// 保存
	err, errMsg, isSendEmail := data.SaveEdbRefreshDefaultConfig(req.Source, req.SubSource, req.Frequency, req.List)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "保存失败，Err：" + err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// SaveEdbRefreshConfig
// @Title 设置指标刷新配置接口
// @Description 设置指标刷新配置接口
// @Param	request	body data_manage.SaveEdbRefreshConfigReq true "type json string"
// @Success 200 {object} data_manage.RefreshBaseEdbInfoResp
// @router /edb_info/refresh/config/save [post]
func (c *EdbInfoController) SaveEdbRefreshConfig() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	// 保存
	err, errMsg, isSendEmail := data.SaveEdbRefreshConfig(req.Source, req.SubSource, req.ClassifyId, req.TerminalCode, req.Frequency, req.Keyword, req.Status, req.SysUserId, req.IsSelectAll, req.List, req.EdbSelectIdList, c.SysUser.AdminId, c.SysUser.RealName)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "保存失败，Err：" + err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// SaveEdbRefreshStatus
// @Title 设置指标刷新状态接口
// @Description 设置指标刷新状态接口
// @Param	request	body data_manage.SaveEdbRefreshStatusReq true "type json string"
// @Success 200 {object} data_manage.RefreshBaseEdbInfoResp
// @router /edb_info/refresh/status/save [post]
func (c *EdbInfoController) SaveEdbRefreshStatus() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

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

	if req.Source <= 0 {
		br.Msg = "来源不能为空"
		br.IsSendEmail = false
		return
	}

	edbIdList := make([]int, 0)
	edbCodeList := make([]string, 0)
	// 指标id列表
	if req.IsSelectAll {
		// 如果是列表全选
		_, edbList, err := data.GetList(req.Source, req.SubSource, req.ClassifyId, req.TerminalCode, req.SysUserId, req.Frequency, req.Keyword, req.Status, 0, 100000, "", "")
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		// 不配置的指标id
		notIdMap := make(map[int]int, 0)
		for _, v := range req.EdbSelectIdList {
			notIdMap[v] = v
		}

		for _, v := range edbList {
			_, ok := notIdMap[v.EdbInfoId]
			// 在不配置的指标id列表内的话，那就过滤
			if ok {
				continue
			}

			// 加入到待配置的指标列表id
			edbIdList = append(edbIdList, v.EdbInfoId)
			edbCodeList = append(edbCodeList, v.IndexCode)
		}
	} else {
		edbIdList = req.EdbSelectIdList
	}

	if len(edbIdList) <= 0 {
		br.Msg = "指标不能为空"
		br.IsSendEmail = false
		return
	}

	isStop := 0
	if req.ModifyStatus == `暂停` {
		isStop = 1
	}

	switch req.Source {
	case utils.DATA_SOURCE_MYSTEEL_CHEMICAL: // 钢联
		err = data_manage.ModifyMysteelChemicalUpdateStatus(edbIdList, edbCodeList, isStop)
	case utils.DATA_SOURCE_YS: // 有色
		err = data_manage.ModifySmmUpdateStatus(edbIdList, edbCodeList, isStop)
	default:
		err = data_manage.ModifyEdbInfoUpdateStatus(edbIdList, isStop)
	}
	if err != nil {
		br.Msg = `保存失败`
		br.ErrMsg = "保存失败，Err：" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// GetEdbRefreshEdbConfig
// @Title 获取单个指标的刷新配置列表接口
// @Description 获取单个指标的刷新配置列表接口
// @Param   Source   query   int  true       "来源:1:同花顺,2:wind,3:彭博"
// @Param   SubSource   query   int  true       "来源:0:经济数据库,1:日期序列"
// @Param   EdbInfoId   query   int  false       "指标id"
// @Success 200 {object} data_manage.RefreshBaseEdbInfoResp
// @router /edb_info/refresh/edb_config [get]
func (c *EdbInfoController) GetEdbRefreshEdbConfig() {
	br := new(models.BaseResponse).Init()

	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()

	source, _ := c.GetInt("Source")
	subSource, _ := c.GetInt("SubSource")
	edbInfoId, _ := c.GetInt("EdbInfoId")

	if source <= 0 {
		br.Msg = "来源不能为空"
		br.IsSendEmail = false
		return
	}

	if edbInfoId <= 0 {
		br.Msg = "指标不能为空"
		br.IsSendEmail = false
		return
	}

	// 获取指标的刷新配置列表
	list, err := edb_refresh.GetEdbRefreshConfigListBySourceAndeEdbInfoId(source, subSource, edbInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = err.Error()
		return
	}

	if len(list) > 0 {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = list
		return
	}

	// 如果没有找到该指标的配置，那么就查询默认配置

	var frequency string

	// 根据类型查找指标的频度信息
	switch source {
	case utils.DATA_SOURCE_MYSTEEL_CHEMICAL: // 钢联
		item, err := data_manage.GetBaseFromMysteelChemicalIndexByIndexId(edbInfoId)
		if err != nil {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = err.Error()
			return
		}
		frequency = item.Frequency
	case utils.DATA_SOURCE_YS: // 有色
		item, err := data_manage.GetSmmIndexById(edbInfoId)
		if err != nil {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = err.Error()
			return
		}
		frequency = item.Frequency
	default:
		item, err := data_manage.GetEdbInfoById(edbInfoId)
		if err != nil {
			br.Msg = "获取指标信息失败"
			br.ErrMsg = err.Error()
			return
		}
		frequency = item.Frequency
	}

	if frequency == `` {
		br.Msg = "获取的指标频度信息异常"
		br.IsSendEmail = false
		return
	}

	tmpList, err := edb_refresh.GetListBySourceAndFrequency(source, subSource, frequency)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = err.Error()
		return
	}
	list = make([]*edb_refresh.EdbRefreshConfigItem, 0)
	for _, v := range tmpList {
		list = append(list, &edb_refresh.EdbRefreshConfigItem{
			RefreshFrequency:    v.RefreshFrequency,
			RefreshFrequencyDay: v.RefreshFrequencyDay,
			RefreshTime:         v.RefreshTime,
			RefreshAllData:      v.RefreshAllData,
			RefreshDataNum:      v.RefreshDataNum,
		})
	}

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