mixed_table.go 37 KB

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