package models

import (
	"eta/eta_index_lib/utils"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type EdbInfoRelation struct {
	EdbInfoRelationId  int       `orm:"column(edb_info_relation_id);pk"`
	EdbInfoId          int       `description:"指标id"`
	Source             int       `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,9:手工指标,10:隆众"`
	EdbName            string    `description:"指标名称"`
	EdbCode            string    `description:"指标编码"`
	ReferObjectId      int       `description:"引用对象ID（图表ID，ETA逻辑ID等）"`
	ReferObjectType    int       `description:"引用对象ID类型（1.图表，2.ETA逻辑）"`
	ReferObjectSubType int       `description:"引用对象子类"`
	CreateTime         time.Time `description:"创建时间"`
	ModifyTime         time.Time `description:"修改时间"`
	RelationTime       time.Time `description:"引用时间"`
	RelationType       int       `description:"引用类型，0:直接饮用，1间接引用"`
	RootEdbInfoId      int       `description:"间接引用时，关联的直接引用的指标ID"`
	ChildEdbInfoId     int       `description:"间接引用时，计算指标直接关联的指标ID"`
	RelationCode       string    `description:"引用标识"`
	ParentRelationId   int       `description:"间接引用关联的直接引用的ID"`
}

func (e *EdbInfoRelation) TableName() string {
	return "edb_info_relation"
}

// GetEdbInfoRelationByChildEdbInfoId 查询引用的指标ID
func GetEdbInfoRelationByChildEdbInfoId(edbInfoId int) (item *EdbInfoRelation, err error) {
	o := orm.NewOrm()
	msql := ` SELECT * FROM edb_info_relation WHERE child_edb_info_id = ? or edb_info_id=?`
	err = o.Raw(msql, edbInfoId, edbInfoId).QueryRow(&item)
	return
}

// GetEdbInfoRelationListByChildEdbInfoId 根据间接引用中的的计算指标ID查询引用列表
func GetEdbInfoRelationListByChildEdbInfoId(edbInfoId int) (items []*EdbInfoRelation, err error) {
	o := orm.NewOrm()
	msql := ` SELECT * FROM edb_info_relation WHERE relation_type=1 AND child_edb_info_id=?`
	_, err = o.Raw(msql, edbInfoId).QueryRows(&items)
	return
}

// GetEdbInfoRelationListByParentRelationId 根据间接引用中的的父级ID查询
func GetEdbInfoRelationEdbIdsByParentRelationId(relationId, edbInfoId int) (items []int, err error) {
	o := orm.NewOrm()
	msql := ` SELECT edb_info_id FROM edb_info_relation WHERE parent_relation_id=? AND child_edb_info_id=?`
	_, err = o.Raw(msql, relationId, edbInfoId).QueryRows(&items)
	return
}

// GetEdbInfoRelationByRelationIds 查询引用的指标ID
func GetEdbInfoRelationByRelationIds(ids []int) (items []*EdbInfoRelation, err error) {
	o := orm.NewOrm()
	msql := ` SELECT * FROM edb_info_relation WHERE edb_info_relation_id in (` + utils.GetOrmInReplace(len(ids)) + `) `
	_, err = o.Raw(msql, ids).QueryRows(&items)
	return
}

// UpdateSecondRelationEdbInfoId 更新指标替换后的间接引用记录
func UpdateSecondRelationEdbInfoId(edbRelationIds []int, relationList []*EdbInfoRelation, refreshEdbInfoIds []int, indexCodeList []string) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
			return
		}
		_ = o.Commit()
	}()
	// 删除相关的间接引用
	sql := ` DELETE FROM edb_info_relation WHERE relation_type=1 and parent_relation_id in (` + utils.GetOrmInReplace(len(edbRelationIds)) + `)`
	_, err = o.Raw(sql, edbRelationIds).Exec()
	if err != nil {
		return
	}

	// 新增间接引用
	relationCodesMap := make(map[string]struct{}, 0)
	if len(relationList) > 0 {
		for _, relation := range relationList {
			if relation.RelationType == 1 {
				relationCodesMap[relation.RelationCode] = struct{}{}
			}
		}
		_, err = o.InsertMulti(len(relationList), relationList)
		if err != nil {
			return
		}
	}

	if len(refreshEdbInfoIds) > 0 {
		// todo 更新指标的刷新状态
		sql = ` UPDATE edb_info SET no_update = 0 WHERE  edb_info_id IN (` + utils.GetOrmInReplace(len(refreshEdbInfoIds)) + `) AND no_update = 1`
		_, err = o.Raw(sql, refreshEdbInfoIds).Exec()
		if err != nil {
			return
		}
	}

	//更新数据源钢联化工指标
	if len(indexCodeList) > 0 {
		// 更改数据源的更新状态
		sql = ` UPDATE base_from_mysteel_chemical_index SET is_stop = 0 WHERE index_code IN (` + utils.GetOrmInReplace(len(indexCodeList)) + `) and is_stop=1`
		_, err = o.Raw(sql, indexCodeList).Exec()
		if err != nil {
			return
		}
	}
	if len(relationList) > 0 {
		// 更新间接引用指标的关联ID
		relationCodes := make([]string, 0)
		for relationCode := range relationCodesMap {
			relationCodes = append(relationCodes, relationCode)
		}
		if len(relationCodes) > 0 {
			sql := ` UPDATE edb_info_relation e1  
JOIN edb_info_relation e2 ON e1.relation_code = e2.relation_code   
SET e1.parent_relation_id = e2.edb_info_relation_id  
WHERE  
    e1.relation_type = 1   
    AND e2.relation_type = 0 AND e1.parent_relation_id !=e2.edb_info_relation_id AND e1.relation_code in (` + utils.GetOrmInReplace(len(relationCodes)) + `)`
			_, err = o.Raw(sql, relationCodes).Exec()
			if err != nil {
				return
			}
		}
	}
	return
}
