瀏覽代碼

Merge branch 'chart/11.1' into debug

# Conflicts:
#	controllers/base_from_calculate.go
#	models/edb_data_calculate_ljztbpj.go
#	models/edb_data_calculate_time_shift.go
#	models/edb_data_calculate_zjpj.go
Roc 2 年之前
父節點
當前提交
af19fbd2d3

文件差異過大導致無法顯示
+ 681 - 135
controllers/base_from_calculate.go


+ 44 - 5
models/base_from_calculate.go

@@ -23,10 +23,13 @@ type EdbInfoCalculateSaveReq struct {
 	Unit             string `description:"单位"`
 	ClassifyId       int    `description:"分类id"`
 	CalculateFormula string `description:"计算公式"`
-	EdbInfoIdArr     []struct {
-		EdbInfoId int    `description:"指标id"`
-		FromTag   string `description:"指标对应标签"`
-	}
+	EdbInfoIdArr     []EdbInfoFromTag
+}
+
+// EdbInfoFromTag 计算指标的关联指标
+type EdbInfoFromTag struct {
+	EdbInfoId int    `description:"指标id"`
+	FromTag   string `description:"指标对应标签"`
 }
 
 // CalculateItems 计算(运算)指标信息
@@ -121,6 +124,42 @@ func AddCalculate(edbInfoIdArr []*EdbInfo, edbInfoId int, edbCode, formulaStr st
 	return
 }
 
+// GetCalculateEdbInfo 获取计算指标的关联指标id
+func GetCalculateEdbInfo(edbInfoId int) (from_edb_info_id string, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT GROUP_CONCAT(from_edb_info_id ORDER BY sort ASC SEPARATOR ',') AS from_edb_info_id 
+			FROM edb_info_calculate_mapping
+			WHERE edb_info_id=?
+			GROUP BY edb_info_id
+			 `
+	err = o.Raw(sql, edbInfoId).QueryRow(&from_edb_info_id)
+	return
+}
+
+// DeleteCalculateEdbInfo 删除指标信息
+func DeleteCalculateEdbInfo(edbInfoId int) (err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	sql := `DELETE FROM edb_data_calculate WHERE edb_info_id=?`
+	_, err = to.Raw(sql, edbInfoId).Exec()
+	if err != nil {
+		return
+	}
+	sql = `DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=?`
+	_, err = to.Raw(sql, edbInfoId).Exec()
+	return
+}
+
 // RefreshAllCalculate 刷新全部数据
 func RefreshAllCalculate(edbInfoIdArr []*EdbInfo, edbInfoId, source int, edbCode, formulaStr, startDate, endDate string, edbInfoIdBytes []string) (err error) {
 	o := orm.NewOrm()
@@ -152,7 +191,7 @@ func RefreshAllCalculate(edbInfoIdArr []*EdbInfo, edbInfoId, source int, edbCode
 		//	pars = append(pars, endDate)
 		//}
 		//fmt.Println("v.Source:", v.Source)
-		dataList, err := GetEdbDataListAll(condition, pars, v.Source, 1)
+		dataList, err := GetEdbDataListAllByTo(to, condition, pars, v.Source, 1)
 		if err != nil {
 			return err
 		}

+ 75 - 222
models/edb_data_calculate_bp.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateBp 变频
-func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -27,7 +27,7 @@ func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edb
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_BP
 		edbInfo.SourceName = "变频"
 		edbInfo.EdbCode = edbCode
@@ -45,9 +45,10 @@ func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edb
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 		//关联关系
 		{
 			calculateMappingItem := new(EdbInfoCalculateMapping)
@@ -55,7 +56,7 @@ func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edb
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -70,7 +71,10 @@ func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edb
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_BP)
 		fmt.Println("dataTableName:" + dataTableName)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
@@ -81,84 +85,14 @@ func AddCalculateBp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edb
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
-
-	addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	dataLen := len(dataList)
-	fmt.Println("dataLen:", dataLen)
+	err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-	for i := 0; i < dataLen; i++ {
-		//当期
-		currentItem := dataList[i]
-		currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-		var day int
-		var preItem *EdbInfoSearchData
-		var preDate time.Time
-		if i == 0 {
-			day = int(time.Now().Sub(currentDate).Hours() / float64(24))
-			preDate = time.Now()
-		} else {
-			j := i - 1
-			if j < dataLen {
-				preItem = dataList[j]
-				preDate, _ = time.Parse(utils.FormatDate, preItem.DataTime)
-				day = int(preDate.Sub(currentDate).Hours() / float64(24))
-				utils.FileLog.Info("preItem.DataTime:" + preItem.DataTime + ";currentItem.DataTime" + currentItem.DataTime)
-			}
-		}
-		for k := 0; k <= day; k++ {
-			needDay := preDate.AddDate(0, 0, -k)
-			needDayStr := needDay.Format(utils.FormatDate)
-			existKey := edbCode + needDayStr
-			if _, ok := existMap[existKey]; !ok {
-				timestamp := needDay.UnixNano() / 1e6
-				timestampStr := fmt.Sprintf("%d", timestamp)
-				valStr := decimal.NewFromFloat(currentItem.Value).String()
-				addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
-				isAdd = true
-			}
-			existMap[existKey] = needDayStr
-		}
-		existKey := edbCode + currentItem.DataTime
-		if _, ok := existMap[existKey]; !ok {
-			currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-			timestampStr := fmt.Sprintf("%d", timestamp)
-			valStr := decimal.NewFromFloat(currentItem.Value).String()
-			addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, valStr)
-			isAdd = true
-		}
-		existMap[existKey] = currentItem.DataTime
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateBp 修改变频数据
-func EditCalculateBp(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateBp(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -174,157 +108,72 @@ func EditCalculateBp(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, ed
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
 	if err != nil {
 		return
 	}
 
+	//判断计算指标是否被更换
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
-	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
 	if err != nil {
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 {
-		//删除指标关联计算指标
-		//sql := ` DELETE FROM edb_info_calculate_bp WHERE edb_info_id = ? `
-		//_, err = o.Raw(sql, edbInfoId).Exec()
-		//if err != nil {
-		//	return
-		//}
-
-		//calculateItem := new(EdbInfoCalculateHbz)
-		//calculateItem.CreateTime = time.Now()
-		//calculateItem.ModifyTime = time.Now()
-		//calculateItem.Sort = 1
-		//calculateItem.EdbCode = edbCode
-		//calculateItem.EdbInfoId = edbInfoId
-		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
-		//calculateItem.FromEdbName = fromEdbInfo.EdbName
-		//calculateItem.FromSource = fromEdbInfo.Source
-		//calculateItem.FromSourceName = fromEdbInfo.SourceName
-		//
-		//_, err = o.Insert(calculateItem)
-		//if err != nil {
-		//	return
-		//}
-
-		//删除,计算指标关联的,基础指标的关联关系
-		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
-			return
-		}
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_bp WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		//关联关系
-		{
-			calculateMappingItem := new(EdbInfoCalculateMapping)
-			calculateMappingItem.CreateTime = time.Now()
-			calculateMappingItem.ModifyTime = time.Now()
-			calculateMappingItem.Sort = 1
-			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
-			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-			calculateMappingItem.FromSource = fromEdbInfo.Source
-			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-			calculateMappingItem.FromTag = ""
-			calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_BP
-			calculateMappingItem.SourceName = "变频"
-			_, err = o.Insert(calculateMappingItem)
-			if err != nil {
-				return
-			}
+	if count > 0 { // 指标未被替换,无需重新计算
+		return
+	}
+
+	//删除,计算指标关联的,基础指标的关联关系
+	sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
+		return
+	}
+	//清空原有数据
+	sql = ` DELETE FROM edb_data_calculate_bp WHERE edb_info_id = ? `
+	_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+	//关联关系
+	{
+		calculateMappingItem := &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    utils.DATA_SOURCE_CALCULATE_BP,
+			SourceName:                "变频",
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+			FromEdbCode:               fromEdbInfo.EdbCode,
+			FromEdbName:               fromEdbInfo.EdbName,
+			FromSource:                fromEdbInfo.Source,
+			FromSourceName:            fromEdbInfo.SourceName,
+			FromTag:                   "",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
 		}
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-		fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+		_, err = to.Insert(calculateMappingItem)
 		if err != nil {
-			return edbInfoId, err
-		}
-		addSql := ` INSERT INTO edb_data_calculate_bp(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		existMap := make(map[string]string)
-		dataLen := len(dataList)
-		for i := 0; i < dataLen; i++ {
-			//当期
-			currentItem := dataList[i]
-			currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-			var day int
-			var preItem *EdbInfoSearchData
-			var preDate time.Time
-			if i == 0 {
-				day = int(time.Now().Sub(currentDate).Hours() / float64(24))
-				preDate = time.Now()
-			} else {
-				j := i + 1
-				if j < dataLen {
-					preItem = dataList[j]
-					preDate, _ = time.Parse(utils.FormatDate, preItem.DataTime)
-					day = int(currentDate.Sub(preDate).Hours() / float64(24))
-				}
-			}
-			for k := 0; k <= day; k++ {
-				needDay := preDate.AddDate(0, 0, -k)
-				needDayStr := needDay.Format(utils.FormatDate)
-				existKey := edbCode + needDayStr
-				if _, ok := existMap[existKey]; !ok {
-					timestamp := needDay.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-					valStr := decimal.NewFromFloat(currentItem.Value).String()
-					addSql += GetAddSql(edbInfoIdStr, edbCode, needDayStr, timestampStr, valStr)
-				}
-				existMap[existKey] = needDayStr
-			}
-			existKey := edbCode + currentItem.DataTime
-			if _, ok := existMap[existKey]; !ok {
-				currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-				timestamp := currentDate.UnixNano() / 1e6
-				timestampStr := fmt.Sprintf("%d", timestamp)
-				valStr := decimal.NewFromFloat(currentItem.Value).String()
-				addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, valStr)
-			}
-			existMap[existKey] = currentItem.DataTime
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
+			return
 		}
 	}
+
+	//计算数据
+	err = refreshAllCalculateBp(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
+
 	return
 }
 
@@ -365,7 +214,7 @@ func RefreshAllCalculateBpBak(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 		pars = append(pars, endDate)
 	}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
 	if err != nil {
 		return err
 	}
@@ -484,11 +333,15 @@ func RefreshAllCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode,
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	// 计算数据
+	err = refreshAllCalculateBp(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
+
+	return
+}
+
+// refreshAllCalculateBp 刷新变频数据
+func refreshAllCalculateBp(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
-	//计算数据
 
 	//计算数据
 	var condition string
@@ -505,7 +358,7 @@ func RefreshAllCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode,
 	//	pars = append(pars, endDate)
 	//}
 	//获取来源指标的数据
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 1)
 	if err != nil {
 		return err
 	}
@@ -619,7 +472,7 @@ func RefreshAllCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode,
 			//如果没有来源指标数据,那么已经入库的计算指标数据需要全部删除
 			tableName := GetEdbDataTableName(source)
 			sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ?`, tableName)
-			_, err = o.Raw(sql, edbInfoId).Exec()
+			_, err = to.Raw(sql, edbInfoId).Exec()
 			if err != nil {
 				err = fmt.Errorf("删除所有的变频指标数据失败,Err:" + err.Error())
 				return
@@ -639,7 +492,7 @@ func RefreshAllCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode,
 		tableName := GetEdbDataTableName(source)
 		sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
 
-		_, err = o.Raw(sql, edbInfoId).Exec()
+		_, err = to.Raw(sql, edbInfoId).Exec()
 		if err != nil {
 			err = fmt.Errorf("删除不存在的变频指标数据失败,Err:" + err.Error())
 			return
@@ -648,7 +501,7 @@ func RefreshAllCalculateBp(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode,
 
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 	}
 	return
 }

+ 366 - 0
models/edb_data_calculate_cjjx.go

@@ -0,0 +1,366 @@
+package models
+
+import (
+	"errors"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/shopspring/decimal"
+	"hongze/hongze_edb_lib/utils"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// AddCalculateCjjx 超季节性
+func AddCalculateCjjx(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfo *EdbInfo, err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("AddCalculateCjjx,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	fmt.Println("req.EdbInfoId:", req.EdbInfoId)
+	if req.EdbInfoId <= 0 {
+		edbInfo = new(EdbInfo)
+		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_CJJX
+		edbInfo.SourceName = "超季节性"
+		edbInfo.EdbCode = edbCode
+		edbInfo.EdbName = req.EdbName
+		edbInfo.EdbNameSource = req.EdbName
+		edbInfo.Frequency = req.Frequency
+		edbInfo.Unit = req.Unit
+		edbInfo.ClassifyId = req.ClassifyId
+		edbInfo.SysUserId = sysUserId
+		edbInfo.SysUserRealName = sysUserRealName
+		edbInfo.CreateTime = time.Now()
+		edbInfo.ModifyTime = time.Now()
+		edbInfo.UniqueCode = uniqueCode
+		edbInfo.CalculateFormula = req.Formula
+		edbInfo.EdbType = 2
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			err = tmpErr
+			return
+		}
+		edbInfo.EdbInfoId = int(newEdbInfoId)
+
+		//关联关系
+		{
+			calculateMappingItem := new(EdbInfoCalculateMapping)
+			calculateMappingItem.CreateTime = time.Now()
+			calculateMappingItem.ModifyTime = time.Now()
+			calculateMappingItem.Sort = 1
+			calculateMappingItem.EdbCode = edbCode
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
+			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
+			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
+			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
+			calculateMappingItem.FromSource = fromEdbInfo.Source
+			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
+			calculateMappingItem.FromTag = ""
+			calculateMappingItem.Source = edbInfo.Source
+			calculateMappingItem.SourceName = edbInfo.SourceName
+			_, err = to.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	} else {
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
+		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_CJJX)
+		fmt.Println("dataTableName:", dataTableName)
+		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
+		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
+		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
+		if err != nil {
+			return
+		}
+	}
+
+	//计算数据
+	err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
+
+	return
+}
+
+// EditCalculateCjjx 超季节性
+func EditCalculateCjjx(req *EdbInfoCalculateBatchEditReq, edbInfo, fromEdbInfo *EdbInfo, formulaInt int) (err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("EditCalculateCjjx,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
+	edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+	if err != nil {
+		return
+	}
+
+	//修改指标信息
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = o.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
+	if err != nil {
+		return
+	}
+
+	//判断计算指标是否被更换
+	var existCondition string
+	var existPars []interface{}
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
+
+	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
+	if err != nil {
+		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
+		return
+	}
+	if count > 0 && oldCalculateFormula == req.Formula { // 指标未被替换,同时N值未修改,无需重新计算
+		return
+	}
+
+	// 指标被替换,或者N值未修改,那么需要重新计算数据
+	//基础指标被替换了,需要删除原先的 计算指标关联的,基础指标的关联关系
+	if count <= 0 {
+		// 需要删除原先的 计算指标关联的,基础指标的关联关系
+		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+		_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+		if err != nil {
+			return
+		}
+
+		// 添加新的关联关系
+		{
+			calculateMappingItem := &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    utils.DATA_SOURCE_CALCULATE_CJJX,
+				SourceName:                "超季节性",
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+				FromEdbCode:               fromEdbInfo.EdbCode,
+				FromEdbName:               fromEdbInfo.EdbName,
+				FromSource:                fromEdbInfo.Source,
+				FromSourceName:            fromEdbInfo.SourceName,
+				FromTag:                   "",
+				Sort:                      1,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
+			}
+			_, err = o.Insert(calculateMappingItem)
+			if err != nil {
+				return
+			}
+		}
+	}
+
+	//清空原有数据
+	tableName := GetEdbDataTableName(edbInfo.Source)
+	sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	//计算数据
+	err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
+
+	return
+}
+
+// RefreshAllCalculateCjjx 刷新全部超季节性数据
+func RefreshAllCalculateCjjx(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			fmt.Println("RefreshAllCalculateCjjx,Err:" + err.Error())
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+
+	// 重新计算
+	err = refreshAllCalculateCjjx(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
+
+	return
+}
+
+// refreshAllCalculateCjjx 刷新全部超季节性数据
+func refreshAllCalculateCjjx(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
+	if err != nil {
+		return
+	}
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
+	//计算数据
+
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	pars = append(pars, fromEdbInfo.EdbInfoId)
+
+	if startDate != "" {
+		condition += " AND data_time>=? "
+		pars = append(pars, startDate)
+	}
+	//if endDate != "" {
+	//	condition += " AND data_time<=? "
+	//	pars = append(pars, endDate)
+	//}
+
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
+	if err != nil {
+		return err
+	}
+	var dateArr []string
+	dataMap := make(map[string]*EdbInfoSearchData)
+	for _, v := range dataList {
+		dateArr = append(dateArr, v.DataTime)
+		dataMap[v.DataTime] = v
+	}
+	//获取指标所有数据
+	existDataList := make([]*EdbData, 0)
+	dataTableName := GetEdbDataTableName(source)
+	sql := `SELECT * FROM %s WHERE edb_info_id=? `
+	sql = fmt.Sprintf(sql, dataTableName)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	if err != nil {
+		return err
+	}
+	existDataMap := make(map[string]string)
+	for _, v := range existDataList {
+		existDataMap[v.DataTime] = v.Value
+	}
+
+	addSql := ` INSERT INTO edb_data_calculate_cjjx(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
+	var isAdd bool
+	//日度/周度/季度/月度
+	isCompatibility := false //是否向上下兼容35天
+	if utils.InArrayByStr([]string{"日度", "周度", "季度", "月度"}, fromEdbInfo.Frequency) {
+		isCompatibility = true
+	}
+
+	for _, av := range dateArr {
+		currentItem := dataMap[av]
+		if currentItem != nil {
+			pastValueList := make([]float64, 0) // 过去几期的数据
+			//当前日期
+			currentDate, tmpErr := time.Parse(utils.FormatDate, av)
+			if tmpErr != nil {
+				err = tmpErr
+				return
+			}
+			pastValueList = append(pastValueList, currentItem.Value)
+			for i := 1; i < formulaInt; i++ {
+				//前几年的日期
+				preDate := currentDate.AddDate(-i, 0, 0)
+				preDateStr := preDate.Format(utils.FormatDate)
+				if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
+					pastValueList = append(pastValueList, findItem.Value)
+				} else if isCompatibility { // 如果需要兼容上下35天
+					nextDateDay := preDate
+					preDateDay := preDate
+					for i := 0; i < 35; i++ {
+						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
+						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
+							pastValueList = append(pastValueList, findItem.Value)
+							break
+						} else {
+							preDateDayStr := preDateDay.Format(utils.FormatDate)
+							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
+								pastValueList = append(pastValueList, findItem.Value)
+								break
+							}
+						}
+						nextDateDay = nextDateDay.AddDate(0, 0, 1)
+						preDateDay = preDateDay.AddDate(0, 0, -1)
+					}
+				}
+			}
+
+			if len(pastValueList) == formulaInt {
+				val := CjjxSub(currentItem.Value, pastValueList)
+
+				if existVal, ok := existDataMap[edbCode+av]; !ok {
+					timestamp := currentDate.UnixNano() / 1e6
+					timestampStr := fmt.Sprintf("%d", timestamp)
+					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
+					isAdd = true
+				} else {
+					existValDecimal, err := decimal.NewFromString(existVal)
+					existStr := existValDecimal.String()
+					if existStr != val {
+						sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
+						sql = fmt.Sprintf(sql, dataTableName)
+						_, err = to.Raw(sql, val, edbInfoId, av).Exec()
+						if err != nil {
+							return err
+						}
+					}
+				}
+			}
+			existDataMap[edbCode+av] = av
+		}
+	}
+	if isAdd {
+		addSql = strings.TrimRight(addSql, ",")
+		_, err = to.Raw(addSql).Exec()
+		if err != nil {
+			return err
+		}
+	}
+	return
+}
+
+// CjjxSub 计算超季节性值
+// 计算公式=现值-过去n年(包括今年)均值,n为取数个数,需大于等于1;
+//举例:A指标  2022-10-13值100,2021-10-13值120,2020-10-13值110,设置n=3,则“超季节性”指标计算值为100-(100+120+110)/3=-10。
+func CjjxSub(currValue float64, pastValue []float64) (value string) {
+	num := len(pastValue)
+	if num == 0 {
+		return
+	}
+	numDecimal := decimal.NewFromInt(int64(num))
+
+	af := decimal.NewFromFloat(currValue)
+	fmt.Println(af)
+
+	bf := decimal.NewFromFloat(pastValue[0])
+
+	for k := 1; k < num; k++ {
+		tmpVal := decimal.NewFromFloat(pastValue[k])
+		bf = bf.Add(tmpVal)
+	}
+	val, _ := af.Sub(bf.Div(numDecimal)).Float64()
+	//valStr := utils.SubFloatToString(val, 4)
+	valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
+	return valStr
+}

