mixed_table.go 39 KB

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