mixed_table.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. package excel
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models/data_manage"
  6. "eta/eta_api/models/data_manage/excel/request"
  7. "eta/eta_api/services/data"
  8. "eta/eta_api/utils"
  9. "fmt"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/dengsgo/math-engine/engine"
  15. "github.com/shopspring/decimal"
  16. )
  17. // BaseCalculate
  18. // @Description: 指标数据计算请求
  19. type BaseCalculate struct {
  20. DataList []*data_manage.EdbDataList
  21. Frequency string `description:"需要转换的频度"`
  22. Formula interface{}
  23. Calendar string `description:"公历/农历"`
  24. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  25. MoveFrequency string `description:"移动频度"`
  26. FromFrequency string `description:"来源的频度"`
  27. Source int `description:"1:累计值转月;2:累计值转季;3:同比值;4:同差值;5:N数值移动平均数计算;6:环比值;7:环差值;8:升频;9:降频;10:时间移位;11:超季节性;12:年化;13:累计值;14:累计值年初至今;15:指数修匀;16:日均值"`
  28. }
  29. // Cell
  30. // @Description: 单元格位置
  31. type Cell struct {
  32. Column int `description:"行"`
  33. Row int `description:"列"`
  34. CellInfo request.MixedTableCellDataReq `description:"对应的单元格信息"`
  35. }
  36. // GetMixedTableCellData 获取混合表格数据
  37. func GetMixedTableCellData(mixedTableReq request.MixedTableReq, lang string) (newMixedTableCellDataList [][]request.MixedTableCellDataReq, err error, errMsg string) {
  38. cellRelationConf := mixedTableReq.CellRelation
  39. config := mixedTableReq.Data
  40. // 单元格关系配置x信息
  41. cellRelationConfMap := make(map[string]request.CellRelationConf)
  42. cellRelationConfList := make([]request.CellRelationConf, 0)
  43. if cellRelationConf != `` {
  44. err = json.Unmarshal([]byte(cellRelationConf), &cellRelationConfList)
  45. if err != nil {
  46. return
  47. }
  48. for _, v := range cellRelationConfList {
  49. cellRelationConfMap[v.Key] = v
  50. }
  51. }
  52. // 找出所有的关联指标id
  53. config, edbInfoIdList, _, err, errMsg := handleConfig(config)
  54. if err != nil {
  55. return
  56. }
  57. // 查询所有关联的指标信息
  58. edbInfoList, err := data_manage.GetEdbInfoByIdList(edbInfoIdList)
  59. if err != nil {
  60. return
  61. }
  62. // 指标信息map
  63. edbInfoMap := make(map[int]*data_manage.EdbInfo)
  64. // 日度指标数据map
  65. edbDayDataListMap := make(map[int]map[string]float64)
  66. // 月度指标数据map
  67. edbMonthDataListMap := make(map[int]map[string]string)
  68. // 日度指标数据map
  69. edbDataListMap := make(map[int][]*data_manage.EdbDataList)
  70. for _, edbInfo := range edbInfoList {
  71. edbInfoMap[edbInfo.EdbInfoId] = edbInfo
  72. dataList := make([]*data_manage.EdbDataList, 0)
  73. switch edbInfo.EdbInfoType {
  74. case 0:
  75. dataList, _ = data_manage.GetEdbDataList(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbInfoId, ``, ``)
  76. case 1:
  77. _, dataList, _, _, _, _ = data.GetPredictDataListByPredictEdbInfoId(edbInfo.EdbInfoId, ``, ``, false)
  78. default:
  79. err = errors.New(fmt.Sprint("获取失败,指标类型异常", edbInfo.EdbInfoType))
  80. }
  81. dateValMap := make(map[string]float64)
  82. monthDateMap := make(map[string]string)
  83. for _, tmpData := range dataList {
  84. // 日度数据
  85. dateValMap[tmpData.DataTime] = tmpData.Value
  86. // 月度数据(取该月份的第一个数据)
  87. yearMonth := strings.Join(strings.Split(tmpData.DataTime, "-")[0:2], "-")
  88. if _, ok := monthDateMap[yearMonth]; !ok {
  89. // 存最早的时间
  90. monthDateMap[yearMonth] = tmpData.DataTime
  91. }
  92. }
  93. edbDayDataListMap[edbInfo.EdbInfoId] = dateValMap
  94. edbMonthDataListMap[edbInfo.EdbInfoId] = monthDateMap
  95. edbDataListMap[edbInfo.EdbInfoId] = dataList
  96. }
  97. // 单元格实际绑定的信息map
  98. cellDataRelationMap := make(map[string]request.MixedTableCellDataReq, 0)
  99. // 处理指定指标的日期
  100. for k, row := range config {
  101. for i, cell := range row {
  102. // 单元格是日期类型,且是日导入指标日期(指标库的最新日期)
  103. if cell.DataType == request.DateDT && cell.DataTimeType == request.EdbDateDT {
  104. // 指标id是在配置里面
  105. var edbDateConfig request.EdbDateConf
  106. err = json.Unmarshal([]byte(cell.Value), &edbDateConfig)
  107. if err != nil {
  108. return
  109. }
  110. if dataList, ok := edbDataListMap[edbDateConfig.EdbInfoId]; ok {
  111. // todo 获取配置信息,根据配置信息进行日期变换, 是否需要更新当前记录,将历史记录逐渐转换成新的记录
  112. var newDate string
  113. newDate, err = GetEdbDateByMoveForward(config[k][i].Value, dataList)
  114. if err != nil {
  115. return
  116. }
  117. newDate, err = HandleMixTableDateChange(newDate, config[k][i].Value)
  118. if err != nil {
  119. return
  120. }
  121. cell.ShowValue = newDate
  122. cell.DataTime = newDate
  123. config[k][i] = cell
  124. }
  125. }
  126. row[i] = cell
  127. cellDataRelationMap[cell.Uid] = cell
  128. }
  129. config[k] = row
  130. }
  131. // 指标计算的结果map
  132. edbSourceDataMap := make(map[string]data.BaseCalculateDataResp)
  133. // 单元格对应的key与他的值(只处理数据类型)
  134. cellKeyVal := make(map[string]float64)
  135. // 基础计算单元格的位置信息
  136. calculateCellMap := make(map[string]Cell)
  137. calculateChainList := make([]string, 0)
  138. dateCalculateList := make([]string, 0)
  139. showStyleList := make([]string, 0)
  140. // 处理单元格中的数据类型(除去基础计算,因为这个是依赖于其他)
  141. for k, row := range config {
  142. for i, cell := range row {
  143. switch cell.DataType {
  144. case request.EdbDT: // 指标类型
  145. if cell.Value == `` {
  146. if edbInfo, ok := edbInfoMap[cell.EdbInfoId]; ok {
  147. cell.ShowValue = edbInfo.EdbName
  148. }
  149. } else {
  150. cell.ShowValue = cell.Value
  151. }
  152. case request.InsertDataDT, request.PopInsertDataDT: // 数据类型
  153. // 数值先清空
  154. cell.ShowValue = ``
  155. //cell.Value = ``
  156. // 日期关系配置不存在,则默认最新数据
  157. if relationConf, ok := cellRelationConfMap[cell.Uid]; ok { //表示表格日期
  158. if relationConf.RelationDate.Key == `` {
  159. // 日期关系配置未绑定
  160. continue
  161. }
  162. // 配置
  163. relationCell, ok := cellDataRelationMap[relationConf.RelationDate.Key]
  164. if !ok {
  165. // 找不到对应日期的单元格
  166. continue
  167. }
  168. // 确实是找到了这个关联日期的单元格,那么通过日期重新获取数据值
  169. tmpDateValMap := make(map[string]float64)
  170. // 日度数据
  171. if dateValMap, ok := edbDayDataListMap[cell.EdbInfoId]; ok {
  172. tmpDateValMap = dateValMap
  173. }
  174. // todo 根据配置进行日期变换
  175. relationDate := relationCell.DataTime
  176. if strings.Contains(cell.Value, "{") {
  177. relationDate, err = HandleMixTableDateChange(relationDate, cell.Value)
  178. if err != nil {
  179. return
  180. }
  181. } else {
  182. cell.Value = ""
  183. }
  184. if val, ok2 := tmpDateValMap[relationDate]; ok2 {
  185. //cell.ShowValue = fmt.Sprint(val)
  186. cellKeyVal[cell.Uid] = val
  187. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  188. }
  189. } else {
  190. // 如果不是取得一个关联的日期,那么就是指定日期
  191. // 如果没有指定日期,则默认最新数据
  192. if cell.DataTime == `` {
  193. // 指标的最新日期
  194. if dateValList, ok := edbDataListMap[cell.EdbInfoId]; ok {
  195. tmpLenData := len(dateValList)
  196. if tmpLenData > 0 {
  197. //做期数前移动和日期变换
  198. if !strings.Contains(cell.Value, "{") {
  199. cell.Value = ""
  200. }
  201. var newDate string
  202. newDate, err = GetEdbDateByMoveForward(cell.Value, dateValList)
  203. if err != nil {
  204. return
  205. }
  206. newDate, err = HandleMixTableDateChange(newDate, cell.Value)
  207. if err != nil {
  208. return
  209. }
  210. var finalVal string
  211. for _, v := range dateValList {
  212. if v.DataTime == newDate {
  213. finalVal = utils.FormatMixTableDataShowValue(v.Value)
  214. cellKeyVal[cell.Uid] = v.Value
  215. break
  216. }
  217. }
  218. cell.ShowValue = finalVal
  219. }
  220. }
  221. } else {
  222. tmpDateList := strings.Split(cell.DataTime, "-")
  223. tmpDateValMap := make(map[string]float64)
  224. var newDate string
  225. if len(tmpDateList) == 2 {
  226. //月度数据
  227. if dateMap, ok1 := edbMonthDataListMap[cell.EdbInfoId]; ok1 {
  228. if d, ok2 := dateMap[cell.DataTime]; ok2 {
  229. newDate = d
  230. }
  231. }
  232. } else {
  233. // 日度数据
  234. newDate = cell.DataTime
  235. }
  236. // 日期变换后才能确定最后的时间
  237. //做期数前移动和日期变换
  238. if !strings.Contains(cell.Value, "{") {
  239. cell.Value = ""
  240. }
  241. newDate, err = HandleMixTableDateChange(newDate, cell.Value)
  242. if err != nil {
  243. return
  244. }
  245. if dateValMap, ok3 := edbDayDataListMap[cell.EdbInfoId]; ok3 {
  246. tmpDateValMap = dateValMap
  247. if val, ok2 := tmpDateValMap[cell.DataTime]; ok2 {
  248. //cell.ShowValue = fmt.Sprint(val)
  249. cellKeyVal[cell.Uid] = val
  250. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  251. }
  252. }
  253. }
  254. }
  255. case request.CustomTextDT: //自定义文本
  256. if cell.Value == `` {
  257. continue
  258. }
  259. // 处理看下能否转成float,如果可以的话,说明这个也是可以参与计算的
  260. tmpDeci, tmpErr := decimal.NewFromString(cell.Value)
  261. if tmpErr == nil {
  262. tmpVal, _ := tmpDeci.Float64()
  263. cellKeyVal[cell.Uid] = tmpVal
  264. }
  265. case request.FormulateCalculateDataDT: // 公式计算(A+B这种)
  266. calculateChainList = append(calculateChainList, cell.Uid)
  267. case request.InsertEdbCalculateDataDT: // 插入指标系统计算公式生成的值
  268. // 处理value的值
  269. if !strings.Contains(cell.Value, "EdbInfoId") && cell.EdbInfoId > 0 {
  270. cell.Value, _ = fixCalculateValueConfig(cell.Value, cell.EdbInfoId)
  271. row[i] = cell
  272. }
  273. // 日期
  274. var cellDateTime string
  275. // 日期关系配置不存在,则默认最新数据
  276. // 从绑定的单元格中获取数据的日期
  277. if relationConf, ok := cellRelationConfMap[cell.Uid]; ok {
  278. if relationConf.RelationDate.Key == `` {
  279. // 日期关系配置未绑定
  280. continue
  281. }
  282. // 配置
  283. relationCell, ok := cellDataRelationMap[relationConf.RelationDate.Key]
  284. if !ok {
  285. // 找不到对应日期的单元格
  286. continue
  287. }
  288. cellDateTime = relationCell.DataTime
  289. }
  290. var tmpDataMap map[string]float64
  291. key := utils.MD5(cell.Value)
  292. respItemData, ok := edbSourceDataMap[key]
  293. if !ok {
  294. // 对应的配置值
  295. var tmpConfig request.CalculateConf
  296. err = json.Unmarshal([]byte(cell.Value), &tmpConfig)
  297. if err != nil {
  298. return
  299. }
  300. tmpDataList, ok := edbDataListMap[tmpConfig.EdbInfoId]
  301. if !ok {
  302. continue
  303. }
  304. edbInfo, ok := edbInfoMap[tmpConfig.EdbInfoId]
  305. if !ok {
  306. continue
  307. }
  308. req2 := &BaseCalculate{
  309. DataList: tmpDataList,
  310. Frequency: tmpConfig.Frequency,
  311. Formula: tmpConfig.Formula,
  312. Calendar: tmpConfig.Calendar,
  313. MoveType: tmpConfig.MoveType,
  314. MoveFrequency: tmpConfig.MoveFrequency,
  315. FromFrequency: edbInfo.Frequency,
  316. Source: tmpConfig.Source,
  317. }
  318. // 调用指标库去更新
  319. reqJson, tmpErr := json.Marshal(req2)
  320. if tmpErr != nil {
  321. utils.FileLog.Error(fmt.Sprintf("计算失败1,配置信息;%s;错误原因:%s", cell.Value, tmpErr.Error()))
  322. err = tmpErr
  323. return
  324. }
  325. respItem, tmpErr := data.BaseCalculate(string(reqJson), lang)
  326. if tmpErr != nil {
  327. utils.FileLog.Error(fmt.Sprintf("计算失败2,配置信息;%s;错误原因:%s", cell.Value, tmpErr.Error()))
  328. err = tmpErr
  329. return
  330. }
  331. if respItem.Ret != 200 {
  332. utils.FileLog.Error(fmt.Sprintf("计算失败3,配置信息;%s;原因:%s;错误原因:%s", cell.Value, respItem.Msg, respItem.ErrMsg))
  333. continue
  334. }
  335. //tmpDataMap = respItem.Data.DataMap
  336. // 计算结果存一份,万一存在重复的计算方式,那么省的重新计算一下
  337. edbSourceDataMap[key] = respItem.Data
  338. respItemData = respItem.Data
  339. }
  340. lenDataList := len(respItemData.DateList)
  341. tmpDataMap = respItemData.DataMap
  342. if cellDateTime == `` && lenDataList > 0 {
  343. //判断是否需要做期数前移动
  344. cellDateTime = respItemData.DateList[lenDataList-1]
  345. cellDateTime, err = GetEdbDateByMoveForwardByDateList(cell.Value, respItemData.DateList)
  346. if err != nil {
  347. utils.FileLog.Error(fmt.Sprintf("日期前移失败,配置信息;%s", cell.Value))
  348. continue
  349. }
  350. }
  351. // 进行日期变换
  352. cellDateTime, err = HandleMixTableDateChange(cellDateTime, cell.Value)
  353. if err != nil {
  354. utils.FileLog.Error(fmt.Sprintf("日期变换失败,配置信息;%s, 日期:%s", cell.Value, cellDateTime))
  355. continue
  356. }
  357. val, ok := tmpDataMap[cellDateTime]
  358. if ok {
  359. cellKeyVal[cell.Uid] = val
  360. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  361. } else {
  362. cell.ShowValue = ""
  363. }
  364. case request.DateCalculateDataDT: //日期计算
  365. dateCalculateList = append(dateCalculateList, cell.Uid)
  366. // 遍历数组,根据公式进行计算,并将得到的结果放到对应的单元格中
  367. }
  368. row[i] = cell
  369. }
  370. config[k] = row
  371. }
  372. // 处理指定指标的日期
  373. for k, row := range config {
  374. for i, cell := range row {
  375. calculateCellMap[cell.Uid] = Cell{
  376. Column: k,
  377. Row: i,
  378. CellInfo: cell,
  379. }
  380. cell.ShowFormatValue = cell.ShowValue
  381. if cell.ShowStyle != `` {
  382. showStyleList = append(showStyleList, cell.Uid)
  383. }
  384. row[i] = cell
  385. cellDataRelationMap[cell.Uid] = cell
  386. }
  387. config[k] = row
  388. }
  389. // 公式链计算
  390. if len(calculateChainList) > 0 {
  391. for _, cellKey := range calculateChainList {
  392. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  393. cellPosition, ok := calculateCellMap[cellKey]
  394. if !ok {
  395. utils.FileLog.Error("找不到单元格位置:", cellKey)
  396. continue
  397. }
  398. cell := config[cellPosition.Column][cellPosition.Row]
  399. if cell.DataType != request.FormulateCalculateDataDT { // 判断公式计算(A+B这种)类型,不是的话也过滤了
  400. continue
  401. }
  402. val, has, tmpErr, tmpErrMsg := getCalculateValueByCell(calculateCellMap, cellKey, cellKeyVal)
  403. if tmpErr != nil {
  404. errMsg = tmpErrMsg
  405. err = tmpErr
  406. return
  407. }
  408. if !has {
  409. continue
  410. }
  411. cellKeyVal[cell.Uid] = val
  412. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  413. config[cellPosition.Column][cellPosition.Row] = cell
  414. }
  415. }
  416. // 日期计算
  417. config, err, errMsg = handlerDateCalculate(dateCalculateList, calculateCellMap, config)
  418. if err != nil {
  419. return
  420. }
  421. // 格式化展示
  422. config, err, errMsg = handleMixCellShowStyle(showStyleList, calculateCellMap, config)
  423. if err != nil {
  424. return
  425. }
  426. config = setDefaultCellSize(config)
  427. newMixedTableCellDataList = config
  428. return
  429. }
  430. func setDefaultCellSize(config [][]request.MixedTableCellDataReq) (newConfig [][]request.MixedTableCellDataReq) {
  431. newConfig = config
  432. for i, row := range config {
  433. for j, cell := range row {
  434. var styleConf request.MixCellShowStyle
  435. if cell.ShowStyle == `` {
  436. styleConf = request.MixCellShowStyle{
  437. Width: 140,
  438. Height: 35,
  439. }
  440. } else {
  441. err := json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  442. if err != nil {
  443. continue
  444. }
  445. if styleConf.Width == 0 {
  446. styleConf.Width = 140
  447. }
  448. if styleConf.Height == 0 {
  449. styleConf.Height = 35
  450. }
  451. }
  452. tmpStyleConf, err := json.Marshal(styleConf)
  453. if err == nil {
  454. cell.ShowStyle = string(tmpStyleConf)
  455. }
  456. newConfig[i][j] = cell
  457. }
  458. }
  459. return
  460. }
  461. // getCalculateValue 获取公式计算的结果
  462. func getCalculateValueByCell(calculateCellMap map[string]Cell, key string, cellKeyValMap map[string]float64) (val float64, has bool, err error, errMsg string) {
  463. // 单元格的标签名
  464. val, ok := cellKeyValMap[key]
  465. if ok {
  466. has = true
  467. return
  468. }
  469. // 查找单元格数据
  470. cell, ok := calculateCellMap[key]
  471. if !ok {
  472. err = errors.New("查找单元格" + key + "的数据失败")
  473. return
  474. }
  475. colData := cell.CellInfo
  476. // 如果不是基础计算单元格,直接返回
  477. if colData.DataType != request.FormulateCalculateDataDT {
  478. return
  479. }
  480. // 如果是计算单元格
  481. tagList := make([]utils.CellPosition, 0)
  482. // 计算单元格relationCellList
  483. var relationCellList []request.RelationCell
  484. if colData.Extra == `` {
  485. err = errors.New(colData.Uid + "没有绑定关系")
  486. return
  487. }
  488. err = json.Unmarshal([]byte(colData.Extra), &relationCellList)
  489. if err != nil {
  490. return
  491. }
  492. for _, relation := range relationCellList {
  493. //relationCellTagName := strings.ToUpper(relation.Tag) + relation.Row
  494. tmpVal, _, tmpErr, tmpErrMsg := getCalculateValueByCell(calculateCellMap, relation.Key, cellKeyValMap)
  495. if tmpErr != nil {
  496. errMsg = tmpErrMsg
  497. err = tmpErr
  498. return
  499. }
  500. cellKeyValMap[relation.Key] = tmpVal
  501. rowInt, tmpErr := strconv.Atoi(relation.Row)
  502. if tmpErr != nil {
  503. err = tmpErr
  504. return
  505. }
  506. tagList = append(tagList, utils.CellPosition{
  507. Tag: relation.Tag,
  508. Row: rowInt,
  509. Value: tmpVal,
  510. })
  511. }
  512. // 计算
  513. val, errMsg, err = calculateByCellList(strings.ToUpper(colData.Value), tagList)
  514. if err != nil {
  515. return
  516. }
  517. // 重新赋值
  518. has = true
  519. cellKeyValMap[key] = val
  520. return
  521. }
  522. // handleConfig
  523. // @Description: 处理混合表格配置
  524. // @author: Roc
  525. // @datetime2023-10-27 13:24:53
  526. // @param configList [][]request.MixedTableCellDataReq
  527. // @return newConfig [][]request.MixedTableCellDataReq
  528. // @return edbInfoIdList []int
  529. // @return dataEdbInfoIdList []int
  530. // @return err error
  531. // @return errMsg string
  532. func handleConfig(configList [][]request.MixedTableCellDataReq) (newConfig [][]request.MixedTableCellDataReq, edbInfoIdList []int, dataEdbInfoIdList []int, err error, errMsg string) {
  533. edbInfoIdList = make([]int, 0)
  534. dataEdbInfoIdList = make([]int, 0)
  535. for ck, rowList := range configList {
  536. for rk, cell := range rowList {
  537. switch cell.DataType {
  538. case request.EdbDT: // 指标信息
  539. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  540. case request.InsertDataDT, request.PopInsertDataDT: // 插值、弹框插值
  541. dataEdbInfoIdList = append(dataEdbInfoIdList, cell.EdbInfoId)
  542. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  543. case request.InsertEdbCalculateDataDT: // 插入指标计算公式生成的值
  544. var config request.CalculateConf
  545. err = json.Unmarshal([]byte(cell.Value), &config)
  546. if err != nil {
  547. return
  548. }
  549. if config.EdbInfoId == 0 && cell.EdbInfoId > 0 {
  550. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  551. } else {
  552. edbInfoIdList = append(edbInfoIdList, config.EdbInfoId)
  553. }
  554. dataEdbInfoIdList = append(dataEdbInfoIdList, cell.EdbInfoId)
  555. case request.DateDT: // 日期类型
  556. date, newVal, tmpErr, tmpErrMsg := handleDate(cell.DataTimeType, cell.Value)
  557. if tmpErr != nil {
  558. err = tmpErr
  559. errMsg = tmpErrMsg
  560. return
  561. }
  562. rowList[rk].DataTime = date
  563. rowList[rk].ShowValue = date
  564. rowList[rk].Value = newVal //兼容原有的历史数据中系统导入日期
  565. // 指标日期类型的单元格需要额外将指标id取出来
  566. if cell.DataTimeType == request.EdbDateDT {
  567. var config request.EdbDateConf
  568. err = json.Unmarshal([]byte(cell.Value), &config)
  569. if err != nil {
  570. return
  571. }
  572. edbInfoIdList = append(edbInfoIdList, config.EdbInfoId)
  573. }
  574. }
  575. }
  576. configList[ck] = rowList
  577. }
  578. newConfig = configList
  579. return
  580. }
  581. // HandleDate
  582. // @Description: 日期处理
  583. // @author: Roc
  584. // @datetime2023-10-27 09:37:02
  585. // @param dataTimeType int
  586. // @param val string
  587. // @return date string
  588. // @return err error
  589. // @return errMsg string
  590. func HandleDate(dataTimeType int, val string) (date string, newVal string, err error, errMsg string) {
  591. return handleDate(dataTimeType, val)
  592. }
  593. // handleDate
  594. // @Description: 日期处理
  595. // @author: Roc
  596. // @datetime2023-10-27 09:36:49
  597. // @param dataTimeType int
  598. // @param val string
  599. // @return date string
  600. // @return err error
  601. // @return errMsg string
  602. func handleDate(dataTimeType int, val string) (date string, newVal string, err error, errMsg string) {
  603. newVal = val
  604. if val == `` {
  605. errMsg = "错误的日期数据"
  606. err = errors.New(errMsg)
  607. return
  608. }
  609. switch dataTimeType {
  610. case request.CustomDateT: //手动输入日期
  611. /*if !strings.Contains(val, "{") {
  612. newVal, err, errMsg = handleOldCustomerDateT(val)
  613. if err != nil {
  614. return
  615. }
  616. }
  617. date, err = HandleMixTableDateChange("", newVal)
  618. if err != nil {
  619. return
  620. }*/
  621. date = val
  622. return
  623. case request.SystemDateT: // 系统日期
  624. date = time.Now().Format(utils.FormatDate)
  625. newVal, err, errMsg = handleOldSystemDateT(val)
  626. if err != nil {
  627. return
  628. }
  629. date, err = HandleMixTableDateChange(date, newVal)
  630. if err != nil {
  631. return
  632. }
  633. case request.EdbDateDT: // 导入指标日期(指标库的最新日期)
  634. default:
  635. errMsg = "错误的日期类型"
  636. err = errors.New(errMsg)
  637. return
  638. }
  639. return
  640. }
  641. func GetEdbDateByMoveForward(conf string, edbDataList []*data_manage.EdbDataList) (date string, err error) {
  642. dateList := make([]string, 0)
  643. for _, v := range edbDataList {
  644. dateList = append(dateList, v.DataTime)
  645. }
  646. date, err = GetEdbDateByMoveForwardByDateList(conf, dateList)
  647. return
  648. }
  649. func GetEdbDateByMoveForwardByDateList(conf string, dateList []string) (date string, err error) {
  650. moveForward := 0
  651. if conf != "" {
  652. var edbDateConf request.EdbDateChangeConf
  653. err = json.Unmarshal([]byte(conf), &edbDateConf)
  654. if err != nil {
  655. err = fmt.Errorf("日期变换配置json解析失败失败: %s", err.Error())
  656. return
  657. }
  658. moveForward = edbDateConf.MoveForward
  659. }
  660. // 根据日期进行排序
  661. index := len(dateList) - 1 - moveForward
  662. for k, v := range dateList {
  663. if k == index {
  664. date = v
  665. return
  666. }
  667. }
  668. return
  669. }
  670. // HandleMixTableDateChange 处理表格中的日期变换
  671. func HandleMixTableDateChange(date, conf string) (newDate string, err error) {
  672. newDate = date
  673. if conf == "" {
  674. return
  675. }
  676. var edbDateConf request.EdbDateConf
  677. err = json.Unmarshal([]byte(conf), &edbDateConf)
  678. if err != nil {
  679. err = fmt.Errorf("日期变换配置json解析失败失败: %s, Err:%s", conf, err.Error())
  680. return
  681. }
  682. if newDate != "" {
  683. if len(edbDateConf.DateChange) > 0 {
  684. var dateTime time.Time
  685. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  686. if err != nil {
  687. err = fmt.Errorf("日期解析失败: %s", err.Error())
  688. return
  689. }
  690. for _, v := range edbDateConf.DateChange {
  691. if v.ChangeType == 1 {
  692. dateTime = dateTime.AddDate(v.Year, v.Month, v.Day)
  693. newDate = dateTime.Format(utils.FormatDate)
  694. } else if v.ChangeType == 2 {
  695. newDate, err, _ = HandleSystemAppointDateT(dateTime, v.FrequencyDay, v.Frequency)
  696. if err != nil {
  697. return
  698. }
  699. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  700. if err != nil {
  701. err = fmt.Errorf("日期解析失败: %s", err.Error())
  702. return
  703. }
  704. }
  705. }
  706. }
  707. }
  708. return
  709. }
  710. // handleOldSystemDateT
  711. // @Description: 历史数据中的导入系统日期
  712. // @author: Roc
  713. // @datetime2023-10-27 09:36:21
  714. // @param confStr string
  715. // @return date string
  716. // @return err error
  717. // @return errMsg string
  718. func handleOldSystemDateT(confStr string) (newConf string, err error, errMsg string) {
  719. newConf = confStr
  720. var config request.SystemDateConf
  721. err = json.Unmarshal([]byte(confStr), &config)
  722. if err != nil {
  723. return
  724. }
  725. newConfig := new(request.EdbDateConf)
  726. dateChange := new(request.EdbDateConfDateChange)
  727. dateChangeList := make([]*request.EdbDateConfDateChange, 0)
  728. switch config.Source {
  729. case request.SystemCurrDateT:
  730. return
  731. case request.SystemCalculateDateT:
  732. // todo 是否直接更新该excel记录,
  733. dateChange.Day = config.CalculateNum
  734. dateChange.ChangeType = 1
  735. dateChangeList = append(dateChangeList, dateChange)
  736. newConfig.DateChange = dateChangeList
  737. newConfByte, e := json.Marshal(newConfig)
  738. if e != nil {
  739. err = fmt.Errorf("日期计算额外配置,json序列化失败: %s", e.Error())
  740. return
  741. }
  742. newConf = string(newConfByte)
  743. return
  744. case request.SystemFrequencyDateT: // 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  745. dateChange.FrequencyDay = config.Day
  746. dateChange.Frequency = config.Frequency
  747. dateChange.ChangeType = 1
  748. dateChangeList = append(dateChangeList, dateChange)
  749. newConfig.DateChange = dateChangeList
  750. newConfByte, e := json.Marshal(newConfig)
  751. if e != nil {
  752. err = fmt.Errorf("日期计算额外配置,json序列化失败: %s", e.Error())
  753. return
  754. }
  755. newConf = string(newConfByte)
  756. return
  757. default:
  758. //errMsg = "错误的日期日期导入方式"
  759. //err = errors.New(fmt.Sprint("错误的日期日期导入方式:", config.Source))
  760. return
  761. }
  762. return
  763. }
  764. // handleSystemCalculateDateT
  765. // @Description: 处理系统日期计算后的日期
  766. // @author: Roc
  767. // @datetime2023-10-27 09:31:22
  768. // @param num int
  769. // @param frequency string
  770. // @return date string
  771. // @return err error
  772. // @return errMsg string
  773. func handleSystemCalculateDateT(num int, frequency string) (date string, err error, errMsg string) {
  774. if err != nil {
  775. return
  776. }
  777. currDate := time.Now()
  778. switch frequency {
  779. case "", "日":
  780. date = currDate.AddDate(0, 0, num).Format(utils.FormatDate)
  781. default:
  782. errMsg = "错误的日期频度:" + frequency
  783. err = errors.New(errMsg)
  784. return
  785. }
  786. return
  787. }
  788. // handleSystemAppointDateT
  789. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  790. // @author: Roc
  791. // @datetime2023-10-27 09:31:35
  792. // @param Frequency string
  793. // @param Day string
  794. // @return date string
  795. // @return err error
  796. // @return errMsg string
  797. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  798. //currDate := time.Now()
  799. switch frequency {
  800. case "本周":
  801. day := int(currDate.Weekday())
  802. if day == 0 { // 周日
  803. day = 7
  804. }
  805. num := 0
  806. switch appointDay {
  807. case "周一":
  808. num = 1
  809. case "周二":
  810. num = 2
  811. case "周三":
  812. num = 3
  813. case "周四":
  814. num = 4
  815. case "周五":
  816. num = 5
  817. case "周六":
  818. num = 6
  819. case "周日":
  820. num = 7
  821. }
  822. day = num - day
  823. date = currDate.AddDate(0, 0, day).Format(utils.FormatDate)
  824. case "本旬":
  825. day := currDate.Day()
  826. var tmpDate time.Time
  827. switch appointDay {
  828. case "第一天":
  829. if day <= 10 {
  830. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  831. } else if day <= 20 {
  832. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  833. } else {
  834. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  835. }
  836. case "最后一天":
  837. if day <= 10 {
  838. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  839. } else if day <= 20 {
  840. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  841. } else {
  842. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  843. }
  844. }
  845. date = tmpDate.Format(utils.FormatDate)
  846. case "本月":
  847. var tmpDate time.Time
  848. switch appointDay {
  849. case "第一天":
  850. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  851. case "最后一天":
  852. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  853. }
  854. date = tmpDate.Format(utils.FormatDate)
  855. case "本季":
  856. month := currDate.Month()
  857. var tmpDate time.Time
  858. switch appointDay {
  859. case "第一天":
  860. if month <= 3 {
  861. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  862. } else if month <= 6 {
  863. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  864. } else if month <= 9 {
  865. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  866. } else {
  867. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  868. }
  869. case "最后一天":
  870. if month <= 3 {
  871. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  872. } else if month <= 6 {
  873. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  874. } else if month <= 9 {
  875. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  876. } else {
  877. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  878. }
  879. }
  880. date = tmpDate.Format(utils.FormatDate)
  881. case "本半年":
  882. month := currDate.Month()
  883. var tmpDate time.Time
  884. switch appointDay {
  885. case "第一天":
  886. if month <= 6 {
  887. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  888. } else {
  889. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  890. }
  891. case "最后一天":
  892. if month <= 6 {
  893. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  894. } else {
  895. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  896. }
  897. }
  898. date = tmpDate.Format(utils.FormatDate)
  899. case "本年":
  900. var tmpDate time.Time
  901. switch appointDay {
  902. case "第一天":
  903. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  904. case "最后一天":
  905. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  906. }
  907. date = tmpDate.Format(utils.FormatDate)
  908. default:
  909. errMsg = "错误的日期频度:" + frequency
  910. err = errors.New(errMsg)
  911. return
  912. }
  913. return
  914. }
  915. // calculateByCellList
  916. // @Description: 根据单元格来进行公式计算
  917. // @author: Roc
  918. // @datetime2023-11-14 16:17:38
  919. // @param calculateFormula string
  920. // @param tagList []utils.CellPosition
  921. // @return calVal string
  922. // @return errMsg string
  923. // @return err error
  924. func calculateByCellList(calculateFormula string, tagList []utils.CellPosition) (calVal float64, errMsg string, err error) {
  925. if calculateFormula == "" {
  926. errMsg = "公式异常"
  927. err = errors.New(errMsg)
  928. return
  929. }
  930. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  931. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  932. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  933. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  934. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  935. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  936. rowList := make([]int, 0)
  937. rowListMap := make(map[int][]utils.CellPosition)
  938. for _, v := range tagList {
  939. tmpRowList, ok := rowListMap[v.Row]
  940. if !ok {
  941. rowList = append(rowList, v.Row)
  942. tmpRowList = make([]utils.CellPosition, 0)
  943. }
  944. tmpRowList = append(tmpRowList, v)
  945. rowListMap[v.Row] = tmpRowList
  946. }
  947. sort.Ints(rowList)
  948. list := make([]utils.CellPosition, 0)
  949. for _, row := range rowList {
  950. list = append(list, rowListMap[row]...)
  951. }
  952. formulaFormStr := utils.ReplaceFormulaByCellList(list, calculateFormula)
  953. //计算公式异常,那么就移除该指标
  954. if formulaFormStr == `` {
  955. errMsg = "公式异常"
  956. err = errors.New(errMsg)
  957. return
  958. }
  959. //expression := formula.NewExpression(formulaFormStr)
  960. //calResult, err := expression.Evaluate()
  961. //if err != nil {
  962. // errMsg = "计算失败"
  963. // err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  964. // // 分母为0的报错
  965. // if strings.Contains(err.Error(), "divide by zero") {
  966. // errMsg = "分母不能为0"
  967. // err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  968. // }
  969. // return
  970. //}
  971. //// 如果计算结果是NAN,那么就提示报错
  972. //if calResult.IsNan() {
  973. // errMsg = "计算失败"
  974. // err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  975. // return
  976. //}
  977. //calVal, err = calResult.Float64()
  978. //if err != nil {
  979. // return
  980. //}
  981. calValFloat, err := engine.ParseAndExec(formulaFormStr)
  982. //calVal, err := calResult.Float64()
  983. if err != nil {
  984. err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  985. fmt.Println(err)
  986. return 0, "", err
  987. }
  988. // 转Decimal然后四舍五入
  989. calVal, _ = decimal.NewFromFloat(calValFloat).Round(4).Float64()
  990. return
  991. }
  992. // handlerDateCalculate 处理日期计算
  993. func handlerDateCalculate(dateCalculateList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  994. config = oldConfig
  995. if len(dateCalculateList) == 0 {
  996. return
  997. }
  998. if len(dateCalculateList) > 0 {
  999. for _, cellKey := range dateCalculateList {
  1000. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  1001. cellPosition, ok := calculateCellMap[cellKey]
  1002. if !ok {
  1003. utils.FileLog.Error("找不到单元格位置:", cellKey)
  1004. continue
  1005. }
  1006. cell := config[cellPosition.Column][cellPosition.Row]
  1007. if cell.DataType != request.DateCalculateDataDT { // 判断公式计算(A+B这种)类型,不是的话也过滤了
  1008. continue
  1009. }
  1010. val, tmpErr, tmpErrMsg := DateCalculatePrepare(calculateCellMap, cell.Value)
  1011. if tmpErr != nil {
  1012. cell.ShowValue = ""
  1013. config[cellPosition.Column][cellPosition.Row] = cell
  1014. utils.FileLog.Error(fmt.Sprintf("%s 日期计算报错:Err:%s:%s", cellKey, tmpErr, tmpErrMsg))
  1015. continue
  1016. }
  1017. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  1018. config[cellPosition.Column][cellPosition.Row] = cell
  1019. }
  1020. }
  1021. return
  1022. }
  1023. // DateCalculatePrepare 单个单元格的日期计算
  1024. func DateCalculatePrepare(calculateCellMap map[string]Cell, config string) (val float64, err error, errMsg string) {
  1025. var edbDateConf request.MixDateCalculateConf
  1026. err = json.Unmarshal([]byte(config), &edbDateConf)
  1027. if err != nil {
  1028. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1029. return
  1030. }
  1031. if len(edbDateConf.RelationCellList) == 0 {
  1032. err = fmt.Errorf("日期计算 未配置日期单元格失败: %s", config)
  1033. return
  1034. }
  1035. valMap := make(map[string]int)
  1036. for _, v := range edbDateConf.RelationCellList {
  1037. // 查找单元格数据
  1038. cell, ok := calculateCellMap[v.Uid]
  1039. if !ok {
  1040. err = fmt.Errorf("查找单元格:%s 的数据失败", v.Uid)
  1041. return
  1042. }
  1043. colData := cell.CellInfo
  1044. // 如果不是基础计算单元格,直接返回
  1045. _, err = time.ParseInLocation(utils.FormatDate, colData.ShowValue, time.Local)
  1046. if err != nil {
  1047. err = fmt.Errorf("%s 的单元格非日期类型, Err: %s", colData.ShowValue, err.Error())
  1048. return
  1049. }
  1050. // todo 把日期转换成excel里的天数
  1051. realDiffDay := utils.GetDaysDiff1900(colData.ShowValue)
  1052. valMap[strings.ToUpper(v.Tag)] = realDiffDay
  1053. }
  1054. // 计算
  1055. val, errMsg, err = DateCalculateFormula(valMap, strings.ToUpper(edbDateConf.Formula))
  1056. if err != nil {
  1057. return
  1058. }
  1059. return
  1060. }
  1061. func DateCalculateFormula(valTagMap map[string]int, calculateFormula string) (calVal float64, errMsg string, err error) {
  1062. if calculateFormula == "" {
  1063. errMsg = "公式异常"
  1064. err = errors.New(errMsg)
  1065. return
  1066. }
  1067. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  1068. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  1069. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  1070. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  1071. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  1072. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  1073. formulaFormStr := utils.ReplaceFormulaByTagMap(valTagMap, calculateFormula)
  1074. if formulaFormStr == `` {
  1075. errMsg = "公式异常"
  1076. err = errors.New(errMsg)
  1077. return
  1078. }
  1079. //fmt.Println("公式:" + formulaFormStr)
  1080. //expression := formula.NewExpression(formulaFormStr)
  1081. //calResult, err := expression.Evaluate()
  1082. //if err != nil {
  1083. // errMsg = "公式错误,请重新填写"
  1084. // err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  1085. // // 分母为0的报错
  1086. // if strings.Contains(err.Error(), "divide by zero") {
  1087. // errMsg = "分母不能为0"
  1088. // err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  1089. // }
  1090. // return
  1091. //}
  1092. //// 如果计算结果是NAN,那么就提示报错
  1093. //if calResult.IsNan() {
  1094. // errMsg = "公式错误,请重新填写"
  1095. // err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  1096. // return
  1097. //}
  1098. //calVal, err = calResult.Float64()
  1099. //if err != nil {
  1100. // return
  1101. //}
  1102. calValFloat, err := engine.ParseAndExec(formulaFormStr)
  1103. //calVal, err := calResult.Float64()
  1104. if err != nil {
  1105. err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  1106. fmt.Println(err)
  1107. return 0, "", err
  1108. }
  1109. // 转Decimal然后四舍五入
  1110. calVal, _ = decimal.NewFromFloat(calValFloat).Round(4).Float64()
  1111. return
  1112. }
  1113. // handleMixCellShowStyle 处理混合表格中,显示计算的逻辑
  1114. func handleMixCellShowStyle(showStyleList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  1115. config = oldConfig
  1116. if len(showStyleList) == 0 {
  1117. return
  1118. }
  1119. if len(showStyleList) > 0 {
  1120. for _, cellKey := range showStyleList {
  1121. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  1122. cellPosition, ok := calculateCellMap[cellKey]
  1123. if !ok {
  1124. utils.FileLog.Error("找不到单元格位置:", cellKey)
  1125. continue
  1126. }
  1127. cell := config[cellPosition.Column][cellPosition.Row]
  1128. val := cell.ShowValue
  1129. // 前端不支持手动输入的%数
  1130. // isPercent := false
  1131. // if strings.Contains(val, "%") {
  1132. // isPercent = true
  1133. // val = strings.Trim(val, "%")
  1134. // }
  1135. // 如果没有showValue, 则使用value
  1136. if cell.ShowValue == "" {
  1137. _, err := strconv.ParseFloat(cell.Value, 64)
  1138. if err == nil {
  1139. val = cell.Value
  1140. cell.ShowValue = cell.Value
  1141. }
  1142. }
  1143. _, e := strconv.ParseFloat(val, 64) // 将字符串转换成float类型
  1144. if e != nil { // 如果没有错误发生则返回true,说明该字符串是一个合法的数字
  1145. var styleConf request.MixCellShowStyle
  1146. err = json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  1147. if err != nil {
  1148. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1149. return
  1150. }
  1151. // 前端传过来的json中有可能有glObj,需要去掉
  1152. if styleConf.GlObj != nil {
  1153. styleConf.GlObj = nil
  1154. }
  1155. tmpStyleConf, err := json.Marshal(styleConf)
  1156. if err == nil {
  1157. cell.ShowStyle = string(tmpStyleConf)
  1158. }
  1159. config[cellPosition.Column][cellPosition.Row] = cell
  1160. continue
  1161. }
  1162. var styleConf request.MixCellShowStyle
  1163. err = json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  1164. if err != nil {
  1165. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1166. return
  1167. }
  1168. hasPercent := false
  1169. if styleConf.Nt == "percent" {
  1170. hasPercent = true
  1171. }
  1172. if styleConf.Pn != 0 || styleConf.Nt != "" {
  1173. // val = changePointDecimalPlaces(val, styleConf.Pn, styleConf.Nt, hasPercent)
  1174. // cell.ShowFormatValue = val
  1175. // 修复历史数据,没有保存小数位数,重置小数位数
  1176. if styleConf.Pn != 0 {
  1177. if styleConf.Decimal == nil {
  1178. styleConf.Decimal = new(int)
  1179. }
  1180. *styleConf.Decimal += styleConf.Pn
  1181. if *styleConf.Decimal < 0 {
  1182. *styleConf.Decimal = 0
  1183. }
  1184. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1185. styleConf.Pn = 0
  1186. } else if styleConf.Decimal != nil {
  1187. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1188. } else {
  1189. if hasPercent {
  1190. numDecimal, _ := decimal.NewFromString(cell.ShowValue)
  1191. tmpStr := numDecimal.Mul(decimal.NewFromInt(100)).String()
  1192. cell.ShowFormatValue = tmpStr + "%"
  1193. } else {
  1194. cell.ShowFormatValue = cell.ShowValue
  1195. }
  1196. }
  1197. } else if styleConf.Decimal != nil {
  1198. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1199. } else {
  1200. cell.ShowFormatValue = cell.ShowValue
  1201. }
  1202. // 前端传过来的json中有可能有glObj,需要去掉
  1203. styleConf.GlObj = nil
  1204. tmpStyleConf, err := json.Marshal(styleConf)
  1205. if err == nil {
  1206. cell.ShowStyle = string(tmpStyleConf)
  1207. }
  1208. config[cellPosition.Column][cellPosition.Row] = cell
  1209. }
  1210. }
  1211. return
  1212. }
  1213. func getDecimalLen(str string, isPercent bool) (decimalPlaces int) {
  1214. dotIndex := strings.Index(str, ".") // 查找小数点的位置
  1215. if dotIndex == -1 {
  1216. decimalPlaces = 0
  1217. } else {
  1218. decimalPlaces = len(str) - dotIndex - 1
  1219. }
  1220. if isPercent && decimalPlaces >= 1 {
  1221. decimalPlaces -= 1
  1222. }
  1223. return
  1224. }
  1225. // changePointDecimalPlaces 小数点位数加减和百分比格式
  1226. func changePointDecimalPlaces(str string, changeNum int, numberType string, isPercent bool) (newStr string) {
  1227. newStr = str
  1228. var decimalPlaces int
  1229. dotIndex := strings.Index(newStr, ".") // 查找小数点的位置
  1230. if dotIndex == -1 {
  1231. decimalPlaces = 0
  1232. } else {
  1233. decimalPlaces = len(newStr) - dotIndex - 1
  1234. }
  1235. // 把字符串转成浮点数
  1236. val, _ := strconv.ParseFloat(str, 64)
  1237. if isPercent {
  1238. if numberType == "number" { //百分数转成小数
  1239. val = val / 100
  1240. if decimalPlaces > 1 {
  1241. decimalPlaces += 2
  1242. } else if decimalPlaces == 1 {
  1243. decimalPlaces += 1
  1244. } else if decimalPlaces == 0 {
  1245. if len(str) == 1 || len(str) > 2 {
  1246. decimalPlaces = 2
  1247. } else if len(str) == 2 {
  1248. if str[1] == '0' {
  1249. decimalPlaces = 1
  1250. } else {
  1251. decimalPlaces = 2
  1252. }
  1253. }
  1254. }
  1255. isPercent = false
  1256. }
  1257. } else {
  1258. if numberType == "percent" {
  1259. if decimalPlaces >= 2 {
  1260. decimalPlaces -= 2
  1261. } else if decimalPlaces == 1 {
  1262. decimalPlaces = 0
  1263. }
  1264. val = val * 100
  1265. }
  1266. }
  1267. if decimalPlaces > 0 {
  1268. val, _ = decimal.NewFromFloat(val).Round(int32(decimalPlaces)).Float64()
  1269. newStr = strconv.FormatFloat(val, 'f', decimalPlaces, 64)
  1270. } else {
  1271. // 此处用%.f避免科学计数法, 从而导致后面出现很多位0
  1272. newStr = fmt.Sprintf("%.f", val)
  1273. }
  1274. // 计算小数位数
  1275. decimalPlaces = 0
  1276. dotIndex = strings.Index(newStr, ".") // 查找小数点的位置
  1277. if dotIndex == -1 {
  1278. decimalPlaces = 0
  1279. } else {
  1280. decimalPlaces = len(newStr) - dotIndex - 1
  1281. }
  1282. decimalPlaces += changeNum
  1283. if decimalPlaces < 0 {
  1284. decimalPlaces = 0
  1285. }
  1286. val, _ = decimal.NewFromFloat(val).Round(int32(decimalPlaces)).Float64()
  1287. newStr = strconv.FormatFloat(val, 'f', decimalPlaces, 64)
  1288. if numberType == "percent" || isPercent {
  1289. newStr += "%"
  1290. }
  1291. return
  1292. }
  1293. func fixCalculateValueConfig(conf string, edbInfoId int) (newConf string, err error) {
  1294. newConf = conf
  1295. if edbInfoId == 0 {
  1296. return
  1297. }
  1298. var tmpConfig request.CalculateConf
  1299. err = json.Unmarshal([]byte(conf), &tmpConfig)
  1300. if err != nil {
  1301. return
  1302. }
  1303. if tmpConfig.EdbInfoId == 0 {
  1304. tmpConfig.EdbInfoId = edbInfoId
  1305. newConfByte, _ := json.Marshal(tmpConfig)
  1306. newConf = string(newConfByte)
  1307. return
  1308. }
  1309. return
  1310. }