+ 71 - 153
models/edb_data_calculate_hbz.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateHbz 新增环比值指标
-func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -27,7 +27,7 @@ func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HBZ
 		edbInfo.SourceName = "环比值"
 		edbInfo.EdbCode = edbCode
@@ -45,9 +45,10 @@ func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := o.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 		//关联关系
 		{
 			calculateMappingItem := new(EdbInfoCalculateMapping)
@@ -55,7 +56,7 @@ func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -70,7 +71,10 @@ func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HBZ)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
@@ -80,62 +84,14 @@ func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
+	err = refreshAllCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
 
-	addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	dataLen := len(dataList)
-	for i := 0; i < dataLen; i++ {
-		j := i + formulaInt
-		if j < dataLen {
-			//当期
-			currentItem := dataList[i]
-			preItem := dataList[j]
-			fmt.Println("preItem.Value:", preItem.Value)
-			if currentItem != nil && preItem != nil && preItem.Value != 0 {
-				existKey := edbCode + currentItem.DataTime
-				if _, ok := existMap[existKey]; !ok {
-					currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-					val := HbzDiv(currentItem.Value, preItem.Value)
-					if val != "" {
-						addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
-						isAdd = true
-					}
-				}
-				existMap[existKey] = currentItem.DataTime
-			}
-		}
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateHbz 环比值
-func EditCalculateHbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, formulaInt int, calculateFormula string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateHbz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -151,28 +107,22 @@ func EditCalculateHbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
- 			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
 	if err != nil {
 		return
 	}
 
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
 	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
@@ -180,86 +130,51 @@ func EditCalculateHbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 || strconv.Itoa(formulaInt) != calculateFormula {
-		//删除,计算指标关联的,基础指标的关联关系
-		if count <= 0 {
-			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-			_, err = o.Raw(sql, edbInfoId).Exec()
-			if err != nil {
-				return
-			}
-			//关联关系
-			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = edbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-				calculateMappingItem.FromSource = fromEdbInfo.Source
-				calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-				calculateMappingItem.FromTag = ""
-				calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_HBZ
-				calculateMappingItem.SourceName = "环比值"
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
-				}
-			}
-		}
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_hbz WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
+		return
+	}
+
+	//删除,计算指标关联的,基础指标的关联关系
+	if count <= 0 {
+		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 		if err != nil {
-			return edbInfoId, err
+			return
 		}
-		addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		existMap := make(map[string]string)
-		dataLen := len(dataList)
-		for i := 0; i < dataLen; i++ {
-			j := i + formulaInt
-			if j < dataLen {
-				//当期
-				currentItem := dataList[i]
-				preItem := dataList[j]
-				if currentItem != nil && preItem != nil {
-					existKey := edbCode + currentItem.DataTime
-					if _, ok := existMap[existKey]; !ok {
-						currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-						timestamp := currentDate.UnixNano() / 1e6
-						timestampStr := fmt.Sprintf("%d", timestamp)
-						val := HbzDiv(currentItem.Value, preItem.Value)
-						if val != "" {
-							addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
-							isAdd = true
-						}
-					}
-					existMap[existKey] = currentItem.DataTime
-				}
+		//关联关系
+		{
+			calculateMappingItem := &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    utils.DATA_SOURCE_CALCULATE_HBZ,
+				SourceName:                "环比值",
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+				FromEdbCode:               fromEdbInfo.EdbCode,
+				FromEdbName:               fromEdbInfo.EdbName,
+				FromSource:                fromEdbInfo.Source,
+				FromSourceName:            fromEdbInfo.SourceName,
+				FromTag:                   "",
+				Sort:                      1,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
+			_, err = to.Insert(calculateMappingItem)
 			if err != nil {
-				return edbInfoId, err
+				return
 			}
 		}
 	}
+	//清空原有数据
+	sql := ` DELETE FROM edb_data_calculate_hbz WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	//计算数据
+	err = refreshAllCalculateHbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
+
 	return
 }
 
@@ -278,12 +193,15 @@ func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 			_ = to.Commit()
 		}
 	}()
-	if err != nil {
-		return
-	}
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
+
 	//计算数据
+	err = refreshAllCalculateHbz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
+	return
+}
 
+// refreshAllCalculateHbz 刷新所有环比值数据
+func refreshAllCalculateHbz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
 	var condition string
 	var pars []interface{}
@@ -299,7 +217,7 @@ func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	//	pars = append(pars, endDate)
 	//}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
 	if err != nil {
 		return err
 	}
@@ -316,7 +234,7 @@ func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	fmt.Println("dataTableName:", dataTableName)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -353,7 +271,7 @@ func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							if existStr != val {
 								sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 								sql = fmt.Sprintf(sql, dataTableName)
-								_, err = o.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
+								_, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
 								if err != nil {
 									return err
 								}
@@ -367,7 +285,7 @@ func RefreshAllCalculateHbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	}
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}

+ 72 - 168
models/edb_data_calculate_hcz.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateHcz 新增环差值指标
-func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -27,7 +27,7 @@ func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HCZ
 		edbInfo.SourceName = "环差值"
 		edbInfo.EdbCode = edbCode
@@ -45,9 +45,10 @@ func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 
 		//关联关系
 		{
@@ -56,7 +57,7 @@ func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -71,7 +72,10 @@ func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HCZ)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
@@ -81,67 +85,14 @@ func AddCalculateHcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-	fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
+	err = refreshAllCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
 
-	addSql := ` INSERT INTO edb_data_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	dataLen := len(dataList)
-	fmt.Println("dataLen:", dataLen)
-	for i := 0; i < dataLen; i++ {
-		j := i + formulaInt
-		if j < dataLen {
-			//当期
-			currentItem := dataList[i]
-			preItem := dataList[j]
-			if currentItem != nil && preItem != nil {
-				existKey := edbCode + currentItem.DataTime
-				if _, ok := existMap[existKey]; !ok {
-					currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-					val := ""
-					if preItem.Value == 0 {
-						val = "0"
-					} else {
-						val = HczDiv(currentItem.Value, preItem.Value)
-					}
-					if val != "" {
-						addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
-						isAdd = true
-					}
-				}
-				existMap[existKey] = currentItem.DataTime
-			}
-		}
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateHcz 修改环差值指标
-func EditCalculateHcz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, formulaInt int, calculateFormula string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateHcz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -157,125 +108,74 @@ func EditCalculateHcz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
- 			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
 	if err != nil {
 		return
 	}
 
+	//判断计算指标是否被更换
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
-	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
 	if err != nil {
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
+	if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
+		return
+	}
 
-	if count <= 0 || strconv.Itoa(formulaInt) != calculateFormula {
-		//删除,计算指标关联的,基础指标的关联关系
-		if count <= 0 {
-			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-			_, err = o.Raw(sql, edbInfoId).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
-			//关联关系
-			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = edbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-				calculateMappingItem.FromSource = fromEdbInfo.Source
-				calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-				calculateMappingItem.FromTag = ""
-				calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_HCZ
-				calculateMappingItem.SourceName = "环差值"
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
-				}
-			}
-		}
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_hcz WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-		fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	//删除,计算指标关联的,基础指标的关联关系
+	if count <= 0 {
+		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+		_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
 		if err != nil {
-			return edbInfoId, err
-		}
-		var dateArr []string
-		dataMap := make(map[string]*EdbInfoSearchData)
-		for _, v := range dataList {
-			dateArr = append(dateArr, v.DataTime)
-			dataMap[v.DataTime] = v
+			return
 		}
-
-		addSql := ` INSERT INTO edb_data_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		existMap := make(map[string]string)
-		dataLen := len(dataList)
-		fmt.Println("dataLen:", dataLen)
-		for i := 0; i < dataLen; i++ {
-			j := i + formulaInt
-			if j < dataLen {
-				//当期
-				currentItem := dataList[i]
-				preItem := dataList[j]
-				if currentItem != nil && preItem != nil {
-					existKey := edbCode + currentItem.DataTime
-					if _, ok := existMap[existKey]; !ok {
-						currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-						timestamp := currentDate.UnixNano() / 1e6
-						timestampStr := fmt.Sprintf("%d", timestamp)
-						val := HczDiv(currentItem.Value, preItem.Value)
-						if val != "" {
-							addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
-							isAdd = true
-						}
-					}
-					existMap[existKey] = currentItem.DataTime
-				}
+		//关联关系
+		{
+			calculateMappingItem := &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    utils.DATA_SOURCE_CALCULATE_HCZ,
+				SourceName:                "环差值",
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+				FromEdbCode:               fromEdbInfo.EdbCode,
+				FromEdbName:               fromEdbInfo.EdbName,
+				FromSource:                fromEdbInfo.Source,
+				FromSourceName:            fromEdbInfo.SourceName,
+				FromTag:                   "",
+				Sort:                      1,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
+			_, err = to.Insert(calculateMappingItem)
 			if err != nil {
-				return edbInfoId, err
+				return
 			}
 		}
 	}
+	//清空原有数据
+	sql := ` DELETE FROM edb_data_calculate_hcz WHERE edb_info_id = ? `
+	_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	//计算数据
+	err = refreshAllCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
+
 	return
 }
 
@@ -295,9 +195,13 @@ func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	//计算数据
+	err = refreshAllCalculateHcz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
+	return
+}
+
+// refreshAllCalculateHcz 刷新所有环差值数据
+func refreshAllCalculateHcz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
 
 	//计算数据
@@ -315,7 +219,7 @@ func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	//	pars = append(pars, endDate)
 	//}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
 	if err != nil {
 		return err
 	}
@@ -332,7 +236,7 @@ func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	fmt.Println("dataTableName:", dataTableName)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -369,7 +273,7 @@ func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							if existStr != val {
 								sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 								sql = fmt.Sprintf(sql, dataTableName)
-								_, err = o.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
+								_, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
 								if err != nil {
 									return err
 								}
@@ -383,7 +287,7 @@ func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	}
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}
@@ -399,6 +303,6 @@ func HczDiv(current, pre float64) string {
 	currentVal := decimal.NewFromFloat(current)
 	preVal := decimal.NewFromFloat(pre)
 	val, _ := currentVal.Sub(preVal).Float64()
-	valStr := decimal.NewFromFloat(val).RoundCeil(4).String()//utils.SubFloatToString(val, 4)
+	valStr := decimal.NewFromFloat(val).RoundCeil(4).String() //utils.SubFloatToString(val, 4)
 	return valStr
 }

+ 233 - 507
models/edb_data_calculate_ljztbpj.go

@@ -25,7 +25,7 @@ type EdbDataCalculateLjztbpj struct {
 }
 
 // AddCalculateLjztbpj 新增累计值同比拼接数据
-func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -58,7 +58,8 @@ func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, second
 
 		lastEdbData, tmpErr := GetLastEdbData(condition, pars, firstEdbInfo.Source)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
 		lastDateTime, _ = time.ParseInLocation(utils.FormatDate, lastEdbData.DataTime, time.Local)
 
@@ -68,9 +69,10 @@ func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, second
 		condition += " AND data_time <= ? AND edb_info_id=? "
 		pars = append(pars, lastEdbData.DataTime, firstEdbInfo.EdbInfoId)
 
-		firstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
+		firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, firstEdbInfo.Source, 0)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
 
 		for _, v := range firstDataList {
@@ -79,7 +81,6 @@ func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, second
 		}
 	}
 
-	var edbInfo *EdbInfo
 	if req.EdbInfoId <= 0 {
 		edbInfo = &EdbInfo{
 			SourceName:       "累计值同比拼接",
@@ -100,15 +101,19 @@ func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, second
 			CalculateFormula: lastDateTime.Format(utils.FormatDate),
 			EdbType:          2,
 		}
-		newEdbInfoId, err := to.Insert(edbInfo)
-		if err != nil {
-			return edbInfoId, err
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		//查询
-		tmpEdbInfo, tmpErr := GetEdbInfoById(edbInfoId)
+		tmpEdbInfo, tmpErr := GetEdbInfoById(edbInfo.EdbInfoId)
 		if tmpErr != nil {
 			err = tmpErr
 			return
@@ -128,167 +133,77 @@ func AddCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, second
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
 		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
 		if err != nil {
-			return 0, err
+			return
 		}
 
 		//删除指标关系
 		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=? `
-		_, err = to.Raw(sql, edbInfoId).Exec()
+		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 	}
 
 	//关联关系
 
+	var existItemA, existItemB *EdbInfoCalculateMapping
 	//拼接指标
 	{
-		calculateMappingItem := new(EdbInfoCalculateMapping)
-		calculateMappingItem.CreateTime = time.Now()
-		calculateMappingItem.ModifyTime = time.Now()
-		calculateMappingItem.Sort = 1
-		calculateMappingItem.EdbCode = edbCode
-		calculateMappingItem.EdbInfoId = edbInfoId
-		calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
-		calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
-		calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
-		calculateMappingItem.FromSource = firstEdbInfo.Source
-		calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
-		calculateMappingItem.FromTag = "A"
-		calculateMappingItem.Source = edbInfo.Source
-		calculateMappingItem.SourceName = edbInfo.SourceName
-		_, err = to.Insert(calculateMappingItem)
-		if err != nil {
-			return
-		}
-	}
-
-	//同比值指标
-	{
-		calculateMappingItem := new(EdbInfoCalculateMapping)
-		calculateMappingItem.CreateTime = time.Now()
-		calculateMappingItem.ModifyTime = time.Now()
-		calculateMappingItem.Sort = 1
-		calculateMappingItem.EdbCode = edbCode
-		calculateMappingItem.EdbInfoId = edbInfoId
-		calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
-		calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
-		calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
-		calculateMappingItem.FromSource = secondEdbInfo.Source
-		calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
-		calculateMappingItem.FromTag = "B"
-		calculateMappingItem.Source = edbInfo.Source
-		calculateMappingItem.SourceName = edbInfo.SourceName
-		_, err = to.Insert(calculateMappingItem)
-		if err != nil {
+		existItemA = &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    edbInfo.Source,
+			SourceName:                edbInfo.SourceName,
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             firstEdbInfo.EdbInfoId,
+			FromEdbCode:               firstEdbInfo.EdbCode,
+			FromEdbName:               firstEdbInfo.EdbName,
+			FromSource:                firstEdbInfo.Source,
+			FromSourceName:            firstEdbInfo.SourceName,
+			FromTag:                   "A",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
+		}
+		insertId, tmpErr := to.Insert(existItemA)
+		if tmpErr != nil {
+			err = tmpErr
 			return
 		}
+		existItemA.EdbInfoCalculateMappingId = int(insertId)
 	}
 
-	//同比值指标map
-	tbzEdbDataMap := make(map[string]float64)
-
-	//同比值日期切片列表
-	tbzEdbDataTimeList := make([]string, 0)
-
 	//同比值指标
 	{
-		var condition string
-		var pars []interface{}
-
-		condition += " AND data_time > ? AND edb_info_id = ? "
-		pars = append(pars, lastDateTime, secondEdbInfo.EdbInfoId)
-
-		//同比值指标的数据列表
-		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
-		if tmpErr != nil {
-			return edbInfoId, tmpErr
-		}
-
-		for _, v := range secondDataList {
-			tbzEdbDataMap[v.DataTime] = v.Value
-			tbzEdbDataTimeList = append(tbzEdbDataTimeList, v.DataTime)
-		}
-	}
-
-	sort.Strings(tbzEdbDataTimeList)
-	for _, v := range tbzEdbDataTimeList {
-		tbzDataTime, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
-
-		//获取拼接指标上一年同一天的数据
-		var pjDataTime time.Time
-		if tbzDataTime.Month() == 2 {
-			pjDataTime = tbzDataTime.AddDate(0, -11, 0)
-			pjDataTime = time.Date(pjDataTime.Year(), pjDataTime.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, -1)
-		} else {
-			pjDataTime = tbzDataTime.AddDate(-1, 0, 0)
-		}
-
-		//如果存在数据,那么就去计算当前的数据
-		if pjDataValue, ok := pjDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
-			tbzDataValue := tbzEdbDataMap[v] //同比值
-			currValue := pjDataValue * (1 + tbzDataValue/100)
-
-			currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64()
-			//将计算后的数据存入待拼接指标map里面,以便后续计算
-			pjDataMap[v] = currValue
-
-			pjEdbDataTimeList = append(pjEdbDataTimeList, v)
-		}
-	}
-
-	addDataList := make([]*EdbDataCalculateLjztbpj, 0)
-
-	//日期排序下
-	sort.Strings(pjEdbDataTimeList)
-	//这么做的目的是为了让数据插入的时候,可以正序插入(业务上没啥卵用,就是为了让我看数据的时候舒服点,手动狗头-_-|)
-	for _, dataTime := range pjEdbDataTimeList {
-		if dataValue, ok := pjDataMap[dataTime]; ok {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, dataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataLjztbpj := &EdbDataCalculateLjztbpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       edbInfo.EdbCode,
-				DataTime:      dataTime,
-				Value:         dataValue,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataLjztbpj)
-		}
-	}
-
-	//数据入库
-	tmpAddDataList := make([]*EdbDataCalculateLjztbpj, 0)
-	for _, v := range addDataList {
-		tmpAddDataList = append(tmpAddDataList, v)
-
-		if len(tmpAddDataList) >= 200 {
-			_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-			if tmpErr != nil {
-				err = tmpErr
-				return
-			}
-			//重新初始化需要加入的数据切片
-			tmpAddDataList = make([]*EdbDataCalculateLjztbpj, 0)
-		}
-	}
-	//最后如果还有需要新增的数据,那么就统一入库
-	if len(tmpAddDataList) > 0 {
-		_, tmpErr := to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+		existItemB = &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    edbInfo.Source,
+			SourceName:                edbInfo.SourceName,
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             secondEdbInfo.EdbInfoId,
+			FromEdbCode:               secondEdbInfo.EdbCode,
+			FromEdbName:               secondEdbInfo.EdbName,
+			FromSource:                secondEdbInfo.Source,
+			FromSourceName:            secondEdbInfo.SourceName,
+			FromTag:                   "B",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
+		}
+		insertId, tmpErr := to.Insert(existItemB)
 		if tmpErr != nil {
 			err = tmpErr
 			return
 		}
