package excel

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/excel/request"
	"eta/eta_api/services/data"
	excel2 "eta/eta_api/services/data/excel"
	"strconv"
)

// GetSystemDate
// @Title 获取系统日期（包含计算日期）
// @Description 获取系统日期（包含计算日期）
// @Param	request	body request.MixedTableCellDataReq true "type json string"
// @router /excel_info/get_system_date [post]
func (c *ExcelInfoController) GetSystemDate() {
	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.MixedTableCellDataReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	date, err, errMsg := excel2.HandleDate(req.DataTimeType, req.Value)
	if err != nil {
		br.Msg = "获取系统日期失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "获取系统日期失败,Err:" + err.Error()
		return
	}

	type resp struct {
		Date string
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取系统日期成功"
	br.Data = resp{
		Date: date,
	}
}

// CalculateData
// @Title 公式计算（混合表格）
// @Description 公式计算（混合表格）
// @Param	request	body request.CalculateConf true "type json string"
// @router /excel_info/mixed/calculate [post]
func (c *ExcelInfoController) CalculateData() {
	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.CalculateConf
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
	if err != nil {
		br.Msg = "获取指标信息失败！"
		br.ErrMsg = "获取指标信息失败，Err:" + err.Error()
		return
	}

	dataList := make([]*data_manage.EdbDataList, 0)
	switch edbInfo.EdbInfoType {
	case 0:
		dataList, _ = data_manage.GetEdbDataList(edbInfo.Source, edbInfo.EdbInfoId, ``, ``)
	case 1:
		_, dataList, _, _, _, _ = data.GetPredictDataListByPredictEdbInfoId(edbInfo.EdbInfoId, ``, ``, false)
	default:
		br.Msg = "指标类型异常！"
		br.ErrMsg = "指标类型异常，Err:" + strconv.Itoa(edbInfo.EdbInfoType)
		return
	}

	//获取所有数据，计算所有数据
	//获取部分数据，计算部分数据
	// BaseCalculate 数据计算的结构体
	type BaseCalculate struct {
		DataList      []*data_manage.EdbDataList
		Frequency     string `description:"需要转换的频度"`
		Formula       interface{}
		Calendar      string `description:"公历/农历"`
		MoveType      int    `description:"移动方式:1:领先(默认),2:滞后"`
		MoveFrequency string `description:"移动频度"`
		FromFrequency string `description:"来源的频度"`
		Source        int    `description:"1：累计值转月；2：累计值转季；3：同比值；4：同差值；5：N数值移动平均数计算；6：环比值；7：环差值；8：升频；9：降频；10：时间移位；11：超季节性；12：年化；13：累计值；14：累计值年初至今；15：指数修匀；16：日均值"`
	}

	req2 := &BaseCalculate{
		DataList:      dataList,
		Frequency:     req.Frequency,
		Formula:       req.Formula,
		Calendar:      req.Calendar,
		MoveType:      req.MoveType,
		MoveFrequency: req.MoveFrequency,
		FromFrequency: edbInfo.Frequency,
		Source:        req.Source,
	}

	// 调用指标库去更新
	reqJson, tmpErr := json.Marshal(req2)
	if tmpErr != nil {
		err = tmpErr
		return
	}
	respItem, tmpErr := data.BaseCalculate(string(reqJson))
	if tmpErr != nil {
		err = tmpErr
		return
	}
	if respItem.Ret != 200 {
		br.Msg = respItem.Msg
		br.ErrMsg = respItem.ErrMsg
		return
	}

	// 数据处理成需要返回的样式
	num := 5
	lenDate := len(respItem.Data.DateList)
	if lenDate < 5 {
		num = lenDate
	}

	var currDate string // 当前日期
	dataListResp := make([]*data_manage.EdbDataList, 0)

	if req.DataTime == `` {
		for i := 1; i <= num; i++ {
			date := respItem.Data.DateList[lenDate-i]
			val, ok := respItem.Data.DataMap[date]
			if !ok {
				continue
			}

			dataListResp = append(dataListResp, &data_manage.EdbDataList{
				Value:    val,
				DataTime: date,
			})
		}
	} else {
		if val, ok := respItem.Data.DataMap[req.DataTime]; ok {
			for i, tmpDate := range respItem.Data.DateList {
				if tmpDate == req.DataTime {
					if i+3 <= lenDate {
						t1Date := respItem.Data.DateList[i+2]
						if tmpVal, ok2 := respItem.Data.DataMap[t1Date]; ok2 {
							// 当前日期
							dataListResp = append(dataListResp, &data_manage.EdbDataList{
								Value:    tmpVal,
								DataTime: t1Date,
							})
						}
					}

					if i+2 <= lenDate {
						t1Date := respItem.Data.DateList[i+1]
						if tmpVal, ok2 := respItem.Data.DataMap[t1Date]; ok2 {
							// 当前日期
							dataListResp = append(dataListResp, &data_manage.EdbDataList{
								Value:    tmpVal,
								DataTime: t1Date,
							})
						}
					}

					// 当前日期
					dataListResp = append(dataListResp, &data_manage.EdbDataList{
						Value:    val,
						DataTime: req.DataTime,
					})
					if i >= 1 {
						t1Date := respItem.Data.DateList[i-1]
						if tmpVal, ok2 := respItem.Data.DataMap[t1Date]; ok2 {
							// 当前日期
							dataListResp = append(dataListResp, &data_manage.EdbDataList{
								Value:    tmpVal,
								DataTime: t1Date,
							})
						}
					}
					if i >= 2 {
						t1Date := respItem.Data.DateList[i-2]
						if tmpVal, ok2 := respItem.Data.DataMap[t1Date]; ok2 {
							// 当前日期
							dataListResp = append(dataListResp, &data_manage.EdbDataList{
								Value:    tmpVal,
								DataTime: t1Date,
							})
						}
					}
				}
			}
		}
	}
	resp := data_manage.BeforeAndAfterDateDataResp{
		List: dataListResp,
		Date: currDate,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "计算成功"
	br.Data = resp
}
