mixed_table.go 37 KB

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