+		existItemB.EdbInfoCalculateMappingId = int(insertId)
 	}
 
+	// 添加数据
+	err = refreshAllCalculateLjztbpj(to, edbInfo, existItemA, existItemB)
+
 	return
 }
 
 // EditCalculateLjztbpj 编辑累计值同比拼接数据
-func EditCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateLjztbpj(req *EdbInfoCalculateBatchEditReq, edbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -303,14 +218,26 @@ func EditCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEd
 		}
 	}()
 
+	nowEdbInfo := *edbInfo // 现在的指标信息
+
 	sql := ``
+	//修改指标信息
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	//edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
+	if err != nil {
+		return
+	}
 
+	//查询出所有的关联指标
 	var existCondition string
 	var existPars []interface{}
 	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	//查询出所有的关联指标
+	existPars = append(existPars, edbInfo.EdbInfoId)
 	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
 	if err != nil {
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
@@ -325,338 +252,134 @@ func EditCalculateLjztbpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEd
 			existItemB = existItem
 		}
 	}
-	// 原数据开始计算日期
-	startCalculationDate, _ := time.ParseInLocation(utils.FormatDate, nowEdbInfo.CalculateFormula, time.Local)
 
-	//待拼接指标map
-	pjDataMap := make(map[string]float64)     //需要入库的数据
-	nowEdbDataMap := make(map[string]float64) //当前指标的数据(已经在库里了,不需要重新)
-
-	//拼接指标的日期切片数据
-	pjEdbDataTimeList := make([]string, 0)
+	// 是否需要删除数据重新计算
+	isNeedCalculateData := false
 
-	//最近开始的时间
-	lastDateTime := startCalculationDate
+	// 如果截止日期变更,那么需要重新计算
+	if req.Formula != nowEdbInfo.CalculateFormula {
+		isNeedCalculateData = true
+	}
 
 	//待拼接指标数据
-	{
-		//如果拼接指标变更了,那么需要删除所有的指标进行重新拼接
-		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
-			//删除旧的指标数据
-			{
-				//删除之前的A指标关联关系
-				sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
-				_, err = o.Raw(sql, edbInfoId, existItemA.FromEdbInfoId).Exec()
-				if err != nil {
-					err = errors.New("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
-					return
-				}
-
-				//如果拼接指标变更了,那么需要删除所有的指标数据
-				tableName := GetEdbDataTableName(nowEdbInfo.Source)
-				sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
-
-				_, err = o.Raw(sql, edbInfoId).Exec()
-				if err != nil {
-					err = errors.New("删除所有的累计值同比拼接指标数据失败,Err:" + err.Error())
-					return
-				}
-			}
-
-			//添加新的指标关系
-			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
-				calculateMappingItem.FromSource = firstEdbInfo.Source
-				calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
-				calculateMappingItem.FromTag = "A"
-				calculateMappingItem.Source = nowEdbInfo.Source
-				calculateMappingItem.SourceName = nowEdbInfo.SourceName
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
-				}
-			}
-
-			var condition string
-			var pars []interface{}
-
-			//获取待拼接指标最近的个12月31日有值的年份
-			condition += " AND data_time like ? AND edb_info_id=? "
-			pars = append(pars, "%12-31", firstEdbInfo.EdbInfoId)
-
-			//获取最新的待拼接指标
-			lastEdbData, tmpErr := GetLastEdbData(condition, pars, firstEdbInfo.Source)
-			if tmpErr != nil {
-				return edbInfoId, tmpErr
-			}
-			lastDateTime, _ = time.ParseInLocation(utils.FormatDate, lastEdbData.DataTime, time.Local)
-
-			//获取待拼接指标的数据列表
-			condition = ``
-			pars = make([]interface{}, 0)
-			condition += " AND data_time <= ? AND edb_info_id=? "
-			pars = append(pars, lastEdbData.DataTime, firstEdbInfo.EdbInfoId)
-
-			firstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
-			if tmpErr != nil {
-				return edbInfoId, tmpErr
-			}
-
-			for _, v := range firstDataList {
-				pjDataMap[v.DataTime] = v.Value
-				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
+	//如果拼接指标变更了,那么需要删除所有的指标进行重新拼接
+	if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
+		//删除之前的A指标关联关系
+		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+		_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemA.FromEdbInfoId).Exec()
+		if err != nil {
+			err = errors.New("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
+			return
+		}
 
-				//将新的数据存入已入库指标map里面,以便后续计算
-				nowEdbDataMap[v.DataTime] = v.Value
+		//添加新的指标关系
+		{
+			existItemA = &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    edbInfo.Source,
+				SourceName:                edbInfo.SourceName,
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             firstEdbInfo.EdbInfoId,
+				FromEdbCode:               firstEdbInfo.EdbCode,
+				FromEdbName:               firstEdbInfo.EdbName,
+				FromSource:                firstEdbInfo.Source,
+				FromSourceName:            firstEdbInfo.SourceName,
+				FromTag:                   "A",
+				Sort:                      1,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-		} else {
-			// 获取当前指标的所有数据
-			var condition string
-			var pars []interface{}
-			condition += " AND edb_info_id=? and data_time <= ?"
-			pars = append(pars, nowEdbInfo.EdbInfoId, nowEdbInfo.CalculateFormula)
-
-			nowEdbDataList, tmpErr := GetEdbDataListAll(condition, pars, nowEdbInfo.Source, 0)
+			insertId, tmpErr := to.Insert(existItemA)
 			if tmpErr != nil {
-				return edbInfoId, tmpErr
+				err = tmpErr
+				return
 			}
+			existItemA.EdbInfoCalculateMappingId = int(insertId)
 
-			for _, v := range nowEdbDataList {
-				nowEdbDataMap[v.DataTime] = v.Value
-				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
-			}
+			isNeedCalculateData = true
 		}
 	}
 
-	//同比值指标map
-	tbzEdbDataMap := make(map[string]float64)
-
-	//同比值日期切片列表
-	tbzEdbDataTimeList := make([]string, 0)
-
 	//同比值指标
-	{
-		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
-			//删除通过B指标生成的数据
-			{
-				//删除之前的B指标关联关系
-				sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
-				_, err = o.Raw(sql, edbInfoId, existItemB.FromEdbInfoId).Exec()
-				if err != nil {
-					err = errors.New("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
-					return
-				}
-
-				//如果同比值指标变更了,那么需要删除所有计算出来的指标数据
-				tableName := GetEdbDataTableName(nowEdbInfo.Source)
-				sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time > ? `, tableName)
-
-				_, err = o.Raw(sql, edbInfoId, nowEdbInfo.CalculateFormula).Exec()
-				if err != nil {
-					err = errors.New("删除计算出来的累计值同比拼接指标数据失败,Err:" + err.Error())
-					return
-				}
-			}
-
-			//添加新的指标关系
-			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
-				calculateMappingItem.FromSource = secondEdbInfo.Source
-				calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
-				calculateMappingItem.FromTag = "B"
-				calculateMappingItem.Source = nowEdbInfo.Source
-				calculateMappingItem.SourceName = nowEdbInfo.SourceName
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
-				}
-			}
-		}
-
-		var condition string
-		var pars []interface{}
-
-		condition += " AND data_time > ? AND edb_info_id = ? "
-		pars = append(pars, lastDateTime, secondEdbInfo.EdbInfoId)
-
-		//同比值指标的数据列表
-		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
-		if tmpErr != nil {
-			return edbInfoId, tmpErr
-		}
-
-		for _, v := range secondDataList {
-			tbzEdbDataMap[v.DataTime] = v.Value
-			tbzEdbDataTimeList = append(tbzEdbDataTimeList, v.DataTime)
+	if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
+		//删除之前的B指标关联关系
+		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+		_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemB.FromEdbInfoId).Exec()
+		if err != nil {
+			err = errors.New("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
+			return
 		}
-	}
-
-	sort.Strings(tbzEdbDataTimeList)
 
-	// 遍历现有的数据,判断拼接指标中是否存在该日期数据,如果拼接指标无此数据,那么需要删除该日期数据(日期的判断:需要在开始计算日期之后)
-	removeDateList := make([]string, 0)
-	for nowEdbDate := range nowEdbDataMap {
-		nowEdbDateTime, _ := time.ParseInLocation(utils.FormatDate, nowEdbDate, time.Local)
-		//校验日期 需要 大于 拼接前日期
-		if startCalculationDate.Before(nowEdbDateTime) {
-			if _, ok := tbzEdbDataMap[nowEdbDate]; !ok {
-				// 同比指标中,不存在该日期数据,那么需要移除 现有数据 中该日期的数据
-				removeDateList = append(removeDateList, nowEdbDate)
+		//添加新的指标关系
+		{
+			existItemB = &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    edbInfo.Source,
+				SourceName:                edbInfo.SourceName,
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             secondEdbInfo.EdbInfoId,
+				FromEdbCode:               secondEdbInfo.EdbCode,
+				FromEdbName:               secondEdbInfo.EdbName,
+				FromSource:                secondEdbInfo.Source,
+				FromSourceName:            secondEdbInfo.SourceName,
+				FromTag:                   "B",
+				Sort:                      2,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-		}
-	}
-
-	//待修改的指标数据map(index:日期,value:值)
-	updateEdbDataMap := make(map[string]float64)
-	for _, v := range tbzEdbDataTimeList {
-		tbzDataTime, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
-
-		//获取拼接指标上一年同一天的数据
-		var pjDataTime time.Time
-		if tbzDataTime.Month() == 2 {
-			pjDataTime = tbzDataTime.AddDate(0, -11, 0)
-			pjDataTime = time.Date(pjDataTime.Year(), pjDataTime.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, -1)
-		} else {
-			pjDataTime = tbzDataTime.AddDate(-1, 0, 0)
-		}
 
-		//校验现有数据中,是否存在该日期的数据,如果存在的话,那么就要去校验 最新计算数据 与 现有数据 是否一致
-		if nowEdbDataValue, isHas := nowEdbDataMap[v]; isHas {
-			//获取去年今日的数据,获取到后,然后是去修改该日期的数据
-			if lastYearEdbDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
-				tbzDataValue := tbzEdbDataMap[v] //同比值
-				currValue := lastYearEdbDataValue * (1 + tbzDataValue/100)
-				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64() //保留4位小数
-				//如果计算出来的值与库里面的值不匹配,那么就去修改该值
-				if nowEdbDataValue != currValue {
-					//将计算后的数据存入待拼接指标map里面,以便后续计算
-					updateEdbDataMap[v] = currValue
-				}
+			insertId, tmpErr := to.Insert(existItemB)
+			if tmpErr != nil {
+				err = tmpErr
+				return
 			}
-		} else {
-			//因为 现有数据中 不存在该日期数据,那么需要做新增数据处理
-
-			//如果去年今日存在该数据,那么就去计算当前的数据
-			if pjDataValue, ok := nowEdbDataMap[pjDataTime.Format(utils.FormatDate)]; ok {
-				tbzDataValue := tbzEdbDataMap[v] //同比值
-				currValue := pjDataValue * (1 + tbzDataValue/100)
-
-				currValue, _ = decimal.NewFromFloat(currValue).Truncate(4).Float64()
-				//将计算后的数据存入已入库指标map里面,以便后续计算
-				nowEdbDataMap[v] = currValue
+			existItemA.EdbInfoCalculateMappingId = int(insertId)
 
-				//将计算后的数据存入待拼接指标map里面,以便后续入库
-				pjDataMap[v] = currValue
-				pjEdbDataTimeList = append(pjEdbDataTimeList, v)
-			}
+			isNeedCalculateData = true
 		}
 	}
 
-	//新增的数据入库
-	{
-		addDataList := make([]*EdbDataCalculateLjztbpj, 0)
-		for dataTime, dataValue := range pjDataMap {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, dataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataLjztbpj := &EdbDataCalculateLjztbpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       nowEdbInfo.EdbCode,
-				DataTime:      dataTime,
-				Value:         dataValue,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataLjztbpj)
+	// 如果需要重新计算,那么先删除所有的指标数据,然后再重新计算
+	if isNeedCalculateData {
+		// 删除之前所有的指标数据
+		tableName := GetEdbDataTableName(edbInfo.Source)
+		sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
+		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+		if err != nil {
+			err = errors.New("删除所有的累计值同比拼接指标数据失败,Err:" + err.Error())
+			return
 		}
 
-		tmpAddDataList := make([]*EdbDataCalculateLjztbpj, 0)
-		for _, v := range addDataList {
-			tmpAddDataList = append(tmpAddDataList, v)
+		//获取待拼接指标最近一年的12月份日期
+		{
+			var condition string
+			var pars []interface{}
 
-			if len(tmpAddDataList) >= 200 {
-				_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-				if tmpErr != nil {
-					err = tmpErr
-					return
-				}
-				//重新初始化需要加入的数据切片
-				tmpAddDataList = make([]*EdbDataCalculateLjztbpj, 0)
-			}
-		}
-		//最后如果还有需要新增的数据,那么就统一入库
-		if len(tmpAddDataList) > 0 {
-			_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+			//获取待拼接指标最近的个12月31日有值的年份
+			condition += " AND data_time like ? AND edb_info_id=? "
+			pars = append(pars, "%12-31", firstEdbInfo.EdbInfoId)
+
+			lastEdbData, tmpErr := GetLastEdbData(condition, pars, firstEdbInfo.Source)
 			if tmpErr != nil {
 				err = tmpErr
 				return
 			}
-		}
-	}
-
-	//删除已经不存在的累计同比拼接指标数据(由于同比值当日的数据删除了)
-	{
-		if len(removeDateList) > 0 {
-			removeDateStr := strings.Join(removeDateList, `","`)
-			removeDateStr = `"` + removeDateStr + `"`
-			//如果拼接指标变更了,那么需要删除所有的指标数据
-			tableName := GetEdbDataTableName(nowEdbInfo.Source)
-			sql = fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
-
-			_, err = o.Raw(sql, edbInfoId).Exec()
-			if err != nil {
-				err = errors.New("删除不存在的累计值同比拼接指标数据失败,Err:" + err.Error())
+			lastDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, lastEdbData.DataTime, time.Local)
+			if tmpErr != nil {
+				err = tmpErr
 				return
 			}
-		}
-	}
-
-	//修改现有的数据中对应的值
-	{
-		tableName := GetEdbDataTableName(nowEdbInfo.Source)
-		for edbDate, edbDataValue := range updateEdbDataMap {
-			sql = fmt.Sprintf(` UPDATE  %s set value = %f,modify_time=now() WHERE edb_info_id = ? and data_time = %s `, tableName, edbDataValue, edbDate)
-
-			_, err = o.Raw(sql, edbInfoId).Exec()
+			edbInfo.CalculateFormula = lastDateTime.Format(utils.FormatDate)
+			_, err = to.Update(edbInfo, "CalculateFormula")
 			if err != nil {
-				err = errors.New("更新现有的累计值同比拼接指标数据失败,Err:" + err.Error())
 				return
 			}
-		}
-	}
 
-	//修改指标信息
-	sql = ` UPDATE  edb_info SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?, 
-			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, lastDateTime.Format(utils.FormatDate), edbInfoId).Exec()
-	if err != nil {
-		return
+		}
+		// 重新计算
+		err = refreshAllCalculateLjztbpj(to, edbInfo, existItemA, existItemB)
 	}
 
 	return
@@ -686,14 +409,42 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 		}
 	}()
 
+	//查询关联指标信息
+	var existCondition string
+	var existPars []interface{}
+	existCondition += " AND edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId)
+	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
+	if err != nil {
+		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
+		return
+	}
+
+	var existItemA, existItemB *EdbInfoCalculateMapping
+	for _, existItem := range existList {
+		if existItem.FromTag == "A" {
+			existItemA = existItem
+		} else if existItem.FromTag == "B" {
+			existItemB = existItem
+		}
+	}
+	// 刷新数据
+	err = refreshAllCalculateLjztbpj(to, edbInfo, existItemA, existItemB)
+	return
+}
+
+// refreshAllCalculateLjztbpj 刷新所有 累计值同比拼接 数据
+func refreshAllCalculateLjztbpj(to orm.TxOrmer, edbInfo *EdbInfo, existItemA, existItemB *EdbInfoCalculateMapping) (err error) {
 	//查询当前指标现有的数据
 	var condition string
 	var pars []interface{}
 	condition += " AND edb_info_id=? "
 	pars = append(pars, edbInfo.EdbInfoId)
 
-	//所有的数据
-	dataList, err := GetAllEdbDataCalculateLjztbpjByEdbInfoId(edbInfo.EdbInfoId)
+	//根据指标id获取全部的数据
+	var dataList []*EdbDataCalculateLjztbpj
+	sql := ` SELECT * FROM edb_data_calculate_ljztbpj WHERE edb_info_id=? ORDER BY data_time DESC `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).QueryRows(&dataList)
 	if err != nil {
 		return err
 	}
