package data_manage

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

// MultipleGraphConfigChartMapping 图表与多图配置的关系表
type MultipleGraphConfigChartMapping struct {
	Id                    int       `orm:"column(id);pk"`
	MultipleGraphConfigId int       `description:"多图配置id"`
	ChartInfoId           int       `description:"图表id"`
	Source                int       `description:"来源,1:曲线图,2:相关性图;3:滚动相关性图1;4:滚动相关性图2;"`
	ModifyTime            time.Time `description:"最近一次修改时间"`
	CreateTime            time.Time `description:"添加时间"`
}

// AddMultipleGraphConfigChartMapping 新增多图配置
func AddMultipleGraphConfigChartMapping(item *MultipleGraphConfigChartMapping) (err error) {
	o := orm.NewOrmUsingDB("data")
	// 表格信息入库
	lastId, err := o.Insert(item)
	if err != nil {
		return
	}
	item.Id = int(lastId)
	return
}

// Update 更新 基础信息
func (item *MultipleGraphConfigChartMapping) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(item, cols...)
	return
}

// GetMultipleGraphConfigChartMappingByIdAndSource 根据配置id和来源获取关联关系
func GetMultipleGraphConfigChartMappingByIdAndSource(configId, source int) (item *MultipleGraphConfigChartMapping, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM multiple_graph_config_chart_mapping WHERE multiple_graph_config_id = ? AND source = ? `
	err = o.Raw(sql, configId, source).QueryRow(&item)

	return
}

// GetMultipleGraphConfigChartMappingByChartId 根据图表id和来源获取关联关系
func GetMultipleGraphConfigChartMappingByChartId(chartId int) (item *MultipleGraphConfigChartMapping, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM multiple_graph_config_chart_mapping WHERE chart_info_id = ?  `
	err = o.Raw(sql, chartId).QueryRow(&item)

	return
}

