mixed_table.go 37 KB

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