@@ -711,25 +462,6 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 		nowEdbDataMap[v.DataTime] = v.Value
 	}
 
-	//查询关联指标信息
-	var existCondition string
-	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfo.EdbInfoId)
-	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
-	if err != nil {
-		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
-		return
-	}
-
-	var existItemA, existItemB *EdbInfoCalculateMapping
-	for _, existItem := range existList {
-		if existItem.FromTag == "A" {
-			existItemA = existItem
-		} else if existItem.FromTag == "B" {
-			existItemB = existItem
-		}
-	}
 	// 原数据开始计算日期
 	startCalculationDate, _ := time.ParseInLocation(utils.FormatDate, edbInfo.CalculateFormula, time.Local)
 
@@ -742,7 +474,7 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 		pars = append(pars, startCalculationDate, existItemA.FromEdbInfoId)
 
 		//第一个指标的数据列表
-		firstDataList, tmpErr := GetEdbDataListAll(condition, pars, existItemA.FromSource, 0)
+		firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemA.FromSource, 0)
 		if tmpErr != nil {
 			return tmpErr
 		}
@@ -753,12 +485,15 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 				if edbData.Value != v.Value {
 					//更新指标数据
 					edbData.Value = v.Value
-					_, _ = o.Update(edbData, "Value")
-
-					//将新的数据存入已入库指标map里面,以便后续计算
-					nowEdbDataMap[edbData.DataTime] = v.Value
+					_, _ = to.Update(edbData, "Value")
 				}
+			} else {
+				pjDataMap[v.DataTime] = v.Value
+				pjEdbDataTimeList = append(pjEdbDataTimeList, v.DataTime)
 			}
+
+			//将新的数据存入已入库指标map里面,以便后续计算
+			nowEdbDataMap[v.DataTime] = v.Value
 		}
 	}
 
@@ -777,7 +512,7 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 		pars = append(pars, startCalculationDate, existItemB.FromEdbInfoId)
 
 		//第二个指标的数据列表
-		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, existItemB.FromSource, 0)
+		secondDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemB.FromSource, 0)
 		if tmpErr != nil {
 			return tmpErr
 		}
