mixed_table.go 37 KB

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