package data_manage

import (
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strconv"
	"strings"
	"time"
)

type ChartRangeAnalysisExtraConf struct {
	EdbInfoMode           int                                `description:"指标模式 0: 单指标，1: 多指标"`
	DateRangeType         int                                `description:"区间划分类型 0：智能划分，1:手工划分，2：跨年划分"`
	AutoDateConf          ChartRangeAnalysisAutoDateConf     `description:"智能划分时间区间配置"`
	ManualDateConf        []ChartRangeAnalysisManualDateConf `description:"手工划分时间区间配置"`
	YearDateConf          ChartRangeAnalysisYearDateConf     `description:"跨年划分时间区间配置"`
	CalculateType         int                                `description:"计算类型 0: 区间均值，1: 区间累计值，2：区间涨幅，3：区间年化增长率，4：区间最大值，5：区间最小值"`
	UnNormalDataDealType  int                                `description:"异常值处理配置 0：不处理，1:剔除，2替换"`
	UnNormalDataConf      ChartRangeAnalysisDeleteDataConf
	DataConvertType       int                               `description:"数据转换类型 0不转, 1乘 2除 3对数"`
	DataConvertConf       ChartRangeAnalysisDataConvertConf `description:"数据转换详情"`
	SeriesName            string                            `description:"指标系列名称"`
	EdbInfoType           int                               `description:"指标类型：0普通指标，1预测指标"`
	MultipleGraphConfigId int                               `description:"配置ID"`
}

type ChartRangeAnalysisAutoDateChangeConf struct {
	BaseDateType int `description:"基准日期类型：0指标日期，1系统日期"`
	MoveForward  int `description:"前移的期数"`
	DateChange   []*EdbDataDateChangeConf
}

type EdbDataDateChangeConf struct {
	Year         int
	Month        int
	Day          int
	Frequency    string `description:"频度变换"`
	FrequencyDay string `description:"频度的固定日期"`
	ChangeType   int    `description:"日期变换类型1日期位移，2指定频率"`
}

type ChartRangeAnalysisDeleteDataConf struct {
	Formula      string  `description:"比较符号：=、>、<、>=、<="`
	Value        float64 `description:"比较的值"`
	ReplaceValue float64 `description:"替换的值"`
}

type ChartRangeAnalysisDataConvertConf struct {
	Value  float64 `description:"数据转换值"`
	Unit   string  `description:"数据转换单位"`
	EnUnit string  `description:"数据转换单位"`
}

type ChartRangeAnalysisManualDateConf struct { //手工划分
	StartDate string `description:"开始日期"`
	EndDate   string `description:"结束日期"`
}

type ChartRangeAnalysisAutoDateConf struct { //智能划分
	IsAutoStartDate int                                  `description:"起始日期是否是动态设置：0固定，1动态"`
	StartDate       string                               `description:"固定模式下的起始日期"`
	EndDate         string                               `description:"固定模式下的截止日期"`
	IsAutoEndDate   int                                  `description:"截止日期是否是动态设置：0固定，1动态"`
	StartDateConf   ChartRangeAnalysisAutoDateChangeConf `description:"动态起始日期配置"`
	EndDateConf     ChartRangeAnalysisAutoDateChangeConf `description:"动态截止日期配置"`
}

type ChartRangeAnalysisYearDateConf struct {
	StartDay string `description:"开始日"`
	EndDay   string `description:"结束日"`
}

// ChartRangeAnalysisPreviewReq 相关性图表请求体
type ChartRangeAnalysisPreviewReq struct {
	ExtraConfig      ChartRangeAnalysisExtraConf
	ChartEdbInfoList []*ChartSaveItem `description:"指标及配置信息"`
	DateType         int              `description:"日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间,6:起始日期至今 20:最近N年"`
	StartDate        string           `description:"自定义开始日期"`
	EndDate          string           `description:"自定义结束日期"`
	StartYear        int              `description:"当选择的日期类型为最近N年类型时，即date_type=20, 用start_year表示N"`
}

type ChartRangeAnalysisManualDateConfList []ChartRangeAnalysisManualDateConf