@@ -856,41 +591,32 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 	//新增的数据入库
 	{
 		addDataList := make([]*EdbDataCalculateLjztbpj, 0)
-		for dataTime, dataValue := range pjDataMap {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, dataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataLjztbpj := &EdbDataCalculateLjztbpj{
-				EdbInfoId:     edbInfo.EdbInfoId,
-				EdbCode:       edbInfo.EdbCode,
-				DataTime:      dataTime,
-				Value:         dataValue,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataLjztbpj)
-		}
-
-		tmpAddDataList := make([]*EdbDataCalculateLjztbpj, 0)
-		for _, v := range addDataList {
-			tmpAddDataList = append(tmpAddDataList, v)
-
-			if len(tmpAddDataList) >= 200 {
-				_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-				if tmpErr != nil {
-					err = tmpErr
-					return
+		//日期排序下
+		sort.Strings(pjEdbDataTimeList)
+		//这么做的目的是为了让数据插入的时候,可以正序插入(业务上没啥卵用,就是为了让我看数据的时候舒服点,手动狗头-_-|)
+		for _, dataTime := range pjEdbDataTimeList {
+			if dataValue, ok := pjDataMap[dataTime]; ok {
+				//时间戳
+				currentDate, _ := time.Parse(utils.FormatDate, dataTime)
+				timestamp := currentDate.UnixNano() / 1e6
+
+				edbDataLjztbpj := &EdbDataCalculateLjztbpj{
+					EdbInfoId:     edbInfo.EdbInfoId,
+					EdbCode:       edbInfo.EdbCode,
+					DataTime:      dataTime,
+					Value:         dataValue,
+					Status:        1,
+					CreateTime:    time.Now(),
+					ModifyTime:    time.Now(),
+					DataTimestamp: timestamp,
 				}
-				//重新初始化需要加入的数据切片
-				tmpAddDataList = make([]*EdbDataCalculateLjztbpj, 0)
+				addDataList = append(addDataList, edbDataLjztbpj)
 			}
 		}
-		//最后如果还有需要新增的数据,那么就统一入库
-		if len(tmpAddDataList) > 0 {
-			_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+
+		//数据入库
+		if len(addDataList) > 0 {
+			_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
 			if tmpErr != nil {
 				err = tmpErr
 				return
@@ -907,7 +633,7 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 			tableName := GetEdbDataTableName(edbInfo.Source)
 			sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
 
-			_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 			if err != nil {
 				err = errors.New("删除不存在的累计值同比拼接指标数据失败,Err:" + err.Error())
 				return
@@ -921,7 +647,7 @@ func RefreshAllCalculateLjztbpj(edbInfo *EdbInfo) (err error) {
 		for edbDate, edbDataValue := range updateEdbDataMap {
 			sql := fmt.Sprintf(` UPDATE  %s set value = ?,modify_time=now() WHERE edb_info_id = ? and data_time = ? `, tableName)
 
-			_, err = o.Raw(sql, edbDataValue, edbInfo.EdbInfoId, edbDate).Exec()
+			_, err = to.Raw(sql, edbDataValue, edbInfo.EdbInfoId, edbDate).Exec()
 			if err != nil {
 				err = errors.New("更新现有的累计值同比拼接指标数据失败,Err:" + err.Error())
 				return

+ 72 - 304
models/edb_data_calculate_ljzzy.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateLjzzy 累计值转月
-func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -28,7 +28,7 @@ func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo,
 	}()
 
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_LJZZY
 		edbInfo.SourceName = "累计值转月值"
 		edbInfo.EdbCode = edbCode
@@ -46,9 +46,10 @@ func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo,
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return int(newEdbInfoId), tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 
 		//关联关系
 		{
@@ -57,7 +58,7 @@ func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo,
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -72,7 +73,10 @@ func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo,
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_LJZZY)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
@@ -81,127 +85,15 @@ func AddCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo,
 			return
 		}
 	}
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
-	if err != nil {
-		return edbInfoId, err
-	}
-
-	yearMap := make(map[int]map[int]*EdbInfoSearchData)
-	dataLen := len(dataList)
-	for i := 0; i < dataLen; i++ {
-		item := dataList[i]
-		//日其中获取年
-		itemDate, err := time.Parse(utils.FormatDate, item.DataTime)
-		if err != nil {
-			return edbInfoId, err
-		}
-		year := itemDate.Year()
-		month := int(itemDate.Month())
-		if monthMap, yok := yearMap[year]; yok {
-			monthMap[month] = item
-			yearMap[year] = monthMap
-		} else {
-			monthMap = make(map[int]*EdbInfoSearchData)
-			monthMap[month] = item
-			yearMap[year] = monthMap
-		}
-	}
-
-	addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	for yk, yv := range yearMap {
-		_, oneMonthOk := yv[1]
-		_, twoMonthOk := yv[2]
-		if !oneMonthOk && !twoMonthOk {
-			continue
-		}
-		for i := 1; i <= 12; i++ {
-			fmt.Println(yk, i, yv[i])
-			dataCurrentItem := yv[i]
-			fmt.Println("i:", i, yk, dataCurrentItem)
-			var date string
-			var val float64
-			if i == 1 || i == 2 {
-				if _, mok := yv[1]; mok { //1月有值
-					if i == 1 {
-						date = dataCurrentItem.DataTime
-						val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
-					}
-					if i == 2 {
-						dataOneItem := yv[1]
-						if dataCurrentItem != nil {
-							date = dataCurrentItem.DataTime
-							twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
-							oneMonth := decimal.NewFromFloat(dataOneItem.Value)
-							val, _ = twoMonth.Sub(oneMonth).Float64()
-						} else {
-							continue
-						}
-					}
-				} else { //1月无值
-					dataTwoItem := yv[2]
-					if i == 1 {
-						date = strconv.Itoa(yk) + "-01-31"
-						a := decimal.NewFromFloat(dataTwoItem.Value)
-						b := decimal.NewFromFloat(2.0)
-						val, _ = a.Div(b).Float64()
-					}
-					if i == 2 {
-						date = dataCurrentItem.DataTime
-						a := decimal.NewFromFloat(dataTwoItem.Value)
-						b := decimal.NewFromFloat(2.0)
-						val, _ = a.Div(b).Float64()
-					}
-				}
-			} else {
-				dataPreItem := yv[i-1]
-				if dataCurrentItem != nil && dataPreItem != nil {
-					date = dataCurrentItem.DataTime
-					//val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Sub(decimal.NewFromFloat(dataPreItem.Value)).Float64()
-					a := decimal.NewFromFloat(dataCurrentItem.Value)
-					b := decimal.NewFromFloat(dataPreItem.Value)
-					val, _ = a.Sub(b).Float64()
-				}
-			}
 
-			if date != "" {
-				dataTime, _ := time.Parse(utils.FormatDate, date)
-				timestamp := dataTime.UnixNano() / 1e6
-				timeStr := fmt.Sprintf("%d", timestamp)
+	//计算数据
+	err = refreshAllCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-				if _, ok := existMap[edbCode+date]; !ok {
-					addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, utils.SubFloatToString(val, 4))
-					isAdd = true
-				}
-				existMap[edbCode+date] = date
-			}
-		}
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateLjzzy 编辑累计值转月数据
-func EditCalculateLjzzy(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateLjzzy(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -217,27 +109,21 @@ func EditCalculateLjzzy(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo,
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-              edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
 	if err != nil {
 		return
 	}
 
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
 	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
@@ -245,173 +131,51 @@ func EditCalculateLjzzy(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo,
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 {
-		//删除指标关联计算指标
-		//sql := ` DELETE FROM edb_info_calculate_ljzzy WHERE edb_info_id = ? `
-		//_, err = o.Raw(sql, edbInfoId).Exec()
-		//if err != nil {
-		//	return
-		//}
-
-		//calculateItem := new(EdbInfoCalculateLjzzy)
-		//calculateItem.CreateTime = time.Now()
-		//calculateItem.ModifyTime = time.Now()
-		//calculateItem.Sort = 1
-		//calculateItem.EdbCode = edbCode
-		//calculateItem.EdbInfoId = edbInfoId
-		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
-		//calculateItem.FromEdbName = fromEdbInfo.EdbName
-		//calculateItem.FromSource = fromEdbInfo.Source
-		//calculateItem.FromSourceName = fromEdbInfo.SourceName
-		//_, err = o.Insert(calculateItem)
-		//if err != nil {
-		//	return
-		//}
+	if count > 0 { // 指标未被替换,无需重新计算
+		return
+	}
 
-		//删除,计算指标关联的,基础指标的关联关系
-		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return
-		}
+	//删除,计算指标关联的,基础指标的关联关系
+	sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
 
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_ljzzy WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
+	//清空原有数据
+	sql = ` DELETE FROM edb_data_calculate_ljzzy WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
 
-		//关联关系
-		{
-			calculateMappingItem := new(EdbInfoCalculateMapping)
-			calculateMappingItem.CreateTime = time.Now()
-			calculateMappingItem.ModifyTime = time.Now()
-			calculateMappingItem.Sort = 1
-			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
-			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-			calculateMappingItem.FromSource = fromEdbInfo.Source
-			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-			calculateMappingItem.FromTag = ""
-			calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_LJZZY
-			calculateMappingItem.SourceName = "累计值转月"
-			_, err = o.Insert(calculateMappingItem)
-			if err != nil {
-				return
-			}
+	//关联关系
+	{
+		calculateMappingItem := &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    utils.DATA_SOURCE_CALCULATE_LJZZY,
+			SourceName:                "累计值转月",
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+			FromEdbCode:               fromEdbInfo.EdbCode,
+			FromEdbName:               fromEdbInfo.EdbName,
+			FromSource:                fromEdbInfo.Source,
+			FromSourceName:            fromEdbInfo.SourceName,
+			FromTag:                   "",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
 		}
-
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
+		_, err = to.Insert(calculateMappingItem)
 		if err != nil {
-			return edbInfoId, err
-		}
-
-		yearMap := make(map[int]map[int]*EdbInfoSearchData)
-		dataLen := len(dataList)
-		for i := 0; i < dataLen; i++ {
-			item := dataList[i]
-			//日其中获取年
-			itemDate, err := time.Parse(utils.FormatDate, item.DataTime)
-			if err != nil {
-				return edbInfoId, err
-			}
-			year := itemDate.Year()
-			month := int(itemDate.Month())
-			if monthMap, yok := yearMap[year]; yok {
-				monthMap[month] = item
-				yearMap[year] = monthMap
-			} else {
-				monthMap = make(map[int]*EdbInfoSearchData)
-				monthMap[month] = item
-				yearMap[year] = monthMap
-			}
+			return
 		}
+	}
 
-		addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		nowStr := time.Now().Format(utils.FormatDateTime)
-		var isAdd bool
-
-		for yk, yv := range yearMap {
-			_, oneMonthOk := yv[1]
-			_, twoMonthOk := yv[2]
-			if !oneMonthOk && !twoMonthOk {
-				continue
-			}
-			for i := 1; i <= 12; i++ {
-				fmt.Println(yk, i, yv[i])
-				dataCurrentItem := yv[i]
-				var date string
-				var val float64
-				if i == 1 || i == 2 {
-					if _, mok := yv[1]; mok { //1月有值
-						if i == 1 {
-							date = dataCurrentItem.DataTime
-							val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
-						}
-						if i == 2 {
-							dataOneItem := yv[1]
-							date = dataCurrentItem.DataTime
-							twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
-							oneMonth := decimal.NewFromFloat(dataOneItem.Value)
-							val, _ = twoMonth.Sub(oneMonth).Float64()
-						}
-					} else { //1月无值
-						dataTwoItem := yv[2]
-						if i == 1 {
-							date = strconv.Itoa(yk) + "-01-31"
-							a := decimal.NewFromFloat(dataTwoItem.Value)
-							b := decimal.NewFromFloat(2.0)
-							val, _ = a.Div(b).Float64()
-						}
-						if i == 2 {
-							date = dataCurrentItem.DataTime
-							a := decimal.NewFromFloat(dataTwoItem.Value)
-							b := decimal.NewFromFloat(2.0)
-							val, _ = a.Div(b).Float64()
-						}
-					}
-				} else {
-					dataPreItem := yv[i-1]
-					if dataCurrentItem != nil && dataPreItem != nil {
-						date = dataCurrentItem.DataTime
-						//val = dataCurrentItem.Value - dataPreItem.Value
-						a := decimal.NewFromFloat(dataCurrentItem.Value)
-						b := decimal.NewFromFloat(dataPreItem.Value)
-						val, _ = a.Sub(b).Float64()
-					}
-				}
-				if date != "" {
-					dataTime, _ := time.Parse(utils.FormatDate, date)
-					timestamp := dataTime.UnixNano() / 1e6
-					timeStr := fmt.Sprintf("%d", timestamp)
+	//计算数据
+	err = refreshAllCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-					addSql += "("
-					addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + date + "'" + "," + utils.SubFloatToString(val, 4) + "," + "'" + nowStr + "'" +
-						"," + "'" + nowStr + "'" + "," + "1"
-					addSql += "," + "'" + timeStr + "'"
-					addSql += "),"
-					isAdd = true
-				}
-			}
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
-		}
-	}
 	return
 }
 
@@ -431,9 +195,13 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	// 计算数据
+	err = refreshAllCalculateLjzzy(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
+
+	return
+}
+
+func refreshAllCalculateLjzzy(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
 	var condition string
@@ -450,7 +218,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 	//	pars = append(pars, endDate)
 	//}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 1)
 	if err != nil {
 		return err
 	}
@@ -483,7 +251,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 	dataTableName := GetEdbDataTableName(source)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -533,7 +301,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 								b := decimal.NewFromFloat(2.0)
 								val, _ = a.Div(b).Float64()
 
-								tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, o)
+								tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
 								if !isAdd {
 									isAdd = newAdd
 								}
@@ -583,7 +351,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 				//		}
 				//	}
 				//}
-				tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, o)
+				tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
 				if !isAdd {
 					isAdd = newAdd
 				}
@@ -596,7 +364,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 	}
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			fmt.Println("RefreshAllCalculateLjzzy add Err", err.Error())
 			return
@@ -605,7 +373,7 @@ func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCo
 	return
 }
 
-func calculateLjzzy(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, o orm.Ormer) (newSql string, isAdd bool, err error) {
+func calculateLjzzy(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, o orm.TxOrmer) (newSql string, isAdd bool, err error) {
 	newSql = addSql
 	saveValue := utils.SubFloatToString(val, 4)
 	//判断数据是否存在

+ 75 - 208
models/edb_data_calculate_nszydbpjjs.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateNszydpjjs N数值移动平均计算
-func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
+func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	defer func() {
@@ -24,7 +24,7 @@ func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
 		edbInfo.SourceName = "N数值移动平均计算"
 		edbInfo.EdbCode = edbCode
@@ -42,9 +42,10 @@ func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 
 		//关联关系
 		{
@@ -53,7 +54,7 @@ func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -68,7 +69,10 @@ func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NSZYDPJJS)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
@@ -78,122 +82,41 @@ func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
-	var dateArr []string
-	dataMap := make(map[string]*EdbInfoSearchData)
-	for _, v := range dataList {
-		dateArr = append(dateArr, v.DataTime)
-		dataMap[v.DataTime] = v
-	}
-
-	addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-
-	arrLen := len(dateArr)
-	for ak, av := range dateArr {
-		//处理第一个值
-		var valArr []float64
-		if findItem, ok := dataMap[av]; ok {
-			valArr = append(valArr, findItem.Value)
-		} else {
-			continue
-		}
-		if ak+1 != arrLen {
-			//处理除第一个值之外的N-1个值
-			for i := 1; i < formulaInt; i++ {
-				arrIndex := ak + i
-				if arrIndex >= arrLen {
-					break
-				}
-				arrVal := dateArr[arrIndex]
-				if findItem, ok := dataMap[arrVal]; ok {
-					valArr = append(valArr, findItem.Value)
-				} else {
-					continue
-				}
-			}
-		}
-		valArrLen := len(valArr)
-		totalVal := decimal.NewFromFloat(0.00)
-		for _, v := range valArr {
-			newDecimal := decimal.NewFromFloat(v)
-			totalVal = totalVal.Add(newDecimal)
-		}
-		af := totalVal //decimal.NewFromFloat(totalVal)
-		bf := decimal.NewFromFloat(float64(valArrLen))
-		val, _ := af.Div(bf).Float64()
-		currentDate, err := time.Parse(utils.FormatDate, av)
-		if err != nil {
-			return edbInfoId, err
-		}
-
-		timestamp := currentDate.UnixNano() / 1e6
-		timestampStr := fmt.Sprintf("%d", timestamp)
-		valStr := utils.SubFloatToString(val, 4)
-		addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
-		isAdd = true
-	}
-
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
+	err = refreshAllCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
 	return
 }
 
 // EditCalculateNszydpjjs 修改N数值移动平均计算
-func EditCalculateNszydpjjs(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, formulaInt int, oldCalculateFormula string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
-
+func EditCalculateNszydpjjs(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	defer func() {
 		if err != nil {
-			fmt.Println("AddCalculateNszydpjjs,Err:" + err.Error())
+			fmt.Println("EditCalculateNszydpjjs,Err:" + err.Error())
 			_ = to.Rollback()
 		} else {
 			_ = to.Commit()
 		}
 	}()
+
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-              edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
 	if err != nil {
 		return
 	}
 
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
 	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
@@ -201,115 +124,55 @@ func EditCalculateNszydpjjs(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbI
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 || oldCalculateFormula != req.Formula {
-		//删除,计算指标关联的,基础指标的关联关系
-		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_nszydpjjs WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		//关联关系
-		{
-			calculateMappingItem := new(EdbInfoCalculateMapping)
-			calculateMappingItem.CreateTime = time.Now()
-			calculateMappingItem.ModifyTime = time.Now()
-			calculateMappingItem.Sort = 1
-			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
-			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-			calculateMappingItem.FromSource = fromEdbInfo.Source
-			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-			calculateMappingItem.FromTag = ""
-			calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
-			calculateMappingItem.SourceName = "N数值移动平均计算"
-			_, err = o.Insert(calculateMappingItem)
-			if err != nil {
-				return
-			}
-		}
+	fmt.Println("oldCalculateFormula:", oldCalculateFormula)
+	fmt.Println("req.Formula:", req.Formula)
+	fmt.Println("count:", count)
+	if count > 0 && oldCalculateFormula == req.Formula { // 指标未被替换,同时N值未修改,无需重新计算
+		return
+	}
 
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	if count <= 0 {
+		// 需要删除原先的 计算指标关联的,基础指标的关联关系
+		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+		_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
 		if err != nil {
-			return edbInfoId, err
-		}
-		var dateArr []string
-		dataMap := make(map[string]*EdbInfoSearchData)
-		for _, v := range dataList {
-			dateArr = append(dateArr, v.DataTime)
-			dataMap[v.DataTime] = v
+			return
 		}
 
-		addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-
-		arrLen := len(dateArr)
-		for ak, av := range dateArr {
-			//处理第一个值
-			var valArr []float64
-			if findItem, ok := dataMap[av]; ok {
-				valArr = append(valArr, findItem.Value)
-			} else {
-				continue
-			}
-			if ak+1 != arrLen {
-				//处理除第一个值之外的N-1个值
-				for i := 1; i < formulaInt; i++ {
-					arrIndex := ak + i
-					if arrIndex >= arrLen {
-						break
-					}
-					arrVal := dateArr[arrIndex]
-					if findItem, ok := dataMap[arrVal]; ok {
-						valArr = append(valArr, findItem.Value)
-					} else {
-						continue
-					}
-				}
-			}
-			valArrLen := len(valArr)
-			totalVal := decimal.NewFromFloat(0.00)
-			for _, v := range valArr {
-				newDecimal := decimal.NewFromFloat(v)
-				totalVal = totalVal.Add(newDecimal)
-			}
-			af := totalVal
-			bf := decimal.NewFromFloat(float64(valArrLen))
-			val, _ := af.Div(bf).Float64()
-			currentDate, err := time.Parse(utils.FormatDate, av)
-			if err != nil {
-				return edbInfoId, err
+		// 添加新的关联关系
+		{
+			calculateMappingItem := &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    utils.DATA_SOURCE_CALCULATE_NSZYDPJJS,
+				SourceName:                "N数值移动平均计算",
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+				FromEdbCode:               fromEdbInfo.EdbCode,
+				FromEdbName:               fromEdbInfo.EdbName,
+				FromSource:                fromEdbInfo.Source,
+				FromSourceName:            fromEdbInfo.SourceName,
+				FromTag:                   "",
+				Sort:                      1,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-
-			timestamp := currentDate.UnixNano() / 1e6
-			timestampStr := fmt.Sprintf("%d", timestamp)
-
-			valStr := utils.SubFloatToString(val, 4)
-			addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
-			isAdd = true
-		}
-
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
+			_, err = to.Insert(calculateMappingItem)
 			if err != nil {
-				return edbInfoId, err
+				return
 			}
 		}
 	}
+	//清空原有数据
+	sql := ` DELETE FROM edb_data_calculate_nszydpjjs WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+
+	//计算数据
+	err = refreshAllCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
+
 	return
 }
 
@@ -327,9 +190,13 @@ func RefreshAllCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	//计算数据
+	err = refreshAllCalculateNszydpjjs(to, edbInfoId, source, formulaInt, fromEdbInfo, edbCode, startDate)
+	return
+}
+
+// refreshAllCalculateNszydpjjs 更新全部N数值移动平均计算
+func refreshAllCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	fmt.Println(edbInfoIdStr)
 	//计算数据
@@ -338,7 +205,7 @@ func RefreshAllCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo
 	condition += " AND edb_info_id=? "
 	pars = append(pars, edbInfoId)
 
-	existDataList, err := GetEdbDataListAllV1(condition, pars, source, 0)
+	existDataList, err := GetEdbDataListAllV1ByTo(to, condition, pars, source, 0)
 	if err != nil {
 		fmt.Println("existDataList GetEdbDataListAll Err:" + err.Error())
 		return err
@@ -358,7 +225,7 @@ func RefreshAllCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo
 	fromPars = append(fromPars, startDate)
 
 	fmt.Println("fromPars:", fromPars)
-	fromDataList, err := GetEdbDataListAllV1(fromCondition, fromPars, fromEdbInfo.Source, 0)
+	fromDataList, err := GetEdbDataListAllV1ByTo(to, fromCondition, fromPars, fromEdbInfo.Source, 0)
 	if err != nil {
 		fmt.Println("from GetEdbDataListAll Err:" + err.Error())
 		return err
@@ -430,7 +297,7 @@ func RefreshAllCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo
 			if existStr != valStr {
 				sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 				sql = fmt.Sprintf(sql, dataTableName)
-				_, err = o.Raw(sql, valStr, edbInfoId, av).Exec()
+				_, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
 				if err != nil {
 					return err
 				}
@@ -440,7 +307,7 @@ func RefreshAllCalculateNszydpjjs(edbInfoId, source, formulaInt int, fromEdbInfo
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
 		utils.FileLog.Info("addSql:" + addSql)
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}

+ 74 - 363
models/edb_data_calculate_tbz.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateTbz 同比值
-func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -27,7 +27,7 @@ func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TBZ
 		edbInfo.SourceName = "同比值"
 		edbInfo.EdbCode = edbCode
@@ -45,9 +45,10 @@ func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 
 		//关联关系
 		{
@@ -56,7 +57,7 @@ func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -72,7 +73,10 @@ func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TBZ)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
@@ -82,153 +86,14 @@ func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
-	var dateArr []string
-	dataMap := make(map[string]*EdbInfoSearchData)
-	for _, v := range dataList {
-		dateArr = append(dateArr, v.DataTime)
-		dataMap[v.DataTime] = v
-	}
+	err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbCode, "", "")
 
-	addSql := ` INSERT INTO edb_data_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	for _, av := range dateArr {
-		//fmt.Println(ak, av)
-		currentItem := dataMap[av]
-		if currentItem != nil {
-			//当前日期
-			currentDate, err := time.Parse(utils.FormatDate, av)
-			if err != nil {
-				return edbInfoId, err
-			}
-			//上一年的日期
-			preDate := currentDate.AddDate(-1, 0, 0)
-			preDateStr := preDate.Format(utils.FormatDate)
-			if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
-				//dataTime, _ := time.Parse(utils.FormatDate, date)
-				if _, ok := existMap[edbCode+av]; !ok {
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-					val := TbzDiv(currentItem.Value, findItem.Value)
-					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-					isAdd = true
-					utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
-				}
-				existMap[edbCode+av] = av
-			} else {
-				if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
-					nextDateDay := preDate
-					preDateDay := preDate
-					for i := 0; i <= 35; i++ {
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-							if _, ok := existMap[edbCode+av]; !ok {
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TbzDiv(currentItem.Value, findItem.Value)
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-							}
-							existMap[edbCode+av] = av
-							break
-						} else {
-							preDateDayStr := preDateDay.Format(utils.FormatDate)
-							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-								if _, ok := existMap[edbCode+av]; !ok {
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TbzDiv(currentItem.Value, findItem.Value)
-
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-								}
-								existMap[edbCode+av] = av
-								break
-							}
-						}
-						nextDateDay = nextDateDay.AddDate(0, 0, 1)
-						preDateDay = preDateDay.AddDate(0, 0, -1)
-					}
-				} else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
-					if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
-						if _, ok := existMap[edbCode+av]; !ok {
-							timestamp := currentDate.UnixNano() / 1e6
-							timestampStr := fmt.Sprintf("%d", timestamp)
-							val := TbzDiv(currentItem.Value, findItem.Value)
-
-							addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-							isAdd = true
-						}
-						existMap[edbCode+av] = av
-						break
-					}
-				} else {
-					nextDateDay := preDate
-					preDateDay := preDate
-
-					for i := 0; i < 35; i++ {
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-							if _, ok := existMap[edbCode+av]; !ok {
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TbzDiv(currentItem.Value, findItem.Value)
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-							}
-							existMap[edbCode+av] = av
-							break
-						} else {
-							preDateDayStr := preDateDay.Format(utils.FormatDate)
-							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-								if _, ok := existMap[edbCode+av]; !ok {
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TbzDiv(currentItem.Value, findItem.Value)
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-								}
-								existMap[edbCode+av] = av
-								break
-							} else {
-								//fmt.Println("pre not find:", preDateStr, "i:", i)
-							}
-						}
-						nextDateDay = nextDateDay.AddDate(0, 0, 1)
-						preDateDay = preDateDay.AddDate(0, 0, -1)
-					}
-				}
-			}
-		}
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateTbz 同比值
-func EditCalculateTbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateTbz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -244,229 +109,71 @@ func EditCalculateTbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
 	if err != nil {
 		return
 	}
 
+	//判断计算指标是否被更换
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
-	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
 	if err != nil {
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 {
-		//删除指标关联计算指标
-		//sql := ` DELETE FROM edb_info_calculate_tbz WHERE edb_info_id = ? `
-		//_, err = o.Raw(sql, edbInfoId).Exec()
-		//if err != nil {
-		//	return
-		//}
-		//
-		//calculateItem := new(EdbInfoCalculateTbz)
-		//calculateItem.CreateTime = time.Now()
-		//calculateItem.ModifyTime = time.Now()
-		//calculateItem.Sort = 1
-		//calculateItem.EdbCode = edbCode
-		//calculateItem.EdbInfoId = edbInfoId
-		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
-		//calculateItem.FromEdbName = fromEdbInfo.EdbName
-		//calculateItem.FromSource = fromEdbInfo.Source
-		//calculateItem.FromSourceName = fromEdbInfo.SourceName
-		//
-		//_, err = o.Insert(calculateItem)
-		//if err != nil {
-		//	return
-		//}
+	if count > 0 { // 指标未被替换,无需重新计算
+		return
+	}
 
-		//删除,计算指标关联的,基础指标的关联关系
-		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_tbz WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-		//关联关系
-		{
-			calculateMappingItem := new(EdbInfoCalculateMapping)
-			calculateMappingItem.CreateTime = time.Now()
-			calculateMappingItem.ModifyTime = time.Now()
-			calculateMappingItem.Sort = 1
-			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
-			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-			calculateMappingItem.FromSource = fromEdbInfo.Source
-			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-			calculateMappingItem.FromTag = ""
-			calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TBZ
-			calculateMappingItem.SourceName = "同比值"
-			_, err = o.Insert(calculateMappingItem)
-			if err != nil {
-				return
-			}
+	//删除,计算指标关联的,基础指标的关联关系
+	sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+	//清空原有数据
+	sql = ` DELETE FROM edb_data_calculate_tbz WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
+	//关联关系
+	{
+		calculateMappingItem := &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    utils.DATA_SOURCE_CALCULATE_TBZ,
+			SourceName:                "同比值",
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+			FromEdbCode:               fromEdbInfo.EdbCode,
+			FromEdbName:               fromEdbInfo.EdbName,
+			FromSource:                fromEdbInfo.Source,
+			FromSourceName:            fromEdbInfo.SourceName,
+			FromTag:                   "",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
 		}
-
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+		_, err = to.Insert(calculateMappingItem)
 		if err != nil {
-			return edbInfoId, err
-		}
-		var dateArr []string
-		dataMap := make(map[string]*EdbInfoSearchData)
-		for _, v := range dataList {
-			dateArr = append(dateArr, v.DataTime)
-			dataMap[v.DataTime] = v
+			return
 		}
+	}
 
-		addSql := ` INSERT INTO edb_data_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		for _, av := range dateArr {
-			currentItem := dataMap[av]
-			if currentItem != nil {
-				//当前日期
-				currentDate, err := time.Parse(utils.FormatDate, av)
-				if err != nil {
-					return edbInfoId, err
-				}
-				//上一年的日期
-				preDate := currentDate.AddDate(-1, 0, 0)
-				preDateStr := preDate.Format(utils.FormatDate)
-				if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
-					//dataTime, _ := time.Parse(utils.FormatDate, date)
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-					val := TbzDiv(currentItem.Value, findItem.Value)
-					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-					isAdd = true
-					utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
-					continue
-				} else {
-					if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
-						nextDateDay := preDate.AddDate(0, 1, 0)
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-
-						preDateDay := preDate.AddDate(0, -1, 0)
-						preDateDayStr := preDateDay.Format(utils.FormatDate)
-
-						for i := 0; i <= 6; i++ {
-							if i >= 1 {
-								nextDateDay = nextDateDay.AddDate(0, 0, i)
-								nextDateDayStr = nextDateDay.Format(utils.FormatDate)
-							}
-							if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TbzDiv(currentItem.Value, findItem.Value)
-
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-								break
-							} else {
-								if i >= 1 {
-									preDateDay = preDate.AddDate(0, 0, -i)
-									preDateDayStr = nextDateDay.Format(utils.FormatDate)
-								}
-								if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TbzDiv(currentItem.Value, findItem.Value)
-
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-									break
-								}
-							}
-						}
-					} else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
-						if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
-							timestamp := currentDate.UnixNano() / 1e6
-							timestampStr := fmt.Sprintf("%d", timestamp)
-							val := TbzDiv(currentItem.Value, findItem.Value)
-
-							addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-							isAdd = true
-							break
-						}
-					} else {
-						nextDateDay := preDate.AddDate(0, 0, 1)
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-
-						preDateDay := preDate.AddDate(0, 0, -1)
-						preDateDayStr := preDateDay.Format(utils.FormatDate)
-
-						for i := 0; i < 35; i++ {
-							if i >= 1 {
-								nextDateDay = nextDateDay.AddDate(0, 0, i)
-								nextDateDayStr = nextDateDay.Format(utils.FormatDate)
-							}
-							if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TbzDiv(currentItem.Value, findItem.Value)
-
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-								break
-							} else {
-								if i >= 1 {
-									preDateDay = preDate.AddDate(0, 0, -i)
-									preDateDayStr = nextDateDay.Format(utils.FormatDate)
-								}
-								if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TbzDiv(currentItem.Value, findItem.Value)
+	//计算数据
+	err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-									break
-								}
-							}
-						}
-					}
-				}
-			}
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
-		}
-	}
 	return
 }
 
@@ -486,9 +193,13 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	//计算数据
+	err = refreshAllCalculateTbz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
+	return
+}
+
+// refreshAllCalculateTbz
+func refreshAllCalculateTbz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
 
@@ -524,7 +235,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	fmt.Println("dataTableName:", dataTableName)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -565,7 +276,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 					if existStr != val {
 						sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 						sql = fmt.Sprintf(sql, dataTableName)
-						_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+						_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 						if err != nil {
 							return err
 						}
@@ -594,7 +305,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 								if existStr != val {
 									sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 									sql = fmt.Sprintf(sql, dataTableName)
-									_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+									_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 									if err != nil {
 										return err
 									}
@@ -621,7 +332,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 									if existStr != val {
 										sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 										sql = fmt.Sprintf(sql, dataTableName)
-										_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+										_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 										if err != nil {
 											return err
 										}
@@ -649,7 +360,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							if existStr != val {
 								sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 								sql = fmt.Sprintf(sql, dataTableName)
-								_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+								_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 								if err != nil {
 									return err
 								}
@@ -686,7 +397,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 								if existStr != val {
 									sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 									sql = fmt.Sprintf(sql, dataTableName)
-									_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+									_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 									if err != nil {
 										return err
 									}
@@ -715,7 +426,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 									if existStr != val {
 										sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 										sql = fmt.Sprintf(sql, dataTableName)
-										_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+										_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 										if err != nil {
 											return err
 										}
@@ -731,7 +442,7 @@ func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	}
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}

+ 81 - 375
models/edb_data_calculate_tcz.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateTcz 同差值
-func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -28,7 +28,7 @@ func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 	}()
 	fmt.Println("req.EdbInfoId:", req.EdbInfoId)
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TCZ
 		edbInfo.SourceName = "同差值"
 		edbInfo.EdbCode = edbCode
@@ -46,9 +46,10 @@ func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 		edbInfo.EdbType = 2
 		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 
 		//关联关系
 		{
@@ -57,7 +58,7 @@ func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -72,167 +73,28 @@ func AddCalculateTcz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, ed
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TCZ)
 		fmt.Println("dataTableName:", dataTableName)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
 		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
 		if err != nil {
-			return edbInfoId, err
+			return
 		}
 	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
-
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-
-	fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
-	var dateArr []string
-	dataMap := make(map[string]*EdbInfoSearchData)
-	for _, v := range dataList {
-		dateArr = append(dateArr, v.DataTime)
-		dataMap[v.DataTime] = v
-	}
-	fmt.Println("Frequency:", fromEdbInfo.Frequency)
-	addSql := ` INSERT INTO edb_data_calculate_tcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	for _, av := range dateArr {
-		//fmt.Println("dateArr:", ak, av)
-		currentItem := dataMap[av]
-		if currentItem != nil {
-			//当前日期
-			currentDate, err := time.Parse(utils.FormatDate, av)
-			if err != nil {
-				return edbInfoId, err
-			}
-			//上一年的日期
-			preDate := currentDate.AddDate(-1, 0, 0)
-			preDateStr := preDate.Format(utils.FormatDate)
-			if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
-				//dataTime, _ := time.Parse(utils.FormatDate, date)
-				if _, ok := existMap[edbCode+av]; !ok {
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-
-					val := TczSub(currentItem.Value, findItem.Value)
-					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-					isAdd = true
-				}
-				existMap[edbCode+av] = av
-			} else {
-				if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
-					nextDateDay := preDate
-					preDateDay := preDate
-					for i := 0; i <= 35; i++ {
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-						if findItem, ok := dataMap[nextDateDayStr]; ok { //下一年同期->下一个月找到
-							if _, ok := existMap[edbCode+av]; !ok {
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TczSub(currentItem.Value, findItem.Value)
-
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-							}
-							existMap[edbCode+av] = av
-							break
-						} else {
-							preDateDayStr := preDateDay.Format(utils.FormatDate)
-							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-								if _, ok := existMap[edbCode+av]; !ok {
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TczSub(currentItem.Value, findItem.Value)
-
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-								}
-								existMap[edbCode+av] = av
-								break
-							}
-						}
-						nextDateDay = nextDateDay.AddDate(0, 0, 1)
-						preDateDay = preDateDay.AddDate(0, 0, -1)
-					}
-				} else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
-					if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
-						if _, ok := existMap[edbCode+av]; !ok {
-							timestamp := currentDate.UnixNano() / 1e6
-							timestampStr := fmt.Sprintf("%d", timestamp)
-							val := TczSub(currentItem.Value, findItem.Value)
-							addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-							isAdd = true
-						}
-						existMap[edbCode+av] = av
-						break
-					}
-				} else {
-					nextDateDay := preDate
-					preDateDay := preDate
-					for i := 0; i < 35; i++ {
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-							if _, ok := existMap[edbCode+av]; !ok {
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TczSub(currentItem.Value, findItem.Value)
+	err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-							}
-							existMap[edbCode+av] = av
-							break
-						} else {
-							preDateDayStr := preDateDay.Format(utils.FormatDate)
-							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-								if _, ok := existMap[edbCode+av]; !ok {
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TczSub(currentItem.Value, findItem.Value)
-
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-								}
-								existMap[edbCode+av] = av
-								break
-							} else {
-
-							}
-						}
-						nextDateDay = nextDateDay.AddDate(0, 0, 1)
-						preDateDay = preDateDay.AddDate(0, 0, -1)
-					}
-				}
-			}
-		}
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateTcz 同差值
-func EditCalculateTcz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateTcz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -248,27 +110,21 @@ func EditCalculateTcz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 	}()
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
 	if err != nil {
 		return
 	}
 
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
 	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
@@ -276,205 +132,51 @@ func EditCalculateTcz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, e
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
-	if count <= 0 {
-		//删除指标关联计算指标
-		//sql := ` DELETE FROM edb_info_calculate_tcz WHERE edb_info_id = ? `
-		//_, err = o.Raw(sql, edbInfoId).Exec()
-		//if err != nil {
-		//	return
-		//}
-		//
-		//calculateItem := new(EdbInfoCalculateTcz)
-		//calculateItem.CreateTime = time.Now()
-		//calculateItem.ModifyTime = time.Now()
-		//calculateItem.Sort = 1
-		//calculateItem.EdbCode = edbCode
-		//calculateItem.EdbInfoId = edbInfoId
-		//calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-		//calculateItem.FromEdbCode = fromEdbInfo.EdbCode
-		//calculateItem.FromEdbName = fromEdbInfo.EdbName
-		//calculateItem.FromSource = fromEdbInfo.Source
-		//calculateItem.FromSourceName = fromEdbInfo.SourceName
-		//
-		//_, err = o.Insert(calculateItem)
-		//if err != nil {
-		//	return
-		//}
+	if count > 0 { // 指标未被替换,无需重新计算
+		return
+	}
 
-		//删除,计算指标关联的,基础指标的关联关系
-		sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return
-		}
+	//删除,计算指标关联的,基础指标的关联关系
+	sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
 
-		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_tcz WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
+	//清空原有数据
+	sql = ` DELETE FROM edb_data_calculate_tcz WHERE edb_info_id = ? `
+	_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
+	if err != nil {
+		return
+	}
 
-		//关联关系
-		{
-			calculateMappingItem := new(EdbInfoCalculateMapping)
-			calculateMappingItem.CreateTime = time.Now()
-			calculateMappingItem.ModifyTime = time.Now()
-			calculateMappingItem.Sort = 1
-			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
-			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-			calculateMappingItem.FromSource = fromEdbInfo.Source
-			calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-			calculateMappingItem.FromTag = ""
-			calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TCZ
-			calculateMappingItem.SourceName = "同差值"
-			_, err = o.Insert(calculateMappingItem)
-			if err != nil {
-				return
-			}
+	//关联关系
+	{
+		calculateMappingItem := &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    utils.DATA_SOURCE_CALCULATE_TCZ,
+			SourceName:                "同差值",
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+			FromEdbCode:               fromEdbInfo.EdbCode,
+			FromEdbName:               fromEdbInfo.EdbName,
+			FromSource:                fromEdbInfo.Source,
+			FromSourceName:            fromEdbInfo.SourceName,
+			FromTag:                   "",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
 		}
-
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-
-		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+		_, err = to.Insert(calculateMappingItem)
 		if err != nil {
-			return edbInfoId, err
-		}
-		var dateArr []string
-		dataMap := make(map[string]*EdbInfoSearchData)
-		for _, v := range dataList {
-			dateArr = append(dateArr, v.DataTime)
-			dataMap[v.DataTime] = v
+			return
 		}
+	}
 
-		addSql := ` INSERT INTO edb_data_calculate_tcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		for ak, av := range dateArr {
-			fmt.Println(ak, av)
-			currentItem := dataMap[av]
-			if currentItem != nil {
-				//当前日期
-				currentDate, err := time.Parse(utils.FormatDate, av)
-				if err != nil {
-					return edbInfoId, err
-				}
-				//上一年的日期
-				preDate := currentDate.AddDate(-1, 0, 0)
-				preDateStr := preDate.Format(utils.FormatDate)
-				if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
-					//dataTime, _ := time.Parse(utils.FormatDate, date)
-					timestamp := currentDate.UnixNano() / 1e6
-					timestampStr := fmt.Sprintf("%d", timestamp)
-
-					val := TczSub(currentItem.Value, findItem.Value)
-					addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-					isAdd = true
-					utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
-					continue
-				} else {
-					if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
-						nextDateDay := preDate.AddDate(0, 1, 0)
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-
-						preDateDay := preDate.AddDate(0, -1, 0)
-						preDateDayStr := preDateDay.Format(utils.FormatDate)
-
-						for i := 0; i <= 6; i++ {
-							if i >= 1 {
-								nextDateDay = nextDateDay.AddDate(0, 0, i)
-								nextDateDayStr = nextDateDay.Format(utils.FormatDate)
-							}
-							if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TczSub(currentItem.Value, findItem.Value)
-
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-								break
-							} else {
-								if i >= 1 {
-									preDateDay = preDate.AddDate(0, 0, -i)
-									preDateDayStr = nextDateDay.Format(utils.FormatDate)
-								}
-								if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TczSub(currentItem.Value, findItem.Value)
-
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-									break
-								}
-							}
-						}
-					} else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
-						if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
-							timestamp := currentDate.UnixNano() / 1e6
-							timestampStr := fmt.Sprintf("%d", timestamp)
-							val := TczSub(currentItem.Value, findItem.Value)
-
-							addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-							isAdd = true
-							break
-						}
-					} else {
-						nextDateDay := preDate.AddDate(0, 0, 1)
-						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
-
-						preDateDay := preDate.AddDate(0, 0, -1)
-						preDateDayStr := preDateDay.Format(utils.FormatDate)
-
-						for i := 0; i < 35; i++ {
-							if i >= 1 {
-								nextDateDay = nextDateDay.AddDate(0, 0, i)
-								nextDateDayStr = nextDateDay.Format(utils.FormatDate)
-							}
-							if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
-								timestamp := currentDate.UnixNano() / 1e6
-								timestampStr := fmt.Sprintf("%d", timestamp)
-								val := TczSub(currentItem.Value, findItem.Value)
-
-								addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-								isAdd = true
-								break
-							} else {
-								if i >= 1 {
-									preDateDay = preDate.AddDate(0, 0, -i)
-									preDateDayStr = nextDateDay.Format(utils.FormatDate)
-								}
-								if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
-									timestamp := currentDate.UnixNano() / 1e6
-									timestampStr := fmt.Sprintf("%d", timestamp)
-									val := TczSub(currentItem.Value, findItem.Value)
+	//计算数据
+	err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
 
-									addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
-									isAdd = true
-									break
-								}
-							}
-						}
-					}
-				}
-			}
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
-		}
-	}
 	return
 }
 
@@ -494,9 +196,12 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 		}
 	}()
 
-	if err != nil {
-		return
-	}
+	err = refreshAllCalculateTcz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
+
+	return
+}
+
+func refreshAllCalculateTcz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
 	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
 
@@ -515,7 +220,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	//	pars = append(pars, endDate)
 	//}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
 	if err != nil {
 		return err
 	}
@@ -530,7 +235,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	dataTableName := GetEdbDataTableName(source)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -553,7 +258,8 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 			//上一年的日期
 			preDate := currentDate.AddDate(-1, 0, 0)
 			preDateStr := preDate.Format(utils.FormatDate)
-			if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
+			if findItem, ok := dataMap[preDateStr]; ok {
+				//上一年同期找到
 				//dataTime, _ := time.Parse(utils.FormatDate, date)
 				timestamp := currentDate.UnixNano() / 1e6
 				timestampStr := fmt.Sprintf("%d", timestamp)
@@ -571,7 +277,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 					if existStr != val {
 						sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 						sql = fmt.Sprintf(sql, dataTableName)
-						_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+						_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 						if err != nil {
 							return err
 						}
@@ -582,7 +288,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 			} else {
 				if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
 					for i := 0; i <= 35; i++ {
-						nextDateDay := preDate.AddDate(0, 0, 1)
+						nextDateDay := preDate.AddDate(0, 0, i)
 						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
 						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
 							timestamp := currentDate.UnixNano() / 1e6
@@ -601,7 +307,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 								if existStr != val {
 									sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 									sql = fmt.Sprintf(sql, dataTableName)
-									_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+									_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 									if err != nil {
 										return err
 									}
@@ -609,7 +315,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							}
 							break
 						} else {
-							preDateDay := preDate.AddDate(0, 0, -1)
+							preDateDay := preDate.AddDate(0, 0, -i)
 							preDateDayStr := preDateDay.Format(utils.FormatDate)
 							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
 								timestamp := currentDate.UnixNano() / 1e6
@@ -628,7 +334,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 									if existStr != val {
 										sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 										sql = fmt.Sprintf(sql, dataTableName)
-										_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+										_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 										if err != nil {
 											return err
 										}
@@ -656,7 +362,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							if existStr != val {
 								sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 								sql = fmt.Sprintf(sql, dataTableName)
-								_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+								_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 								if err != nil {
 									return err
 								}
@@ -666,7 +372,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 					}
 				} else {
 					for i := 0; i < 35; i++ {
-						nextDateDay := preDate.AddDate(0, 0, 1)
+						nextDateDay := preDate.AddDate(0, 0, i)
 						nextDateDayStr := nextDateDay.Format(utils.FormatDate)
 						if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
 							timestamp := currentDate.UnixNano() / 1e6
@@ -685,7 +391,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 								if existStr != val {
 									sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 									sql = fmt.Sprintf(sql, dataTableName)
-									_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+									_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 									if err != nil {
 										return err
 									}
@@ -693,7 +399,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 							}
 							break
 						} else {
-							preDateDay := preDate.AddDate(0, 0, -1)
+							preDateDay := preDate.AddDate(0, 0, -i)
 							preDateDayStr := preDateDay.Format(utils.FormatDate)
 							if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
 								timestamp := currentDate.UnixNano() / 1e6
@@ -712,7 +418,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 									if existStr != val {
 										sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 										sql = fmt.Sprintf(sql, dataTableName)
-										_, err = o.Raw(sql, val, edbInfoId, av).Exec()
+										_, err = to.Raw(sql, val, edbInfoId, av).Exec()
 										if err != nil {
 											return err
 										}
@@ -728,7 +434,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 	}
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}
@@ -739,7 +445,7 @@ func RefreshAllCalculateTcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode
 // TczSub 计算同差值
 func TczSub(a, b float64) string {
 	af := decimal.NewFromFloat(a)
-	fmt.Println(af)
+	//fmt.Println(af)
 	bf := decimal.NewFromFloat(b)
 	val, _ := af.Sub(bf).Float64()
 	//valStr := utils.SubFloatToString(val, 4)

+ 67 - 173
models/edb_data_calculate_time_shift.go

@@ -12,7 +12,7 @@ import (
 )
 
 // AddCalculateTimeShift 时间移位
-func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -28,7 +28,7 @@ func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 		}
 	}()
 	if req.EdbInfoId <= 0 {
-		edbInfo := new(EdbInfo)
+		edbInfo = new(EdbInfo)
 		edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
 		edbInfo.SourceName = "时间移位"
 		edbInfo.EdbCode = edbCode
@@ -46,11 +46,12 @@ func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 		edbInfo.EdbType = 2
 		edbInfo.MoveType = req.MoveType
 		edbInfo.MoveFrequency = req.MoveFrequency
-		newEdbInfoId, tmpErr := o.Insert(edbInfo)
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
 		if tmpErr != nil {
-			return edbInfoId, tmpErr
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 		//关联关系
 		{
 			calculateMappingItem := new(EdbInfoCalculateMapping)
@@ -58,7 +59,7 @@ func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 			calculateMappingItem.ModifyTime = time.Now()
 			calculateMappingItem.Sort = 1
 			calculateMappingItem.EdbCode = edbCode
-			calculateMappingItem.EdbInfoId = edbInfoId
+			calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
 			calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
 			calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
 			calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
@@ -73,85 +74,30 @@ func AddCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbIn
 			}
 		}
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TIME_SHIFT)
 		fmt.Println("dataTableName:" + dataTableName)
 		deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
 		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
 		if err != nil {
-			return 0, err
+			return
 		}
 	}
 
-	var shiftDay int
 	formulaInt, _ := strconv.Atoi(req.Formula)
-	switch req.MoveFrequency {
-	case "天":
-		shiftDay = formulaInt
-	case "周":
-		shiftDay = formulaInt * 7
-	case "月":
-		shiftDay = formulaInt * 30
-	case "季":
-		shiftDay = formulaInt * 90
-	case "年":
-		shiftDay = formulaInt * 365
-	default:
-		shiftDay = formulaInt
-	}
 
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	if req.EdbInfoId <= 0 {
-		pars = append(pars, req.FromEdbInfoId)
-	} else {
-		pars = append(pars, fromEdbInfo.EdbInfoId)
-	}
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-	if err != nil {
-		return edbInfoId, err
-	}
+	err = refreshAllCalculateTimeShift(to, edbInfo.EdbInfoId, edbInfo.Source, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
 
-	addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-	var isAdd bool
-	existMap := make(map[string]string)
-	dataLen := len(dataList)
-	if req.MoveType == 2 {
-		shiftDay = -shiftDay
-	}
-	for i := 0; i < dataLen; i++ {
-		//当期
-		currentItem := dataList[i]
-		currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-
-		existKey := edbCode + currentItem.DataTime
-		if _, ok := existMap[existKey]; !ok {
-			newDate := currentDate.AddDate(0, 0, shiftDay)
-			timestamp := newDate.UnixNano() / 1e6
-			timestampStr := fmt.Sprintf("%d", timestamp)
-			valStr := decimal.NewFromFloat(currentItem.Value).String()
-			addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
-			isAdd = true
-		}
-		existMap[existKey] = currentItem.DataTime
-	}
-	if isAdd {
-		addSql = strings.TrimRight(addSql, ",")
-		_, err = to.Raw(addSql).Exec()
-		if err != nil {
-			return edbInfoId, err
-		}
-	}
 	return
 }
 
 // EditCalculateTimeShift 修改时间移位
-func EditCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode string, oldEdbInfo *EdbInfo) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateTimeShift(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -166,135 +112,80 @@ func EditCalculateTimeShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbI
 			_ = to.Commit()
 		}
 	}()
+	oldEdbInfo := *edbInfo //旧的指标信息
 
 	//修改指标信息
-	sql := ` UPDATE  edb_info
-			SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?,
-			  move_type=?,
-			  move_frequency=?,
-			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.MoveType, req.MoveFrequency, req.Formula, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.MoveType = req.MoveType
+	edbInfo.MoveFrequency = req.MoveFrequency
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "MoveType", "MoveFrequency", "CalculateFormula", "ModifyTime")
 	if err != nil {
 		return
 	}
 
+	//判断计算指标是否被更换
 	var existCondition string
 	var existPars []interface{}
-	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
-
-	existCondition += " AND from_edb_info_id=? "
-	existPars = append(existPars, req.FromEdbInfoId)
+	existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
+	existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
 
-	//判断计算指标是否被更换
 	count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
 	if err != nil {
 		err = errors.New("判断指标是否改变失败,Err:" + err.Error())
 		return
 	}
+
 	if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
+		//如果是依赖指标变更,那么需要删除对应的关联指标,并添加新的关系
 		if count <= 0 {
 			//删除,计算指标关联的,基础指标的关联关系
-			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
-			_, err = o.Raw(sql, edbInfoId).Exec()
+			sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
+			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 			if err != nil {
 				err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
 				return
 			}
 			//关联关系
 			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = edbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
-				calculateMappingItem.FromSource = fromEdbInfo.Source
-				calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
-				calculateMappingItem.FromTag = ""
-				calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_TIME_SHIFT
-				calculateMappingItem.SourceName = "时间移位"
-				_, err = o.Insert(calculateMappingItem)
+				calculateMappingItem := &EdbInfoCalculateMapping{
+					EdbInfoCalculateMappingId: 0,
+					EdbInfoId:                 edbInfo.EdbInfoId,
+					Source:                    utils.DATA_SOURCE_CALCULATE_TIME_SHIFT,
+					SourceName:                "时间移位",
+					EdbCode:                   edbInfo.EdbCode,
+					FromEdbInfoId:             fromEdbInfo.EdbInfoId,
+					FromEdbCode:               fromEdbInfo.EdbCode,
+					FromEdbName:               fromEdbInfo.EdbName,
+					FromSource:                fromEdbInfo.Source,
+					FromSourceName:            fromEdbInfo.SourceName,
+					FromTag:                   "",
+					Sort:                      1,
+					CreateTime:                time.Now(),
+					ModifyTime:                time.Now(),
+				}
+				_, err = to.Insert(calculateMappingItem)
 				if err != nil {
 					return
 				}
 			}
 		}
+
 		//清空原有数据
-		sql = ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
-		_, err = o.Raw(sql, edbInfoId).Exec()
+		sql := ` DELETE FROM edb_data_calculate_time_shift WHERE edb_info_id = ? `
+		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 		if err != nil {
-			return edbInfoId, err
-		}
-
-		edbInfoIdStr := strconv.Itoa(edbInfoId)
-
-		var shiftDay int
-		formulaInt, _ := strconv.Atoi(req.Formula)
-		switch req.MoveFrequency {
-		case "天":
-			shiftDay = formulaInt
-		case "周":
-			shiftDay = formulaInt * 7
-		case "月":
-			shiftDay = formulaInt * 30
-		case "季":
-			shiftDay = formulaInt * 90
-		case "年":
-			shiftDay = formulaInt * 365
-		default:
-			shiftDay = formulaInt
+			return
 		}
 
 		//计算数据
-		var condition string
-		var pars []interface{}
-		condition += " AND edb_info_id=? "
-		pars = append(pars, req.FromEdbInfoId)
-		fmt.Println("EdbInfoId:", req.FromEdbInfoId)
-		dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
-		if err != nil {
-			return edbInfoId, err
-		}
-		addSql := ` INSERT INTO edb_data_calculate_time_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
-		var isAdd bool
-		existMap := make(map[string]string)
-		dataLen := len(dataList)
-		if req.MoveType == 2 {
-			shiftDay = -shiftDay
-		}
-		for i := 0; i < dataLen; i++ {
-			//当期
-			currentItem := dataList[i]
-			currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
-			newDate := currentDate.AddDate(0, 0, shiftDay)
-			existKey := edbCode + newDate.Format(utils.FormatDate)
-			if _, ok := existMap[existKey]; !ok {
-				timestamp := newDate.UnixNano() / 1e6
-				timestampStr := fmt.Sprintf("%d", timestamp)
-				valStr := decimal.NewFromFloat(currentItem.Value).String()
-				addSql += GetAddSql(edbInfoIdStr, edbCode, newDate.Format(utils.FormatDate), timestampStr, valStr)
-				isAdd = true
-			}
-			existMap[existKey] = currentItem.DataTime
-		}
-		if isAdd {
-			addSql = strings.TrimRight(addSql, ",")
-			_, err = o.Raw(addSql).Exec()
-			if err != nil {
-				return edbInfoId, err
-			}
-		}
+		formulaInt, _ := strconv.Atoi(req.Formula)
+		err = refreshAllCalculateTimeShift(to, edbInfo.EdbInfoId, edbInfo.Source, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
 	}
 	return
 }
@@ -306,7 +197,6 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 	if err != nil {
 		return
 	}
-
 	defer func() {
 		if err != nil {
 			fmt.Println("RefreshAllCalculateTimeShift,Err:" + err.Error())
@@ -316,11 +206,15 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 		}
 	}()
 
-	if err != nil {
-		return
-	}
-	edbInfoIdStr := strconv.Itoa(edbInfoId)
 	//计算数据
+	err = refreshAllCalculateTimeShift(to, edbInfoId, source, formulaInt, moveType, fromEdbInfo, edbCode, startDate, endDate, moveFrequency)
+
+	return
+}
+
+// refreshAllCalculateTimeShift 刷新所有时间移位数据
+func refreshAllCalculateTimeShift(to orm.TxOrmer, edbInfoId, source, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
+	edbInfoIdStr := strconv.Itoa(edbInfoId)
 
 	//计算数据
 	var condition string
@@ -357,7 +251,7 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 		shiftDay = -shiftDay
 	}
 
-	dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
+	dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
 	if err != nil {
 		return err
 	}
@@ -374,7 +268,7 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 	fmt.Println("dataTableName:", dataTableName)
 	sql := `SELECT * FROM %s WHERE edb_info_id=? `
 	sql = fmt.Sprintf(sql, dataTableName)
-	_, err = o.Raw(sql, edbInfoId).QueryRows(&existDataList)
+	_, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
 	if err != nil {
 		return err
 	}
@@ -408,7 +302,7 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 				if existStr != valStr {
 					sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
 					sql = fmt.Sprintf(sql, dataTableName)
-					_, err = o.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
+					_, err = to.Raw(sql, valStr, edbInfoId, newDate.Format(utils.FormatDate)).Exec()
 					if err != nil {
 						return err
 					}
@@ -420,7 +314,7 @@ func RefreshAllCalculateTimeShift(edbInfoId, source, formulaInt, moveType int, f
 
 	if isAdd {
 		addSql = strings.TrimRight(addSql, ",")
-		_, err = o.Raw(addSql).Exec()
+		_, err = to.Raw(addSql).Exec()
 		if err != nil {
 			return err
 		}

+ 163 - 373
models/edb_data_calculate_zjpj.go

@@ -22,7 +22,7 @@ type EdbDataCalculateZjpj struct {
 }
 
 // AddCalculateZjpj 新增直接拼接数据
-func AddCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfoId int, err error) {
+func AddCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -36,7 +36,6 @@ func AddCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdb
 			_ = to.Commit()
 		}
 	}()
-	var edbInfo *EdbInfo
 	if req.EdbInfoId <= 0 {
 		edbInfo = &EdbInfo{
 			SourceName:       "直接拼接",
@@ -57,15 +56,19 @@ func AddCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdb
 			CalculateFormula: req.Formula,
 			EdbType:          2,
 		}
-		newEdbInfoId, err := to.Insert(edbInfo)
-		if err != nil {
-			return edbInfoId, err
+		newEdbInfoId, tmpErr := to.Insert(edbInfo)
+		if tmpErr != nil {
+			err = tmpErr
+			return
 		}
-		edbInfoId = int(newEdbInfoId)
+		edbInfo.EdbInfoId = int(newEdbInfoId)
 	} else {
-		edbInfoId = req.EdbInfoId
+		edbInfo, err = GetEdbInfoById(req.EdbInfoId)
+		if err != nil {
+			return
+		}
 		//查询
-		tmpEdbInfo, tmpErr := GetEdbInfoById(edbInfoId)
+		tmpEdbInfo, tmpErr := GetEdbInfoById(edbInfo.EdbInfoId)
 		if tmpErr != nil {
 			err = tmpErr
 			return
@@ -85,162 +88,77 @@ func AddCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdb
 		deleteSql = fmt.Sprintf(deleteSql, dataTableName)
 		_, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
 		if err != nil {
-			return 0, err
+			return
 		}
 
 		//删除指标关系
 		sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=? `
-		_, err = to.Raw(sql, edbInfoId).Exec()
+		_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 	}
 
 	//关联关系
 
+	var existItemA, existItemB *EdbInfoCalculateMapping
 	//第一个指标
 	{
-		calculateMappingItem := new(EdbInfoCalculateMapping)
-		calculateMappingItem.CreateTime = time.Now()
-		calculateMappingItem.ModifyTime = time.Now()
-		calculateMappingItem.Sort = 1
-		calculateMappingItem.EdbCode = edbCode
-		calculateMappingItem.EdbInfoId = edbInfoId
-		calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
-		calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
-		calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
-		calculateMappingItem.FromSource = firstEdbInfo.Source
-		calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
-		calculateMappingItem.FromTag = "A"
-		calculateMappingItem.Source = edbInfo.Source
-		calculateMappingItem.SourceName = edbInfo.SourceName
-		_, err = to.Insert(calculateMappingItem)
-		if err != nil {
+		existItemA = &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    edbInfo.Source,
+			SourceName:                edbInfo.SourceName,
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             firstEdbInfo.EdbInfoId,
+			FromEdbCode:               firstEdbInfo.EdbCode,
+			FromEdbName:               firstEdbInfo.EdbName,
+			FromSource:                firstEdbInfo.Source,
+			FromSourceName:            firstEdbInfo.SourceName,
+			FromTag:                   "A",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
+		}
+		insertId, tmpErr := to.Insert(existItemA)
+		if tmpErr != nil {
+			err = tmpErr
 			return
 		}
+		existItemA.EdbInfoCalculateMappingId = int(insertId)
 	}
 
 	//第二个指标
 	{
-		calculateMappingItem := new(EdbInfoCalculateMapping)
-		calculateMappingItem.CreateTime = time.Now()
-		calculateMappingItem.ModifyTime = time.Now()
-		calculateMappingItem.Sort = 1
-		calculateMappingItem.EdbCode = edbCode
-		calculateMappingItem.EdbInfoId = edbInfoId
-		calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
-		calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
-		calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
-		calculateMappingItem.FromSource = secondEdbInfo.Source
-		calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
-		calculateMappingItem.FromTag = "B"
-		calculateMappingItem.Source = edbInfo.Source
-		calculateMappingItem.SourceName = edbInfo.SourceName
-		_, err = to.Insert(calculateMappingItem)
-		if err != nil {
+		existItemB = &EdbInfoCalculateMapping{
+			EdbInfoCalculateMappingId: 0,
+			EdbInfoId:                 edbInfo.EdbInfoId,
+			Source:                    edbInfo.Source,
+			SourceName:                edbInfo.SourceName,
+			EdbCode:                   edbInfo.EdbCode,
+			FromEdbInfoId:             secondEdbInfo.EdbInfoId,
+			FromEdbCode:               secondEdbInfo.EdbCode,
+			FromEdbName:               secondEdbInfo.EdbName,
+			FromSource:                secondEdbInfo.Source,
+			FromSourceName:            secondEdbInfo.SourceName,
+			FromTag:                   "B",
+			Sort:                      1,
+			CreateTime:                time.Now(),
+			ModifyTime:                time.Now(),
+		}
+		insertId, tmpErr := to.Insert(existItemB)
+		if tmpErr != nil {
+			err = tmpErr
 			return
 		}
+		existItemB.EdbInfoCalculateMappingId = int(insertId)
 	}
 
-	addDataList := make([]*EdbDataCalculateZjpj, 0)
-
 	//拼接数据
+	err = refreshAllCalculateZjpj(to, edbInfo, existItemA, existItemB)
 
-	//第一个指标
-	{
-		var condition string
-		var pars []interface{}
-
-		condition += " AND data_time < ? AND edb_info_id=? "
-		pars = append(pars, req.Formula, firstEdbInfo.EdbInfoId)
-
-		//第一个指标的数据列表
-		firstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
-		if tmpErr != nil {
-			return edbInfoId, tmpErr
-		}
-
-		for _, v := range firstDataList {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataZjpj := &EdbDataCalculateZjpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       edbInfo.EdbCode,
-				DataTime:      v.DataTime,
-				Value:         v.Value,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataZjpj)
-			if len(addDataList) >= 200 {
-				_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
-				if tmpErr != nil {
-					err = tmpErr
-					return
-				}
-				//重新初始化需要加入的数据切片
-				addDataList = make([]*EdbDataCalculateZjpj, 0)
-			}
-		}
-	}
-
-	//第二个指标
-	{
-		var condition string
-		var pars []interface{}
-
-		condition += " AND data_time >= ? AND edb_info_id = ? "
-		pars = append(pars, req.Formula, secondEdbInfo.EdbInfoId)
-
-		//第二个指标的数据列表
-		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
-		if tmpErr != nil {
-			return edbInfoId, tmpErr
-		}
-
-		for _, v := range secondDataList {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataZjpj := &EdbDataCalculateZjpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       edbInfo.EdbCode,
-				DataTime:      v.DataTime,
-				Value:         v.Value,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataZjpj)
-			if len(addDataList) >= 200 {
-				_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
-				if tmpErr != nil {
-					err = tmpErr
-					return
-				}
-				//重新初始化需要加入的数据切片
-				addDataList = make([]*EdbDataCalculateZjpj, 0)
-			}
-		}
-	}
-
-	//将剩余的数据入库
-	if len(addDataList) > 0 {
-		_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
-		if tmpErr != nil {
-			err = tmpErr
-			return
-		}
-	}
 	return
 }
 
 // EditCalculateZjpj 编辑直接拼接数据
