mixed_table.go 37 KB

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