func (a ChartRangeAnalysisManualDateConfList) Len() int      { return len(a) }
func (a ChartRangeAnalysisManualDateConfList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ChartRangeAnalysisManualDateConfList) Less(i, j int) bool {
	return a[i].StartDate < a[j].StartDate
}

type ChartRangeAnalysisDataResp struct { //图表详情返回值
	*ChartRangeAnalysisExtraConf
	SeriesId     int `description:"指标系列ID"`
	ConfigEdbNum int `description:"生成的指标数"`
}

type ChartRangeAnalysisDateDataItem struct {
	StartDate time.Time
	EndDate   time.Time
	DataList  []*EdbDataList
}

// CreateRangeChartAndEdb 新增区间计算图表
func CreateRangeChartAndEdb(chartInfo *ChartInfo, edbMappingList []*ChartEdbMapping) (chartInfoId int, err error) {
	o := orm.NewOrmUsingDB("data")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 新增图表信息
	newId, err := tx.Insert(chartInfo)
	if err != nil {
		return
	}
	// 指标mapping
	chartInfo.ChartInfoId = int(newId)
	chartInfoId = int(newId)
	if len(edbMappingList) > 0 {
		for i := range edbMappingList {
			edbMappingList[i].ChartInfoId = chartInfoId
		}
		_, err = tx.InsertMulti(len(edbMappingList), edbMappingList)
		if err != nil {
			return
		}
	}
	return
}