-func EditCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (edbInfoId int, err error) {
-	edbInfoId = req.EdbInfoId
+func EditCalculateZjpj(req *EdbInfoCalculateBatchEditReq, edbInfo, firstEdbInfo, secondEdbInfo *EdbInfo) (err error) {
 	o := orm.NewOrm()
 	to, err := o.Begin()
 	if err != nil {
@@ -255,17 +173,17 @@ func EditCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEdbIn
 		}
 	}()
 
+	nowEdbInfo := *edbInfo // 现在的指标信息
+
 	//修改指标信息
-	sql := ` UPDATE  edb_info SET
-			  edb_name =?,
-			  edb_name_source=?,
-			  frequency = ?,
-			  unit = ?,
-			  classify_id = ?, 
-			  calculate_formula=?,
-			  modify_time = NOW()
-			WHERE edb_info_id = ? `
-	_, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
+	edbInfo.EdbName = req.EdbName
+	edbInfo.EdbNameSource = req.EdbName
+	edbInfo.Frequency = req.Frequency
+	edbInfo.Unit = req.Unit
+	edbInfo.ClassifyId = req.ClassifyId
+	edbInfo.CalculateFormula = req.Formula
+	edbInfo.ModifyTime = time.Now()
+	_, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
 	if err != nil {
 		return
 	}
@@ -273,7 +191,7 @@ func EditCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEdbIn
 	var existCondition string
 	var existPars []interface{}
 	existCondition += " AND edb_info_id=? "
-	existPars = append(existPars, edbInfoId)
+	existPars = append(existPars, edbInfo.EdbInfoId)
 
 	//查询出所有的关联指标
 	existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
@@ -291,227 +209,108 @@ func EditCalculateZjpj(req *EdbInfoCalculateBatchSaveReq, nowEdbInfo, firstEdbIn
 		}
 	}
 