// GetMultipleGraphConfigChartMappingListById 根据配置id获取所有关联关系
func GetMultipleGraphConfigChartMappingListById(configId int) (items []*MultipleGraphConfigChartMapping, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT * FROM multiple_graph_config_chart_mapping WHERE multiple_graph_config_id = ? `
	_, err = o.Raw(sql, configId).QueryRows(&items)

	return
}

// ReplaceMultipleGraphConfigChartEdb 替换相关性分析配置中的指标
func ReplaceMultipleGraphConfigChartEdb(oldEdbInfo, newEdbInfo *EdbInfo) (replaceConfigTotal int, err error) {
	var errmsg string
	logMsg := `` // 记录替换的日志

	o := orm.NewOrmUsingDB("data")
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
			if logMsg != `` {
				utils.FileLog.Info(fmt.Sprintf("替换相关性分析中的指标记录 替换总数%d,旧的指标id:%d,新的指标id:%d;%s", replaceConfigTotal, oldEdbInfo.EdbInfoId, newEdbInfo.EdbInfoId, logMsg))
			}
		}
		if errmsg != "" {
			fmt.Println("errmsg:" + errmsg)
		}
		if err != nil && errmsg != "" {
			go alarm_msg.SendAlarmMsg("替换统计分析配置中的指标记录失败提醒,errmsg:"+errmsg, 3)
		}
	}()
	//替换multiple_graph_config中的指标
	multipleGraphConfigList := make([]*MultipleGraphConfig, 0)
	csql := `SELECT * FROM multiple_graph_config WHERE (edb_info_id_a=? or edb_info_id_b=?)`
	_, err = to.Raw(csql, oldEdbInfo.EdbInfoId, oldEdbInfo.EdbInfoId).QueryRows(&multipleGraphConfigList)
	if err != nil {
		errmsg = "获取指标关联图表配置信息失败:Err:" + err.Error()
		return
	}
	if len(multipleGraphConfigList) > 0 {
		replaceConfigTotal = len(multipleGraphConfigList)
		configIdMap := make(map[int]int)
		configIds := make([]int, 0)
		configIdStr := make([]string, 0)
		for _, mv := range multipleGraphConfigList {
			if _, ok := configIdMap[mv.MultipleGraphConfigId]; !ok {
				//判断如果达到1000个数,则执行更新语句
				configIds = append(configIds, mv.MultipleGraphConfigId)
				configIdStr = append(configIdStr, strconv.Itoa(mv.MultipleGraphConfigId))
				configIdMap[mv.MultipleGraphConfigId] = mv.MultipleGraphConfigId
				if len(configIds) >= 1000 {
					numStr := utils.GetOrmInReplace(len(configIds))
					//更新配置中的指标A
					sql := `UPDATE multiple_graph_config SET edb_info_id_a=?, modify_time=? WHERE edb_info_id_a=? and multiple_graph_config_id IN (` + numStr + `)`
					_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
					if err != nil {
						errmsg = "更新指标A关联图表配置信息失败:Err:" + err.Error()
						return
					}
					//更新配置中的指标B
					sql = `UPDATE multiple_graph_config SET edb_info_id_b=?, modify_time=? WHERE edb_info_id_b=? and multiple_graph_config_id IN (` + numStr + `)`
					_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
					if err != nil {
						errmsg = "更新指标B关联图表配置信息失败:Err:" + err.Error()
						return
					}

					// 更新
					// 更新指标id
					sql = `UPDATE multiple_graph_config_edb_mapping SET edb_info_id=?, modify_time=? WHERE edb_info_id=? and multiple_graph_config_id IN (` + numStr + `)`
					_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
					if err != nil {
						errmsg = "更新指标id关联图表配置信息失败:Err:" + err.Error()
						return
					}
					logMsg += `涉及到的配置id:` + strings.Join(configIdStr, ",") + ";"
					configIds = make([]int, 0)
					configIdStr = make([]string, 0)
				}
			}
		}
		if len(configIds) > 0 {
			numStr := utils.GetOrmInReplace(len(configIds))
			//更新配置中的指标A
			sql := `UPDATE multiple_graph_config SET edb_info_id_a=?, modify_time=? WHERE edb_info_id_a=? and multiple_graph_config_id IN (` + numStr + `)`
			_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
			if err != nil {
				errmsg = "更新指标A关联图表配置信息失败:Err:" + err.Error()
				return
			}
			//更新配置中的指标B
			sql = `UPDATE multiple_graph_config SET edb_info_id_b=?, modify_time=? WHERE edb_info_id_b=? and multiple_graph_config_id IN (` + numStr + `)`
			_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
			if err != nil {
				errmsg = "更新指标B关联图表配置信息失败:Err:" + err.Error()
				return
			}
			// 更新指标id
			sql = `UPDATE multiple_graph_config_edb_mapping SET edb_info_id=?, modify_time=? WHERE edb_info_id=? and multiple_graph_config_id IN (` + numStr + `)`
			_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId, configIds).Exec()
			if err != nil {
				errmsg = "更新指标id关联图表配置信息失败:Err:" + err.Error()
				return
			}

			logMsg += `涉及到的配置id:` + strings.Join(configIdStr, ",") + ";"
			configIds = make([]int, 0)
			configIdStr = make([]string, 0)
		}
	}

	// 更新相关性图表中的
	sql := `UPDATE chart_info_correlation SET edb_info_id_first=?, modify_time=? WHERE edb_info_id_first=?`
	_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId).Exec()
	if err != nil {
		errmsg = "更新相关性图表中的指标id关联失败:Err:" + err.Error()
		return
	}
	sql = `UPDATE chart_info_correlation SET edb_info_id_second=?, modify_time=? WHERE edb_info_id_second=?`
	_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId).Exec()
	if err != nil {
		errmsg = "更新相关性图表中的指标id关联失败:Err:" + err.Error()
		return
	}

	// 替换拟合方程曲线替换指标
	// 替换跨品种标签绑定得到指标ID
	sql = `UPDATE chart_tag_variety SET edb_info_id=?, modify_time=? WHERE edb_info_id=?`
	_, err = to.Raw(sql, newEdbInfo.EdbInfoId, time.Now(), oldEdbInfo.EdbInfoId).Exec()
	if err != nil {
		errmsg = "更新指标id关联跨品种分析标签失败:Err:" + err.Error()
		return
	}
	return
}

func RemoveMultiConfigChartMappingByChartInfoId(chartInfoId int) (err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `DELETE FROM multiple_graph_config_chart_mapping WHERE chart_info_id = ?`
	_, err = o.Raw(sql, chartInfoId).Exec()
	return
}