123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401 |
- package models
- import (
- "encoding/json"
- "errors"
- "eta_gn/eta_index_lib/global"
- "eta_gn/eta_index_lib/utils"
- "fmt"
- "github.com/shopspring/decimal"
- "gorm.io/gorm"
- "strconv"
- "strings"
- "time"
- )
- // SavePredictCalculateKszs 预测扩散指数
- func SavePredictCalculateKszs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, relationCalculateEdbInfoIdList []EdbInfoCalculateEdbInfoIdReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
- to := global.DEFAULT_DmSQL.Begin()
- defer func() {
- if err != nil {
- to.Rollback()
- } else {
- to.Commit()
- }
- }()
- fmt.Println("reqEdbInfoId:", reqEdbInfoId)
- tagMap := make(map[string]int) //指标的标签map
- relationEdbInfoList := make([]*EdbInfo, 0)
- if reqEdbInfoId <= 0 {
- edbInfo = &EdbInfo{
- //EdbInfoId: 0,
- EdbInfoType: 1,
- SourceName: utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_KSZS,
- Source: utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS,
- EdbCode: edbCode,
- EdbName: edbName,
- EdbNameSource: edbName,
- Frequency: frequency,
- Unit: unit,
- //StartDate: "",
- //EndDate: "",
- ClassifyId: classifyId,
- SysUserId: sysUserId,
- SysUserRealName: sysUserRealName,
- UniqueCode: uniqueCode,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- MinValue: 0,
- MaxValue: 0,
- CalculateFormula: formula,
- EdbType: 2,
- Sort: GetAddEdbMaxSortByClassifyId(classifyId, utils.PREDICT_EDB_INFO_TYPE),
- MoveType: 0,
- MoveFrequency: "",
- NoUpdate: 0,
- ServerUrl: "",
- EdbNameEn: edbName,
- UnitEn: unit,
- LatestDate: "",
- LatestValue: 0,
- ChartImage: "",
- }
- tmpErr := to.Create(edbInfo).Error
- if tmpErr != nil {
- err = tmpErr
- return
- }
- //关联关系
- calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
- for _, v := range relationCalculateEdbInfoIdList {
- tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
- calculateMappingItem := new(EdbInfoCalculateMapping)
- calculateMappingItem.CreateTime = time.Now()
- calculateMappingItem.ModifyTime = time.Now()
- calculateMappingItem.Sort = 1
- calculateMappingItem.EdbCode = edbCode
- calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
- calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
- calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
- calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
- calculateMappingItem.FromSource = tmpEdbInfo.Source
- calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
- calculateMappingItem.FromTag = v.FromTag
- calculateMappingItem.Source = edbInfo.Source
- calculateMappingItem.SourceName = edbInfo.SourceName
- calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
- tagMap[v.FromTag] = v.EdbInfoId
- }
- err = to.CreateInBatches(calculateMappingItemList, 500).Error
- if err != nil {
- return
- }
- } else {
- edbInfo, err = GetEdbInfoById(reqEdbInfoId)
- if err != nil {
- if err.Error() == utils.ErrNoRow() {
- errMsg = `获取指标信息失败`
- }
- return
- }
- if edbInfo.EdbInfoType != 1 {
- errMsg = `该指标不是预测指标`
- err = errors.New(errMsg)
- return
- }
- //修改指标信息
- switch lang {
- case utils.EnLangVersion:
- edbInfo.EdbNameEn = edbName
- edbInfo.UnitEn = unit
- default:
- edbInfo.EdbName = edbName
- edbInfo.Unit = unit
- edbInfo.EdbNameSource = edbName
- }
- edbInfo.Frequency = frequency
- edbInfo.ClassifyId = classifyId
- edbInfo.CalculateFormula = formula
- edbInfo.ModifyTime = time.Now()
- err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
- if err != nil {
- return
- }
- //删除,计算指标关联的,基础指标的关联关系
- sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
- err = to.Exec(sql, edbInfo.EdbInfoId).Error
- if err != nil {
- err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
- return
- }
- //清空原有数据
- tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
- sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
- err = to.Exec(sql, edbInfo.EdbInfoId).Error
- if err != nil {
- return
- }
- //关联关系
- calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
- for _, v := range relationCalculateEdbInfoIdList {
- tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
- calculateMappingItem := new(EdbInfoCalculateMapping)
- calculateMappingItem.CreateTime = time.Now()
- calculateMappingItem.ModifyTime = time.Now()
- calculateMappingItem.Sort = 1
- calculateMappingItem.EdbCode = edbInfo.EdbCode
- calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
- calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
- calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
- calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
- calculateMappingItem.FromSource = tmpEdbInfo.Source
- calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
- calculateMappingItem.FromTag = v.FromTag
- calculateMappingItem.Source = edbInfo.Source
- calculateMappingItem.SourceName = edbInfo.SourceName
- calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
- tagMap[v.FromTag] = v.EdbInfoId
- }
- err = to.CreateInBatches(calculateMappingItemList, 500).Error
- if err != nil {
- return
- }
- }
- // 计算数据
- latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbCode, formula, tagMap)
- return
- }
- // RefreshAllPredictCalculateKszs 刷新全部预测扩散指数数据
- func RefreshAllPredictCalculateKszs(edbInfo *EdbInfo) (latestDateStr string, latestValue float64, err error) {
- edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
- if err != nil {
- return
- }
- tagMap := make(map[string]int)
- relationEdbInfoList := make([]*EdbInfo, 0)
- for _, v := range edbInfoCalculateDetailList {
- tagMap[v.FromTag] = v.FromEdbInfoId
- fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
- relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
- }
- to := global.DEFAULT_DmSQL.Begin()
- defer func() {
- if err != nil {
- to.Rollback()
- } else {
- to.Commit()
- }
- }()
- // 计算数据
- latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
- return
- }
- // refreshAllPredictCalculateKszs 刷新预测年化数据
- func refreshAllPredictCalculateKszs(to *gorm.DB, edbInfoId, source, subSource int, relationEdbInfoList []*EdbInfo, edbCode, calculateFormula string, tagMap map[string]int) (latestDateStr string, latestValue float64, err error) {
- edbInfoIdStr := strconv.Itoa(edbInfoId)
- tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS, subSource)
- // 获取扩散指标关联的指标id
- checkEdbInfoIdMap := make(map[int]int)
- {
- var config KszsConfig
- err = json.Unmarshal([]byte(calculateFormula), &config)
- if err != nil {
- return
- }
- if config.DateType == 1 {
- for _, tmpEdbInfoId := range tagMap {
- checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
- }
- } else {
- for _, v := range config.CheckList {
- if tmpEdbInfoId, ok := tagMap[v]; ok {
- checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
- }
- }
- }
- }
- //获取当前指标的所有数据
- existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
- if err != nil {
- return
- }
- //计算指标的map
- existDataMap := make(map[string]*EdbData, 0)
- removeDateMap := make(map[string]string)
- for _, v := range existDataList {
- existDataMap[v.DataTime] = v
- removeDateMap[v.DataTime] = ``
- }
- var latestDateTime time.Time //真实数据的最后日期
- var hasValLatestDateTime time.Time // 存在数据的真实日期(正常情况下,这两个值是相等的,除非出现一种情况:真实数据的最后日期当天 计算不出结果,那么 hasValLatestDateTime 不等于 latestDateTime)
- //获取来源指标的数据
- relationEdbDataMap := make(map[int]map[string]float64)
- // 获取选择指标的 需要数据的 开始日期和结束日期
- var startDate, endDate time.Time
- for _, v := range relationEdbInfoList {
- tmpLatestDate, _ := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
- if latestDateTime.IsZero() || latestDateTime.After(tmpLatestDate) {
- // 真实数据的最后日期
- latestDateTime = tmpLatestDate
- }
- tmpDataList, tmpErr := GetPredictEdbDataListAll(v, 1)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- if tmpDataList != nil {
- if _, ok2 := checkEdbInfoIdMap[v.EdbInfoId]; ok2 {
- lenTmpDataList := len(tmpDataList)
- if lenTmpDataList > 0 {
- tmpStartTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[0].DataTime, time.Local)
- tmpEndTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[lenTmpDataList-1].DataTime, time.Local)
- if startDate.IsZero() || tmpStartTime.Before(startDate) {
- startDate = tmpStartTime
- }
- if tmpEndTime.IsZero() || tmpEndTime.After(endDate) {
- endDate = tmpEndTime
- }
- }
- }
- // 用上期的数据补充当期的数据处理
- handleDataMap := make(map[string]float64)
- err = HandleDataByPreviousData(tmpDataList, handleDataMap)
- if err != nil {
- return
- }
- relationEdbDataMap[v.EdbInfoId] = handleDataMap
- }
- }
- addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
- var isAdd bool
- for currDate := startDate.AddDate(0, 0, 1); !currDate.After(endDate); currDate = currDate.AddDate(0, 0, 1) {
- currDateStr := currDate.Format(utils.FormatDate)
- //环差指数列表
- tmpValList := make([]float64, 0)
- for _, dataMap := range relationEdbDataMap {
- currVal, ok := dataMap[currDateStr]
- if !ok {
- continue
- }
- perVal, ok := dataMap[currDate.AddDate(0, 0, -1).Format(utils.FormatDate)]
- if !ok {
- continue
- }
- var tmpVal float64
- if currVal > perVal {
- tmpVal = 1
- } else if currVal == perVal {
- tmpVal = 0.5
- } else {
- tmpVal = 0
- }
- tmpValList = append(tmpValList, tmpVal)
- }
- lenTmpValList := len(tmpValList)
- if lenTmpValList <= 0 {
- continue
- }
- currValDeci := decimal.NewFromFloat(0)
- for _, tmpVal := range tmpValList {
- currValDeci = currValDeci.Add(decimal.NewFromFloat(tmpVal))
- }
- currVal, _ := currValDeci.Div(decimal.NewFromInt(int64(lenTmpValList))).Round(4).Float64()
- // 如果存在数据的真实日期为空,或者 当前日期 早于或等于 实际数据的日期,那么就给 存在数据的真实日期 赋值
- if hasValLatestDateTime.IsZero() || currDate.Before(latestDateTime) || currDate.Equal(latestDateTime) {
- latestValue = currVal
- hasValLatestDateTime = currDate
- }
- // 判断扩散指数指标是否存在数据
- if existData, ok := existDataMap[currDateStr]; ok {
- // 处理扩散指数数据的值
- existValStr := existData.Value
- existValDeci, tmpErr := decimal.NewFromString(existValStr)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existVal, _ := existValDeci.Round(4).Float64()
- // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
- if existVal != currVal {
- err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
- if err != nil {
- return
- }
- }
- } else {
- // 直接入库
- timestamp := currDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
- isAdd = true
- }
- delete(removeDateMap, currDateStr)
- }
- if isAdd {
- addSql = strings.TrimRight(addSql, ",")
- err = to.Exec(addSql).Error
- }
- // 移除不存在的日期数据
- if len(removeDateMap) > 0 {
- removeDateList := make([]string, 0) //需要移除的日期
- for k := range removeDateMap {
- removeDateList = append(removeDateList, k)
- }
- removeDateStr := strings.Join(removeDateList, `','`)
- removeDateStr = `'` + removeDateStr + `'`
- sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
- err = to.Exec(sql, edbInfoId).Error
- if err != nil {
- err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
- return
- }
- }
- // 真实数据的最后日期
- latestDateStr = hasValLatestDateTime.Format(utils.FormatDate)
- return
- }
|