-	addDataList := make([]*EdbDataCalculateZjpj, 0)
-	firstDataList := make([]*EdbInfoSearchData, 0)
-	secondDataList := make([]*EdbInfoSearchData, 0)
-
-	//如果 之前的拼接日期 与 现在的拼接日期 不一致的话,需要做以下处理
-	nowFormulaDate, _ := time.ParseInLocation(utils.FormatDate, nowEdbInfo.CalculateFormula, time.Local)
-	reqFormulaDate, _ := time.ParseInLocation(utils.FormatDate, req.Formula, time.Local)
-
-	//如果前后选择的日期不一致,那么需要删除一部分数据
-	if nowEdbInfo.CalculateFormula != req.Formula {
-		var startDate, endDate time.Time
-		//如果当前选择的日期 小于 之前选择的日期
-		if reqFormulaDate.Before(nowFormulaDate) {
-			startDate = reqFormulaDate
-			endDate = nowFormulaDate
-		} else { //如果当前选择的日期 大于 之前选择的日期
-			startDate = nowFormulaDate
-			endDate = reqFormulaDate
-		}
-		//删除 之前日期 与 当前日期 之间的指标数据
-		sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time >= ? and data_time < ?`
-		_, err = o.Raw(sql, edbInfoId, startDate, endDate).Exec()
-		if err != nil {
-			err = fmt.Errorf("删除 之前日期 与 当前日期 之间的指标数据失败,Err:" + err.Error())
-			return
-		}
+	// 是否需要删除数据重新计算
+	isNeedCalculateData := false
+
+	// 如果截止日期变更,那么需要重新计算
+	if req.Formula != nowEdbInfo.CalculateFormula {
+		isNeedCalculateData = true
 	}
 	//第一个指标数据
 	{
-		var condition string
-		var pars []interface{}
+		// 如果指标变了,那么需要删除关系,并重新计算
 		if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
 			//删除之前的A指标关联关系
-			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
-			_, err = o.Raw(sql, edbInfoId, existItemA.FromEdbInfoId).Exec()
+			sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+			_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemA.FromEdbInfoId).Exec()
 			if err != nil {
 				err = fmt.Errorf("删除拼接日期之前的指标关联关系失败,Err:" + err.Error())
 				return
 			}
 
-			//删除之前所有的A指标数据
-			sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time < ?`
-			_, err = o.Raw(sql, edbInfoId, req.Formula).Exec()
-			if err != nil {
-				err = fmt.Errorf("删除拼接日期之前的数据失败,Err:" + err.Error())
-				return
-			}
-
-			//获取第一个指标的数据列表
-			condition += " AND data_time < ? AND edb_info_id=? "
-			pars = append(pars, req.Formula, firstEdbInfo.EdbInfoId)
-
-			tmpFirstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
-			if tmpErr != nil {
-				return edbInfoId, tmpErr
-			}
-			firstDataList = tmpFirstDataList
-
 			//添加新的指标关系
 			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = firstEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = firstEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = firstEdbInfo.EdbName
-				calculateMappingItem.FromSource = firstEdbInfo.Source
-				calculateMappingItem.FromSourceName = firstEdbInfo.SourceName
-				calculateMappingItem.FromTag = "A"
-				calculateMappingItem.Source = nowEdbInfo.Source
-				calculateMappingItem.SourceName = nowEdbInfo.SourceName
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
+				existItemA = &EdbInfoCalculateMapping{
+					EdbInfoCalculateMappingId: 0,
+					EdbInfoId:                 edbInfo.EdbInfoId,
+					Source:                    edbInfo.Source,
+					SourceName:                edbInfo.SourceName,
+					EdbCode:                   edbInfo.EdbCode,
+					FromEdbInfoId:             firstEdbInfo.EdbInfoId,
+					FromEdbCode:               firstEdbInfo.EdbCode,
+					FromEdbName:               firstEdbInfo.EdbName,
+					FromSource:                firstEdbInfo.Source,
+					FromSourceName:            firstEdbInfo.SourceName,
+					FromTag:                   "A",
+					Sort:                      1,
+					CreateTime:                time.Now(),
+					ModifyTime:                time.Now(),
 				}
-			}
-		} else {
-			if req.Formula != nowEdbInfo.CalculateFormula {
-				//获取第一个指标的数据列表
-				condition += " AND data_time >= ?  AND data_time < ? AND edb_info_id=? "
-				pars = append(pars, nowFormulaDate, reqFormulaDate, firstEdbInfo.EdbInfoId)
-
-				tmpFirstDataList, tmpErr := GetEdbDataListAll(condition, pars, firstEdbInfo.Source, 0)
+				insertId, tmpErr := to.Insert(existItemA)
 				if tmpErr != nil {
-					return edbInfoId, tmpErr
+					err = tmpErr
+					return
 				}
-				firstDataList = tmpFirstDataList
-			}
-		}
+				existItemA.EdbInfoCalculateMappingId = int(insertId)
 
