mixed_table.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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. newConf = confStr
  663. var config request.SystemDateConf
  664. err = json.Unmarshal([]byte(confStr), &config)
  665. if err != nil {
  666. return
  667. }
  668. newConfig := new(request.EdbDateConf)
  669. dateChange := new(request.EdbDateConfDateChange)
  670. dateChangeList := make([]*request.EdbDateConfDateChange, 0)
  671. switch config.Source {
  672. case request.SystemCurrDateT:
  673. return
  674. case request.SystemCalculateDateT:
  675. // todo 是否直接更新该excel记录,
  676. dateChange.Day = config.CalculateNum
  677. dateChange.ChangeType = 1
  678. dateChangeList = append(dateChangeList, dateChange)
  679. newConfig.DateChange = dateChangeList
  680. newConfByte, e := json.Marshal(newConfig)
  681. if e != nil {
  682. err = fmt.Errorf("日期计算额外配置,json序列化失败: %s", e.Error())
  683. return
  684. }
  685. newConf = string(newConfByte)
  686. return
  687. case request.SystemFrequencyDateT: // 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  688. dateChange.FrequencyDay = config.Day
  689. dateChange.Frequency = config.Frequency
  690. dateChange.ChangeType = 1
  691. dateChangeList = append(dateChangeList, dateChange)
  692. newConfig.DateChange = dateChangeList
  693. newConfByte, e := json.Marshal(newConfig)
  694. if e != nil {
  695. err = fmt.Errorf("日期计算额外配置,json序列化失败: %s", e.Error())
  696. return
  697. }
  698. newConf = string(newConfByte)
  699. return
  700. default:
  701. //errMsg = "错误的日期日期导入方式"
  702. //err = errors.New(fmt.Sprint("错误的日期日期导入方式:", config.Source))
  703. return
  704. }
  705. return
  706. }
  707. // handleSystemCalculateDateT
  708. // @Description: 处理系统日期计算后的日期
  709. // @author: Roc
  710. // @datetime2023-10-27 09:31:22
  711. // @param num int
  712. // @param frequency string
  713. // @return date string
  714. // @return err error
  715. // @return errMsg string
  716. func handleSystemCalculateDateT(num int, frequency string) (date string, err error, errMsg string) {
  717. if err != nil {
  718. return
  719. }
  720. currDate := time.Now()
  721. switch frequency {
  722. case "", "日":
  723. date = currDate.AddDate(0, 0, num).Format(utils.FormatDate)
  724. default:
  725. errMsg = "错误的日期频度:" + frequency
  726. err = errors.New(errMsg)
  727. return
  728. }
  729. return
  730. }
  731. // handleSystemAppointDateT
  732. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  733. // @author: Roc
  734. // @datetime2023-10-27 09:31:35
  735. // @param Frequency string
  736. // @param Day string
  737. // @return date string
  738. // @return err error
  739. // @return errMsg string
  740. func handleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  741. //currDate := time.Now()
  742. switch frequency {
  743. case "本周":
  744. day := int(currDate.Weekday())
  745. if day == 0 { // 周日
  746. day = 7
  747. }
  748. num := 0
  749. switch appointDay {
  750. case "周一":
  751. num = 1
  752. case "周二":
  753. num = 2
  754. case "周三":
  755. num = 3
  756. case "周四":
  757. num = 4
  758. case "周五":
  759. num = 5
  760. case "周六":
  761. num = 6
  762. case "周日":
  763. num = 7
  764. }
  765. day = num - day
  766. date = currDate.AddDate(0, 0, day).Format(utils.FormatDate)
  767. case "本旬":
  768. day := currDate.Day()
  769. var tmpDate time.Time
  770. switch appointDay {
  771. case "第一天":
  772. if day <= 10 {
  773. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  774. } else if day <= 20 {
  775. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  776. } else {
  777. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  778. }
  779. case "最后一天":
  780. if day <= 10 {
  781. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  782. } else if day <= 20 {
  783. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  784. } else {
  785. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  786. }
  787. }
  788. date = tmpDate.Format(utils.FormatDate)
  789. case "本月":
  790. var tmpDate time.Time
  791. switch appointDay {
  792. case "第一天":
  793. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  794. case "最后一天":
  795. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  796. }
  797. date = tmpDate.Format(utils.FormatDate)
  798. case "本季":
  799. month := currDate.Month()
  800. var tmpDate time.Time
  801. switch appointDay {
  802. case "第一天":
  803. if month <= 3 {
  804. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  805. } else if month <= 6 {
  806. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  807. } else if month <= 9 {
  808. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  809. } else {
  810. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  811. }
  812. case "最后一天":
  813. if month <= 3 {
  814. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  815. } else if month <= 6 {
  816. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  817. } else if month <= 9 {
  818. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  819. } else {
  820. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  821. }
  822. }
  823. date = tmpDate.Format(utils.FormatDate)
  824. case "本半年":
  825. month := currDate.Month()
  826. var tmpDate time.Time
  827. switch appointDay {
  828. case "第一天":
  829. if month <= 6 {
  830. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  831. } else {
  832. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  833. }
  834. case "最后一天":
  835. if month <= 6 {
  836. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  837. } else {
  838. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  839. }
  840. }
  841. date = tmpDate.Format(utils.FormatDate)
  842. case "本年":
  843. var tmpDate time.Time
  844. switch appointDay {
  845. case "第一天":
  846. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  847. case "最后一天":
  848. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  849. }
  850. date = tmpDate.Format(utils.FormatDate)
  851. default:
  852. errMsg = "错误的日期频度:" + frequency
  853. err = errors.New(errMsg)
  854. return
  855. }
  856. return
  857. }
  858. // calculateByCellList
  859. // @Description: 根据单元格来进行公式计算
  860. // @author: Roc
  861. // @datetime2023-11-14 16:17:38
  862. // @param calculateFormula string
  863. // @param tagList []utils.CellPosition
  864. // @return calVal string
  865. // @return errMsg string
  866. // @return err error
  867. func calculateByCellList(calculateFormula string, tagList []utils.CellPosition) (calVal float64, errMsg string, err error) {
  868. if calculateFormula == "" {
  869. errMsg = "公式异常"
  870. err = errors.New(errMsg)
  871. return
  872. }
  873. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  874. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  875. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  876. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  877. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  878. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  879. rowList := make([]int, 0)
  880. rowListMap := make(map[int][]utils.CellPosition)
  881. for _, v := range tagList {
  882. tmpRowList, ok := rowListMap[v.Row]
  883. if !ok {
  884. rowList = append(rowList, v.Row)
  885. tmpRowList = make([]utils.CellPosition, 0)
  886. }
  887. tmpRowList = append(tmpRowList, v)
  888. rowListMap[v.Row] = tmpRowList
  889. }
  890. sort.Ints(rowList)
  891. list := make([]utils.CellPosition, 0)
  892. for _, row := range rowList {
  893. list = append(list, rowListMap[row]...)
  894. }
  895. formulaFormStr := utils.ReplaceFormulaByCellList(list, calculateFormula)
  896. //计算公式异常,那么就移除该指标
  897. if formulaFormStr == `` {
  898. errMsg = "公式异常"
  899. err = errors.New(errMsg)
  900. return
  901. }
  902. expression := formula.NewExpression(formulaFormStr)
  903. calResult, err := expression.Evaluate()
  904. if err != nil {
  905. errMsg = "计算失败"
  906. err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  907. // 分母为0的报错
  908. if strings.Contains(err.Error(), "divide by zero") {
  909. errMsg = "分母不能为0"
  910. err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  911. }
  912. return
  913. }
  914. // 如果计算结果是NAN,那么就提示报错
  915. if calResult.IsNan() {
  916. errMsg = "计算失败"
  917. err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  918. return
  919. }
  920. calVal, err = calResult.Float64()
  921. if err != nil {
  922. return
  923. }
  924. // 转Decimal然后四舍五入
  925. calVal, _ = decimal.NewFromFloat(calVal).Round(4).Float64()
  926. return
  927. }
  928. // handlerDateCalculate 处理日期计算
  929. func handlerDateCalculate(dateCalculateList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  930. config = oldConfig
  931. if len(dateCalculateList) == 0 {
  932. return
  933. }
  934. if len(dateCalculateList) > 0 {
  935. for _, cellKey := range dateCalculateList {
  936. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  937. cellPosition, ok := calculateCellMap[cellKey]
  938. if !ok {
  939. utils.FileLog.Error("找不到单元格位置:", cellKey)
  940. continue
  941. }
  942. cell := config[cellPosition.Column][cellPosition.Row]
  943. if cell.DataType != request.DateCalculateDataDT { // 判断公式计算(A+B这种)类型,不是的话也过滤了
  944. continue
  945. }
  946. val, tmpErr, tmpErrMsg := DateCalculatePrepare(calculateCellMap, cell.Value)
  947. if tmpErr != nil {
  948. errMsg = tmpErrMsg
  949. err = tmpErr
  950. return
  951. }
  952. cell.ShowValue = utils.FormatTableDataShowValue(val)
  953. config[cellPosition.Column][cellPosition.Row] = cell
  954. }
  955. }
  956. return
  957. }
  958. // DateCalculatePrepare 单个单元格的日期计算
  959. func DateCalculatePrepare(calculateCellMap map[string]Cell, config string) (val float64, err error, errMsg string) {
  960. var edbDateConf request.MixDateCalculateConf
  961. err = json.Unmarshal([]byte(config), &edbDateConf)
  962. if err != nil {
  963. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  964. return
  965. }
  966. if len(edbDateConf.RelationCellList) == 0 {
  967. err = fmt.Errorf("日期计算 未配置日期单元格失败: %s", config)
  968. return
  969. }
  970. valMap := make(map[string]int)
  971. for _, v := range edbDateConf.RelationCellList {
  972. // 查找单元格数据
  973. cell, ok := calculateCellMap[v.Uid]
  974. if !ok {
  975. err = fmt.Errorf("查找单元格:%s 的数据失败", v.Uid)
  976. return
  977. }
  978. colData := cell.CellInfo
  979. // 如果不是基础计算单元格,直接返回
  980. _, err = time.ParseInLocation(utils.FormatDate, colData.ShowValue, time.Local)
  981. if err != nil {
  982. err = fmt.Errorf("%s 的单元格非日期类型, Err: %s", colData.ShowValue, err.Error())
  983. return
  984. }
  985. // todo 把日期转换成excel里的天数
  986. realDiffDay := utils.GetDaysDiff1900(colData.ShowValue)
  987. valMap[strings.ToUpper(v.Tag)] = realDiffDay
  988. }
  989. // 计算
  990. val, errMsg, err = DateCalculateFormula(valMap, strings.ToUpper(edbDateConf.Formula))
  991. if err != nil {
  992. return
  993. }
  994. return
  995. }
  996. func DateCalculateFormula(valTagMap map[string]int, calculateFormula string) (calVal float64, errMsg string, err error) {
  997. if calculateFormula == "" {
  998. errMsg = "公式异常"
  999. err = errors.New(errMsg)
  1000. return
  1001. }
  1002. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  1003. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  1004. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  1005. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  1006. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  1007. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  1008. formulaFormStr := utils.ReplaceFormulaByTagMap(valTagMap, calculateFormula)
  1009. if formulaFormStr == `` {
  1010. errMsg = "公式异常"
  1011. err = errors.New(errMsg)
  1012. return
  1013. }
  1014. fmt.Println("公式:" + formulaFormStr)
  1015. expression := formula.NewExpression(formulaFormStr)
  1016. calResult, err := expression.Evaluate()
  1017. if err != nil {
  1018. errMsg = "计算失败"
  1019. err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  1020. // 分母为0的报错
  1021. if strings.Contains(err.Error(), "divide by zero") {
  1022. errMsg = "分母不能为0"
  1023. err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  1024. }
  1025. return
  1026. }
  1027. // 如果计算结果是NAN,那么就提示报错
  1028. if calResult.IsNan() {
  1029. errMsg = "计算失败"
  1030. err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  1031. return
  1032. }
  1033. calVal, err = calResult.Float64()
  1034. if err != nil {
  1035. return
  1036. }
  1037. // 转Decimal然后四舍五入
  1038. calVal, _ = decimal.NewFromFloat(calVal).Round(4).Float64()
  1039. return
  1040. }
  1041. // handleMixCellShowStyle 处理混合表格中,显示计算的逻辑
  1042. func handleMixCellShowStyle(showStyleList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  1043. config = oldConfig
  1044. if len(showStyleList) == 0 {
  1045. return
  1046. }
  1047. if len(showStyleList) > 0 {
  1048. for _, cellKey := range showStyleList {
  1049. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  1050. cellPosition, ok := calculateCellMap[cellKey]
  1051. if !ok {
  1052. utils.FileLog.Error("找不到单元格位置:", cellKey)
  1053. continue
  1054. }
  1055. cell := config[cellPosition.Column][cellPosition.Row]
  1056. _, e := strconv.ParseFloat(cell.ShowStyle, 64) // 将字符串转换成float类型
  1057. if e != nil { // 如果没有错误发生则返回true,说明该字符串是一个合法的数字
  1058. continue
  1059. }
  1060. val := cell.ShowStyle
  1061. var styleConf request.MixCellShowStyle
  1062. err = json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  1063. if err != nil {
  1064. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1065. return
  1066. }
  1067. if styleConf.NumberStyle.AddPointNum != 0 {
  1068. //val = CountDecimalPlaces(val)
  1069. val = changePointDecimalPlaces(cell.ShowStyle, styleConf.NumberStyle.AddPointNum)
  1070. }
  1071. if styleConf.NumberStyle.IsPercent == 1 {
  1072. val = changeToPercent(cell.ShowStyle)
  1073. }
  1074. cell.ShowValue = val
  1075. config[cellPosition.Column][cellPosition.Row] = cell
  1076. }
  1077. }
  1078. return
  1079. }
  1080. // changePointDecimalPlaces 小数点位数加减
  1081. func changePointDecimalPlaces(str string, changeNum int) (newStr string) {
  1082. newStr = str
  1083. if changeNum == 0 { //无需改变
  1084. return
  1085. }
  1086. dotIndex := strings.Index(str, ".") // 查找小数点的位置
  1087. if dotIndex == -1 {
  1088. return // 没有小数点,返回0
  1089. }
  1090. decimalPlaces := len(str) - dotIndex - 1 // 计算小数位数
  1091. numbers := strings.Split(str, ".")
  1092. number1 := numbers[0] //整数部分
  1093. number2 := numbers[1] //小数部分
  1094. if changeNum > 0 { // 增加小数位数
  1095. newStr = number1 + "." + number2 + strings.Repeat("0", changeNum)
  1096. } else if changeNum < 0 { // 减少小数位数
  1097. newStr = number1 + "." + number2[:decimalPlaces+changeNum]
  1098. }
  1099. fmt.Println(newStr)
  1100. return
  1101. }
  1102. // changeToPercent 展示成百分比
  1103. func changeToPercent(str string) (newStr string) {
  1104. newStr = str
  1105. dotIndex := strings.Index(str, ".") // 查找小数点的位置
  1106. if dotIndex == -1 {
  1107. newStr = newStr + "00%"
  1108. return // 没有小数点,返回0
  1109. }
  1110. decimalPlaces := len(str) - dotIndex - 1 // 计算小数位数
  1111. numbers := strings.Split(str, ".")
  1112. number1 := numbers[0] //整数部分
  1113. number2 := numbers[1] //小数部分
  1114. if decimalPlaces == 1 {
  1115. newStr = number1 + number2 + "0%"
  1116. return
  1117. }
  1118. if decimalPlaces == 2 {
  1119. newStr = number1 + number2 + "%"
  1120. return
  1121. }
  1122. newStr = number1 + number2[:2] + "." + number2[2:] + "%"
  1123. fmt.Println(newStr)
  1124. return
  1125. }