mixed_table.go 37 KB

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