-		//待插入数据
-		for _, v := range firstDataList {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataZjpj := &EdbDataCalculateZjpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       nowEdbInfo.EdbCode,
-				DataTime:      v.DataTime,
-				Value:         v.Value,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
+				isNeedCalculateData = true
 			}
-			addDataList = append(addDataList, edbDataZjpj)
 		}
 	}
 
 	//第二个指标数据
 	{
-		var condition string
-		var pars []interface{}
-
+		// 如果指标变了,那么需要删除关系,并重新计算
 		if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
 			//删除之前的B指标关联关系
-			sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
-			_, err = o.Raw(sql, edbInfoId, existItemB.FromEdbInfoId).Exec()
+			sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
+			_, err = to.Raw(sql, edbInfo.EdbInfoId, existItemB.FromEdbInfoId).Exec()
 			if err != nil {
 				err = fmt.Errorf("删除拼接日期之后的指标关联关系失败,Err:" + err.Error())
 				return
 			}
 
-			//删除历史拼接日期之前所有的B指标数据
-			sql = ` DELETE FROM edb_data_calculate_zjpj WHERE edb_info_id = ? and data_time >= ?`
-			_, err = o.Raw(sql, edbInfoId, nowEdbInfo.CalculateFormula).Exec()
-			if err != nil {
-				err = fmt.Errorf("删除历史拼接日期之后的数据失败,Err:" + err.Error())
-				return
+			// 添加新的指标关联关系
+			existItemB = &EdbInfoCalculateMapping{
+				EdbInfoCalculateMappingId: 0,
+				EdbInfoId:                 edbInfo.EdbInfoId,
+				Source:                    edbInfo.Source,
+				SourceName:                edbInfo.SourceName,
+				EdbCode:                   edbInfo.EdbCode,
+				FromEdbInfoId:             secondEdbInfo.EdbInfoId,
+				FromEdbCode:               secondEdbInfo.EdbCode,
+				FromEdbName:               secondEdbInfo.EdbName,
+				FromSource:                secondEdbInfo.Source,
+				FromSourceName:            secondEdbInfo.SourceName,
+				FromTag:                   "B",
+				Sort:                      2,
+				CreateTime:                time.Now(),
+				ModifyTime:                time.Now(),
 			}
-
-			//第二个指标的数据列表
-			condition = " AND data_time >= ?  AND edb_info_id=? "
-			pars = append(pars, reqFormulaDate, secondEdbInfo.EdbInfoId)
-			tmpSecondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
+			insertId, tmpErr := to.Insert(existItemB)
 			if tmpErr != nil {
-				return edbInfoId, tmpErr
-			}
-			secondDataList = tmpSecondDataList
-
-			//添加新的指标关系
-			{
-				calculateMappingItem := new(EdbInfoCalculateMapping)
-				calculateMappingItem.CreateTime = time.Now()
-				calculateMappingItem.ModifyTime = time.Now()
-				calculateMappingItem.Sort = 1
-				calculateMappingItem.EdbCode = nowEdbInfo.EdbCode
-				calculateMappingItem.EdbInfoId = edbInfoId
-				calculateMappingItem.FromEdbInfoId = secondEdbInfo.EdbInfoId
-				calculateMappingItem.FromEdbCode = secondEdbInfo.EdbCode
-				calculateMappingItem.FromEdbName = secondEdbInfo.EdbName
-				calculateMappingItem.FromSource = secondEdbInfo.Source
-				calculateMappingItem.FromSourceName = secondEdbInfo.SourceName
-				calculateMappingItem.FromTag = "B"
-				calculateMappingItem.Source = nowEdbInfo.Source
-				calculateMappingItem.SourceName = nowEdbInfo.SourceName
-				_, err = o.Insert(calculateMappingItem)
-				if err != nil {
-					return
-				}
-			}
-		} else {
-			if req.Formula != nowEdbInfo.CalculateFormula {
-				//获取第二个指标的数据列表
-				condition += " AND data_time >= ?  AND data_time < ? AND edb_info_id=? "
-				pars = append(pars, reqFormulaDate, nowFormulaDate, secondEdbInfo.EdbInfoId)
-
-				tmpSecondDataList, tmpErr := GetEdbDataListAll(condition, pars, secondEdbInfo.Source, 0)
-				if tmpErr != nil {
-					return edbInfoId, tmpErr
-				}
-				secondDataList = tmpSecondDataList
+				err = tmpErr
+				return
 			}
-		}
+			existItemA.EdbInfoCalculateMappingId = int(insertId)
 
-		//待插入数据
-		for _, v := range secondDataList {
-			//时间戳
-			currentDate, _ := time.Parse(utils.FormatDate, v.DataTime)
-			timestamp := currentDate.UnixNano() / 1e6
-
-			edbDataZjpj := &EdbDataCalculateZjpj{
-				EdbInfoId:     edbInfoId,
-				EdbCode:       nowEdbInfo.EdbCode,
-				DataTime:      v.DataTime,
-				Value:         v.Value,
-				Status:        1,
-				CreateTime:    time.Now(),
-				ModifyTime:    time.Now(),
-				DataTimestamp: timestamp,
-			}
-			addDataList = append(addDataList, edbDataZjpj)
+			isNeedCalculateData = true
 		}
 	}
 
-	//数据入库
-	tmpAddDataList := make([]*EdbDataCalculateZjpj, 0)
-	for _, v := range addDataList {
-		tmpAddDataList = append(tmpAddDataList, v)
+	// 如果需要重新计算,那么先删除所有的指标数据,然后再重新计算
+	if isNeedCalculateData {
+		// 删除之前所有的指标数据
 
-		if len(tmpAddDataList) >= 200 {
-			_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-			if tmpErr != nil {
-				err = tmpErr
-				return
-			}
-			//重新初始化需要加入的数据切片
-			tmpAddDataList = make([]*EdbDataCalculateZjpj, 0)
-		}
-	}
-	//最后如果还有需要新增的数据,那么就统一入库
-	if len(tmpAddDataList) > 0 {
-		_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-		if tmpErr != nil {
-			err = tmpErr
+		tableName := GetEdbDataTableName(edbInfo.Source)
+		sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
+		_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+		if err != nil {
+			err = fmt.Errorf("删除历史数据失败,Err:" + err.Error())
 			return
 		}
+
+		err = refreshAllCalculateZjpj(to, edbInfo, existItemA, existItemB)
 	}
 
 	return
@@ -537,26 +336,6 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 			_ = to.Commit()
 		}
 	}()
-
-	//查询当前指标现有的数据
-	var condition string
-	var pars []interface{}
-	condition += " AND edb_info_id=? "
-	pars = append(pars, edbInfo.EdbInfoId)
-
-	dataList, err := GetAllEdbDataCalculateZjpjByEdbInfoId(edbInfo.EdbInfoId)
-	if err != nil {
-		return err
-	}
-	var dateArr []string
-	dataMap := make(map[string]*EdbDataCalculateZjpj)
-	removeDataTimeMap := make(map[string]int) //需要移除的日期数据
-	for _, v := range dataList {
-		dateArr = append(dateArr, v.DataTime)
-		dataMap[v.DataTime] = v
-		removeDataTimeMap[v.DataTime] = 1
-	}
-
 	//查询关联指标信息
 	var existCondition string
 	var existPars []interface{}
@@ -576,6 +355,32 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 			existItemB = existItem
 		}
 	}
+	// 刷新数据
+	err = refreshAllCalculateZjpj(to, edbInfo, existItemA, existItemB)
+
+	return
+}
+
+// refreshAllCalculateZjpj 刷新所有 直接拼接 数据
+func refreshAllCalculateZjpj(to orm.TxOrmer, edbInfo *EdbInfo, existItemA, existItemB *EdbInfoCalculateMapping) (err error) {
+	//查询当前指标现有的数据
+	var condition string
+	var pars []interface{}
+	condition += " AND edb_info_id=? "
+	pars = append(pars, edbInfo.EdbInfoId)
+
+	dataList, err := GetAllEdbDataCalculateZjpjByEdbInfoId(edbInfo.EdbInfoId)
+	if err != nil {
+		return err
+	}
+	var dateArr []string
+	dataMap := make(map[string]*EdbDataCalculateZjpj)
+	removeDataTimeMap := make(map[string]int) //需要移除的日期数据
+	for _, v := range dataList {
+		dateArr = append(dateArr, v.DataTime)
+		dataMap[v.DataTime] = v
+		removeDataTimeMap[v.DataTime] = 1
+	}
 
 	addDataList := make([]*EdbDataCalculateZjpj, 0)
 	//第一个指标
@@ -587,7 +392,7 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 		pars = append(pars, edbInfo.CalculateFormula, existItemA.FromEdbInfoId)
 
 		//第一个指标的数据列表
-		firstDataList, tmpErr := GetEdbDataListAll(condition, pars, existItemA.FromSource, 0)
+		firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemA.FromSource, 0)
 		if tmpErr != nil {
 			return tmpErr
 		}
@@ -602,7 +407,7 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 				if edbData.Value != v.Value {
 					//更新指标数据
 					edbData.Value = v.Value
-					_, _ = o.Update(edbData, "Value")
+					_, _ = to.Update(edbData, "Value")
 				}
 			} else {
 				//时间戳
@@ -633,7 +438,7 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 		pars = append(pars, edbInfo.CalculateFormula, existItemB.FromEdbInfoId)
 
 		//第二个指标的数据列表
-		secondDataList, tmpErr := GetEdbDataListAll(condition, pars, existItemB.FromSource, 0)
+		secondDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemB.FromSource, 0)
 		if tmpErr != nil {
 			return tmpErr
 		}
@@ -649,7 +454,7 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 					//更新指标数据
 					edbData.Value = v.Value
 					edbData.ModifyTime = time.Now()
-					_, tmpErr := o.Update(edbData, "Value", "ModifyTime")
+					_, tmpErr := to.Update(edbData, "Value", "ModifyTime")
 					if tmpErr != nil {
 						fmt.Println("tmpErr:", tmpErr)
 					}
@@ -687,7 +492,7 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 			tableName := GetEdbDataTableName(edbInfo.Source)
 			sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
 
-			_, err = o.Raw(sql, edbInfo.EdbInfoId).Exec()
+			_, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
 			if err != nil {
 				err = fmt.Errorf("删除不存在的直接拼接指标数据失败,Err:" + err.Error())
 				return
@@ -696,23 +501,8 @@ func RefreshAllCalculateZjpj(edbInfo *EdbInfo) (err error) {
 	}
 
 	//数据入库
-	tmpAddDataList := make([]*EdbDataCalculateZjpj, 0)
-	for _, v := range addDataList {
-		tmpAddDataList = append(tmpAddDataList, v)
-
-		if len(tmpAddDataList) >= 200 {
-			_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
-			if tmpErr != nil {
-				err = tmpErr
-				return
-			}
-			//重新初始化需要加入的数据切片
-			tmpAddDataList = make([]*EdbDataCalculateZjpj, 0)
-		}
-	}
-	//最后如果还有需要新增的数据,那么就统一入库
-	if len(tmpAddDataList) > 0 {
-		_, tmpErr := o.InsertMulti(len(tmpAddDataList), tmpAddDataList)
+	if len(addDataList) > 0 {
+		_, tmpErr := to.InsertMulti(len(addDataList), addDataList)
 		if tmpErr != nil {
 			err = tmpErr
 			return

+ 2 - 0
models/edb_data_table.go

@@ -71,6 +71,8 @@ func GetEdbDataTableName(source int) (tableName string) {
 		tableName = "edb_data_predict_calculate_tcz"
 	case utils.DATA_SOURCE_MYSTEEL_CHEMICAL:
 		tableName = "edb_data_mysteel_chemical"
+	case utils.DATA_SOURCE_CALCULATE_CJJX:
+		tableName = "edb_data_calculate_cjjx"
 	default:
 		tableName = ""
 	}

+ 55 - 0
models/edb_info.go

@@ -131,6 +131,25 @@ func GetEdbDataListAll(condition string, pars []interface{}, source, order int)
 	return
 }
 
+// GetEdbDataListAllByTo 根据事务链接获取指标数据列表 order:1升序,其余值为降序
+func GetEdbDataListAllByTo(to orm.TxOrmer, condition string, pars []interface{}, source, order int) (item []*EdbInfoSearchData, err error) {
+	sql := ``
+	tableName := GetEdbDataTableName(source)
+	sql = ` SELECT * FROM %s WHERE 1=1 `
+	sql = fmt.Sprintf(sql, tableName)
+
+	if condition != "" {
+		sql += condition
+	}
+	if order == 1 {
+		sql += ` ORDER BY data_time ASC `
+	} else {
+		sql += ` ORDER BY data_time DESC `
+	}
+	_, err = to.Raw(sql, pars).QueryRows(&item)
+	return
+}
+
 // EdbInfoMaxAndMinInfo 指标最新数据记录结构体
 type EdbInfoMaxAndMinInfo struct {
 	MinDate     string  `description:"最小日期"`
@@ -264,6 +283,25 @@ func GetEdbDataListAllV1(condition string, pars []interface{}, source, order int
 	return
 }
 
+// GetEdbDataListAllV1ByTo 通过事务链接获取数据列表
+func GetEdbDataListAllV1ByTo(to orm.TxOrmer, condition string, pars []interface{}, source, order int) (item []*EdbInfoSearchDataV1, err error) {
+	sql := ``
+	tableName := GetEdbDataTableName(source)
+	sql = ` SELECT * FROM %s WHERE 1=1 `
+	sql = fmt.Sprintf(sql, tableName)
+
+	if condition != "" {
+		sql += condition
+	}
+	if order == 1 {
+		sql += ` ORDER BY data_time ASC `
+	} else {
+		sql += ` ORDER BY data_time DESC `
+	}
+	_, err = to.Raw(sql, pars).QueryRows(&item)
+	return
+}
+
 // GetEdbInfoByCondition 获取指标列表
 func GetEdbInfoByCondition(condition string, pars []interface{}, order int) (item []*EdbInfo, err error) {
 	o := orm.NewOrm()
@@ -670,3 +708,20 @@ func ModifyPredictEdbInfoMaxAndMinInfo(edbInfoId int, item *EdbInfoMaxAndMinInfo
 	_, err = o.Raw(sql, item.MinDate, item.MaxDate, item.MinValue, item.MaxValue, item.LatestDate, item.LatestValue, edbInfoId).Exec()
 	return
 }
+
+// ModifyCalculateEdbInfo 修改计算指标信息
+func ModifyCalculateEdbInfo(edbName, frequency, unit, calculateFormula string, classifyId, edbInfoId int) (err error) {
+	o := orm.NewOrmUsingDB("data")
+	sql := ` UPDATE  edb_info
+			SET
+			  edb_name =?,
+			  edb_name_source =?,
+			  frequency = ?,
+			  unit = ?,
+			  classify_id = ?,
+			  calculate_formula=?,
+			  modify_time = NOW()
+			WHERE edb_info_id = ?`
+	_, err = o.Raw(sql, edbName, edbName, frequency, unit, classifyId, calculateFormula, edbInfoId).Exec()
+	return
+}

+ 19 - 1
routers/commentsRouter.go

@@ -18,13 +18,31 @@ func init() {
 
     beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
         beego.ControllerComments{
-            Method: "CalculateBatchSave",
+            Method: "BatchEdit",
+            Router: `/batch/edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
+        beego.ControllerComments{
+            Method: "BatchSave",
             Router: `/batch/save`,
             AllowHTTPMethods: []string{"post"},
             MethodParams: param.Make(),
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
+        beego.ControllerComments{
+            Method: "Edit",
+            Router: `/edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
         beego.ControllerComments{
             Method: "Refresh",

+ 0 - 352
routers/commentsRouter_controllers.go

@@ -1,352 +0,0 @@
-package routers
-
-import (
-	beego "github.com/beego/beego/v2/server/web"
-	"github.com/beego/beego/v2/server/web/context/param"
-)
-
-func init() {
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
-        beego.ControllerComments{
-            Method: "CalculateBatchSave",
-            Router: "/batch/save",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CalculateController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CffexController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CffexController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CffexController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CffexController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CoalController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CoalController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CoalController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:CoalController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:DlController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:DlController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:DlController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:DlController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:GieController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:GieController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:GieController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:GieController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LtController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LtController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LtController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LtController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LzController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LzController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LzController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:LzController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ManualController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ManualController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ManualController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ManualController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:MySteelController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:MySteelController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:MySteelController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:MySteelController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbFinanceController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbFinanceController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbFinanceController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PbFinanceController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"],
-        beego.ControllerComments{
-            Method: "Edit",
-            Router: "/edit",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:PythonController"],
-        beego.ControllerComments{
-            Method: "ExcePython",
-            Router: "/exec",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShfeController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShfeController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShfeController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ShfeController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:SmmController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:SmmController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:SmmController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:SmmController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ThsController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ThsController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ThsController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ThsController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:WindController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:WindController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:WindController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:WindController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ZzController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ZzController"],
-        beego.ControllerComments{
-            Method: "Add",
-            Router: "/add",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ZzController"] = append(beego.GlobalControllerRouter["hongze/hongze_edb_lib/controllers:ZzController"],
-        beego.ControllerComments{
-            Method: "Refresh",
-            Router: "/refresh",
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-}

+ 1 - 0
utils/constants.go

@@ -62,6 +62,7 @@ const (
 	DATA_SOURCE_PREDICT_CALCULATE_TBZ            //同比值->32
 	DATA_SOURCE_PREDICT_CALCULATE_TCZ            //同差值->33
 	DATA_SOURCE_MYSTEEL_CHEMICAL                 //钢联化工->34
+	DATA_SOURCE_CALCULATE_CJJX                   //超季节性->35
 )
 
 //基础数据初始化日期

部分文件因文件數量過多而無法顯示