mixed_table.go 37 KB

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