// EditRangeChartInfoAndMapping 修改区间计算图表的 图表与指标 的关系
func EditRangeChartInfoAndMapping(req *EditChartInfoReq, edbInfoIdStr, lang string, calendar string, dateType, disabled int, barChartConf string) (err error) {
	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var pars []interface{}
	pars = append(pars, req.ChartName)
	pars = append(pars, req.ChartNameEn)
	pars = append(pars, edbInfoIdStr)
	pars = append(pars, req.ChartType)
	pars = append(pars, req.ChartClassifyId)
	pars = append(pars, disabled)
	pars = append(pars, barChartConf)
	pars = append(pars, req.ExtraConfig)
	pars = append(pars, req.StartYear)
	pars = append(pars, req.ChartThemeId)
	pars = append(pars, req.SourcesFrom)
	pars = append(pars, req.Instructions)
	pars = append(pars, req.MarkersLines)
	pars = append(pars, req.MarkersAreas)
	pars = append(pars, req.Unit)
	pars = append(pars, req.UnitEn)

	sql := ` UPDATE  chart_info
			SET
			  chart_name =?,
			  chart_name_en =?,
              edb_info_ids=?,
			  chart_type=?,
			  chart_classify_id = ?,
			  modify_time = NOW(),
              disabled = ?,
              bar_config = ?,
              extra_config = ?, 
 			  start_year = ?,
 			  chart_theme_id = ?,
 			  sources_from = ?,
 			  instructions = ?,
 			  markers_lines = ?,
 			  markers_areas = ?,
 			  unit = ?,
 			  unit_en = ?
			`
	if calendar != "" {
		sql += `,calendar = ? `
		pars = append(pars, calendar)
	}
	if dateType > 0 {
		sql += `,date_type = ? `
		pars = append(pars, dateType)
	}

	sql += `,start_date = ? `
	pars = append(pars, req.StartDate)

	sql += `,end_date = ? `
	pars = append(pars, req.EndDate)

	sql += `,season_start_date = ? `
	pars = append(pars, req.StartDate)

	sql += `,season_end_date = ? `
	pars = append(pars, req.EndDate)

	sql += `,left_min = ? `
	pars = append(pars, req.LeftMin)

	sql += `,left_max = ? `
	pars = append(pars, req.LeftMax)

	sql += `,right_min = ? `
	pars = append(pars, req.RightMin)

	sql += `,right_max = ? `
	pars = append(pars, req.RightMax)

	sql += `,right2_min = ? `
	pars = append(pars, req.Right2Min)

	sql += `,right2_max = ? `
	pars = append(pars, req.Right2Max)

	sql += `,min_max_save = ? `
	pars = append(pars, req.MinMaxSave)

	sql += `WHERE chart_info_id = ?`

	pars = append(pars, req.ChartInfoId)
	_, err = to.Raw(sql, pars).Exec()
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}
	chartEdbMappingIdList := make([]string, 0)
	for _, v := range req.ChartEdbInfoList {
		// 查询该指标是否存在,如果存在的话,那么就去修改,否则新增
		var tmpChartEdbMapping *ChartEdbMapping
		csql := `SELECT *  FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id=? AND source = ? `
		err = to.Raw(csql, req.ChartInfoId, v.EdbInfoId, utils.CHART_SOURCE_RANGE_ANALYSIS).QueryRow(&tmpChartEdbMapping)
		if err != nil && err.Error() != utils.ErrNoRow() {
			fmt.Println("QueryRow Err:", err.Error())
			return err
		}
		if tmpChartEdbMapping != nil {
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(tmpChartEdbMapping.ChartEdbMappingId))
			tmpChartEdbMapping.ModifyTime = time.Now()
			//tmpChartEdbMapping.MaxData = v.MaxData
			//tmpChartEdbMapping.MinData = v.MinData
			//tmpChartEdbMapping.IsOrder = v.IsOrder
			tmpChartEdbMapping.EdbAliasName = v.EdbAliasName
			tmpChartEdbMapping.IsAxis = v.IsAxis
			//tmpChartEdbMapping.EdbInfoType = v.EdbInfoType
			//tmpChartEdbMapping.LeadValue = v.LeadValue
			//tmpChartEdbMapping.LeadUnit = v.LeadUnit
			//tmpChartEdbMapping.ChartStyle = v.ChartStyle
			//tmpChartEdbMapping.ChartColor = v.ChartColor
			//tmpChartEdbMapping.PredictChartColor = v.PredictChartColor
			//tmpChartEdbMapping.ChartWidth = v.ChartWidth
			_, err = to.Update(tmpChartEdbMapping, "ModifyTime", "IsAxis", "EdbAliasName")
			if err != nil {
				fmt.Println("chart_edb_mapping Err:" + err.Error())
				return err
			}
		} else {
			mapItem := new(ChartEdbMapping)
			mapItem.ChartInfoId = req.ChartInfoId
			mapItem.EdbInfoId = v.EdbInfoId
			mapItem.EdbAliasName = v.EdbAliasName
			mapItem.IsAxis = v.IsAxis
			mapItem.CreateTime = time.Now()
			mapItem.ModifyTime = time.Now()
			timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
			mapItem.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp + "_" + strconv.Itoa(v.EdbInfoId))
			//mapItem.MaxData = v.MaxData
			//mapItem.MinData = v.MinData
			mapItem.IsOrder = true
			mapItem.EdbInfoType = 1
			//mapItem.LeadValue = v.LeadValue
			//mapItem.LeadUnit = v.LeadUnit
			//mapItem.ChartStyle = v.ChartStyle
			//mapItem.ChartColor = v.ChartColor
			//mapItem.PredictChartColor = v.PredictChartColor
			//mapItem.ChartWidth = v.ChartWidth
			mapItem.Source = utils.CHART_SOURCE_RANGE_ANALYSIS
			tmpId, err := to.Insert(mapItem)
			if err != nil {
				fmt.Println("AddChartEdbMapping Err:" + err.Error())
				return err
			}
			mapItem.ChartEdbMappingId = int(tmpId)
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(mapItem.ChartEdbMappingId))
		}
	}
	if len(chartEdbMappingIdList) > 0 {
		chartEdbMappingIdStr := strings.Join(chartEdbMappingIdList, ",")
		dsql := `DELETE FROM chart_edb_mapping WHERE chart_info_id=? AND chart_edb_mapping_id NOT IN(` + chartEdbMappingIdStr + `)`
		_, err = to.Raw(dsql, req.ChartInfoId).Exec()
		if err != nil {
			fmt.Println("delete err:" + err.Error())
			return err
		}
	}

	return
}

