mixed_table.go 39 KB

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