mixed_table.go 37 KB

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