// EditRangeChartInfo 修改区间计算图表基本信息
func EditRangeChartInfo(req *SaveChartRangeReq) (err error) {
	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var pars []interface{}
	pars = append(pars, req.StartYear)

	sql := ` UPDATE  chart_info
			SET
			  modify_time = NOW(),
 			  start_year = ?
			`
	if req.DateType > 0 {
		sql += `,date_type = ? `
		pars = append(pars, req.DateType)
	}

	sql += `,start_date = ? `
	pars = append(pars, req.StartDate)

	sql += `,end_date = ? `
	pars = append(pars, req.EndDate)

	sql += `,left_min = ? `
	pars = append(pars, req.LeftMin)

	sql += `,left_max = ? `
	pars = append(pars, req.LeftMax)

	sql += `,right_min = ? `
	pars = append(pars, req.RightMin)

	sql += `,right_max = ? `
	pars = append(pars, req.RightMax)

	sql += `,right2_min = ? `
	pars = append(pars, req.Right2Min)

	sql += `,right2_max = ? `
	pars = append(pars, req.Right2Max)

	sql += `,min_max_save = ? `
	pars = append(pars, req.MinMaxSave)

	sql += `WHERE chart_info_id = ?`

	pars = append(pars, req.ChartInfoId)
	_, err = to.Raw(sql, pars).Exec()
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}

	return
}

// SaveChartRangeAnalysisEdbReq 指标保存请求
type SaveChartRangeAnalysisEdbReq struct {
	EdbInfoList           []*CalculateEdbInfoItem `description:"指标列表"`
	ExtraConfig           string
	MultipleGraphConfigId int  `description:"配置id"`
	IsSaveAs              bool `description:"是否另存为，true的话，就是另存为，不会建立与配置的关系"`
	EdbInfoType           int  `description:"指标类型"`
}

// ChartRangeAnalysisConfigEdbResp 指标列表
type ChartRangeAnalysisConfigEdbResp struct {
	EdbInfoList []*ChartRangeAnalysisConfigEdbItem `description:"指标列表"`
}

type ChartRangeAnalysisConfigEdbItem struct {
	EdbInfoId     int    `description:"指标id"`
	EdbName       string `description:"指标名称"`
	EdbNameEn     string `description:"指标名称"`
	Frequency     string `description:"频度"`
	Unit          string `description:"单位"`
	UnitEn        string `description:"单位"`
	ClassifyId    int    `description:"分类id"`
	FromEdbInfoId int    `description:"计算来源指标id"`
	EdbTypeInfo   int    `description:"指标类型，0普通指标，1预测指标"`
}

type SortEdbDataList []*EdbDataList

func (m SortEdbDataList) Len() int {
	return len(m)
}

func (m SortEdbDataList) Less(i, j int) bool {
	return m[i].DataTime > m[j].DataTime
}

func (m SortEdbDataList) Swap(i, j int) {
	m[i], m[j] = m[j], m[i]
}

type EditChartRangeBaseReq struct {
	ChartInfoId int    `description:"图表ID"`
	ChartName   string `description:"英文图表名称"`
}
type SaveChartRangeReq struct {
	ChartInfoId int    `description:"图表ID"`
	DateType    int    `description:"日期类型:1:00年至今,2:10年至今,3:15年至今，4：年初至今，5:自定义时间,6:起始日期至今，20:N年至今"`
	StartDate   string `description:"自定义开始日期"`
	EndDate     string `description:"自定义结束日期"`
	Calendar    string `description:"公历/农历"`
	LeftMin     string `description:"图表左侧最小值"`
	LeftMax     string `description:"图表左侧最大值"`
	RightMin    string `description:"图表右侧最小值"`
	RightMax    string `description:"图表右侧最大值"`
	Right2Min   string `description:"图表右侧最小值"`
	Right2Max   string `description:"图表右侧最大值"`
	MinMaxSave  int    `description:"是否手动保存过上下限：0-否；1-是"`
	StartYear   int    `description:"当选择的日期类型为最近N年类型时，即date_type=20, 用start_year表示N"`
}
