mixed_table.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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. "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. config = setDefaultCellWidth(config)
  427. newMixedTableCellDataList = config
  428. return
  429. }
  430. func setDefaultCellWidth(config [][]request.MixedTableCellDataReq) (newConfig [][]request.MixedTableCellDataReq) {
  431. newConfig = config
  432. for i, row := range config {
  433. for j, cell := range row {
  434. var styleConf request.MixCellShowStyle
  435. if cell.ShowStyle == `` {
  436. styleConf = request.MixCellShowStyle{
  437. Width: 140,
  438. }
  439. } else {
  440. err := json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  441. if err != nil {
  442. continue
  443. }
  444. if styleConf.Width == 0 {
  445. styleConf.Width = 140
  446. }
  447. }
  448. tmpStyleConf, err := json.Marshal(styleConf)
  449. if err == nil {
  450. cell.ShowStyle = string(tmpStyleConf)
  451. }
  452. newConfig[i][j] = cell
  453. }
  454. }
  455. return
  456. }
  457. // getCalculateValue 获取公式计算的结果
  458. func getCalculateValueByCell(calculateCellMap map[string]Cell, key string, cellKeyValMap map[string]float64) (val float64, has bool, err error, errMsg string) {
  459. // 单元格的标签名
  460. val, ok := cellKeyValMap[key]
  461. if ok {
  462. has = true
  463. return
  464. }
  465. // 查找单元格数据
  466. cell, ok := calculateCellMap[key]
  467. if !ok {
  468. err = errors.New("查找单元格" + key + "的数据失败")
  469. return
  470. }
  471. colData := cell.CellInfo
  472. // 如果不是基础计算单元格,直接返回
  473. if colData.DataType != request.FormulateCalculateDataDT {
  474. return
  475. }
  476. // 如果是计算单元格
  477. tagList := make([]utils.CellPosition, 0)
  478. // 计算单元格relationCellList
  479. var relationCellList []request.RelationCell
  480. if colData.Extra == `` {
  481. err = errors.New(colData.Uid + "没有绑定关系")
  482. return
  483. }
  484. err = json.Unmarshal([]byte(colData.Extra), &relationCellList)
  485. if err != nil {
  486. return
  487. }
  488. for _, relation := range relationCellList {
  489. //relationCellTagName := strings.ToUpper(relation.Tag) + relation.Row
  490. tmpVal, _, tmpErr, tmpErrMsg := getCalculateValueByCell(calculateCellMap, relation.Key, cellKeyValMap)
  491. if tmpErr != nil {
  492. errMsg = tmpErrMsg
  493. err = tmpErr
  494. return
  495. }
  496. cellKeyValMap[relation.Key] = tmpVal
  497. rowInt, tmpErr := strconv.Atoi(relation.Row)
  498. if tmpErr != nil {
  499. err = tmpErr
  500. return
  501. }
  502. tagList = append(tagList, utils.CellPosition{
  503. Tag: relation.Tag,
  504. Row: rowInt,
  505. Value: tmpVal,
  506. })
  507. }
  508. // 计算
  509. val, errMsg, err = calculateByCellList(strings.ToUpper(colData.Value), tagList)
  510. if err != nil {
  511. return
  512. }
  513. // 重新赋值
  514. has = true
  515. cellKeyValMap[key] = val
  516. return
  517. }
  518. // handleConfig
  519. // @Description: 处理混合表格配置
  520. // @author: Roc
  521. // @datetime2023-10-27 13:24:53
  522. // @param configList [][]request.MixedTableCellDataReq
  523. // @return newConfig [][]request.MixedTableCellDataReq
  524. // @return edbInfoIdList []int
  525. // @return dataEdbInfoIdList []int
  526. // @return err error
  527. // @return errMsg string
  528. func handleConfig(configList [][]request.MixedTableCellDataReq) (newConfig [][]request.MixedTableCellDataReq, edbInfoIdList []int, dataEdbInfoIdList []int, err error, errMsg string) {
  529. edbInfoIdList = make([]int, 0)
  530. dataEdbInfoIdList = make([]int, 0)
  531. for ck, rowList := range configList {
  532. for rk, cell := range rowList {
  533. switch cell.DataType {
  534. case request.EdbDT: // 指标信息
  535. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  536. case request.InsertDataDT, request.PopInsertDataDT: // 插值、弹框插值
  537. dataEdbInfoIdList = append(dataEdbInfoIdList, cell.EdbInfoId)
  538. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  539. case request.InsertEdbCalculateDataDT: // 插入指标计算公式生成的值
  540. var config request.CalculateConf
  541. err = json.Unmarshal([]byte(cell.Value), &config)
  542. if err != nil {
  543. return
  544. }
  545. if config.EdbInfoId == 0 && cell.EdbInfoId > 0 {
  546. edbInfoIdList = append(edbInfoIdList, cell.EdbInfoId)
  547. } else {
  548. edbInfoIdList = append(edbInfoIdList, config.EdbInfoId)
  549. }
  550. dataEdbInfoIdList = append(dataEdbInfoIdList, cell.EdbInfoId)
  551. case request.DateDT: // 日期类型
  552. date, newVal, tmpErr, tmpErrMsg := handleDate(cell.DataTimeType, cell.Value)
  553. if tmpErr != nil {
  554. err = tmpErr
  555. errMsg = tmpErrMsg
  556. return
  557. }
  558. rowList[rk].DataTime = date
  559. rowList[rk].ShowValue = date
  560. rowList[rk].Value = newVal //兼容原有的历史数据中系统导入日期
  561. // 指标日期类型的单元格需要额外将指标id取出来
  562. if cell.DataTimeType == request.EdbDateDT {
  563. var config request.EdbDateConf
  564. err = json.Unmarshal([]byte(cell.Value), &config)
  565. if err != nil {
  566. return
  567. }
  568. edbInfoIdList = append(edbInfoIdList, config.EdbInfoId)
  569. }
  570. }
  571. }
  572. configList[ck] = rowList
  573. }
  574. newConfig = configList
  575. return
  576. }
  577. // HandleDate
  578. // @Description: 日期处理
  579. // @author: Roc
  580. // @datetime2023-10-27 09:37:02
  581. // @param dataTimeType int
  582. // @param val string
  583. // @return date string
  584. // @return err error
  585. // @return errMsg string
  586. func HandleDate(dataTimeType int, val string) (date string, newVal string, err error, errMsg string) {
  587. return handleDate(dataTimeType, val)
  588. }
  589. // handleDate
  590. // @Description: 日期处理
  591. // @author: Roc
  592. // @datetime2023-10-27 09:36:49
  593. // @param dataTimeType int
  594. // @param val string
  595. // @return date string
  596. // @return err error
  597. // @return errMsg string
  598. func handleDate(dataTimeType int, val string) (date string, newVal string, err error, errMsg string) {
  599. newVal = val
  600. if val == `` {
  601. errMsg = "错误的日期数据"
  602. err = errors.New(errMsg)
  603. return
  604. }
  605. switch dataTimeType {
  606. case request.CustomDateT: //手动输入日期
  607. /*if !strings.Contains(val, "{") {
  608. newVal, err, errMsg = handleOldCustomerDateT(val)
  609. if err != nil {
  610. return
  611. }
  612. }
  613. date, err = HandleMixTableDateChange("", newVal)
  614. if err != nil {
  615. return
  616. }*/
  617. date = val
  618. return
  619. case request.SystemDateT: // 系统日期
  620. date = time.Now().Format(utils.FormatDate)
  621. newVal, err, errMsg = handleOldSystemDateT(val)
  622. if err != nil {
  623. return
  624. }
  625. date, err = HandleMixTableDateChange(date, newVal)
  626. if err != nil {
  627. return
  628. }
  629. case request.EdbDateDT: // 导入指标日期(指标库的最新日期)
  630. default:
  631. errMsg = "错误的日期类型"
  632. err = errors.New(errMsg)
  633. return
  634. }
  635. return
  636. }
  637. func GetEdbDateByMoveForward(conf string, edbDataList []*data_manage.EdbDataList) (date string, err error) {
  638. dateList := make([]string, 0)
  639. for _, v := range edbDataList {
  640. dateList = append(dateList, v.DataTime)
  641. }
  642. date, err = GetEdbDateByMoveForwardByDateList(conf, dateList)
  643. return
  644. }
  645. func GetEdbDateByMoveForwardByDateList(conf string, dateList []string) (date string, err error) {
  646. moveForward := 0
  647. if conf != "" {
  648. var edbDateConf request.EdbDateChangeConf
  649. err = json.Unmarshal([]byte(conf), &edbDateConf)
  650. if err != nil {
  651. err = fmt.Errorf("日期变换配置json解析失败失败: %s", err.Error())
  652. return
  653. }
  654. moveForward = edbDateConf.MoveForward
  655. }
  656. // 根据日期进行排序
  657. index := len(dateList) - 1 - moveForward
  658. for k, v := range dateList {
  659. if k == index {
  660. date = v
  661. return
  662. }
  663. }
  664. return
  665. }
  666. // HandleMixTableDateChange 处理表格中的日期变换
  667. func HandleMixTableDateChange(date, conf string) (newDate string, err error) {
  668. newDate = date
  669. if conf == "" {
  670. return
  671. }
  672. var edbDateConf request.EdbDateConf
  673. err = json.Unmarshal([]byte(conf), &edbDateConf)
  674. if err != nil {
  675. err = fmt.Errorf("日期变换配置json解析失败失败: %s, Err:%s", conf, err.Error())
  676. return
  677. }
  678. if newDate != "" {
  679. if len(edbDateConf.DateChange) > 0 {
  680. var dateTime time.Time
  681. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  682. if err != nil {
  683. err = fmt.Errorf("日期解析失败: %s", err.Error())
  684. return
  685. }
  686. for _, v := range edbDateConf.DateChange {
  687. if v.ChangeType == 1 {
  688. dateTime = dateTime.AddDate(v.Year, v.Month, v.Day)
  689. newDate = dateTime.Format(utils.FormatDate)
  690. } else if v.ChangeType == 2 {
  691. newDate, err, _ = HandleSystemAppointDateT(dateTime, v.FrequencyDay, v.Frequency)
  692. if err != nil {
  693. return
  694. }
  695. dateTime, err = time.ParseInLocation(utils.FormatDate, newDate, time.Local)
  696. if err != nil {
  697. err = fmt.Errorf("日期解析失败: %s", err.Error())
  698. return
  699. }
  700. }
  701. }
  702. }
  703. }
  704. return
  705. }
  706. // handleOldSystemDateT
  707. // @Description: 历史数据中的导入系统日期
  708. // @author: Roc
  709. // @datetime2023-10-27 09:36:21
  710. // @param confStr string
  711. // @return date string
  712. // @return err error
  713. // @return errMsg string
  714. func handleOldSystemDateT(confStr string) (newConf string, err error, errMsg string) {
  715. newConf = confStr
  716. var config request.SystemDateConf
  717. err = json.Unmarshal([]byte(confStr), &config)
  718. if err != nil {
  719. return
  720. }
  721. newConfig := new(request.EdbDateConf)
  722. dateChange := new(request.EdbDateConfDateChange)
  723. dateChangeList := make([]*request.EdbDateConfDateChange, 0)
  724. switch config.Source {
  725. case request.SystemCurrDateT:
  726. return
  727. case request.SystemCalculateDateT:
  728. // todo 是否直接更新该excel记录,
  729. dateChange.Day = config.CalculateNum
  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. case request.SystemFrequencyDateT: // 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  741. dateChange.FrequencyDay = config.Day
  742. dateChange.Frequency = config.Frequency
  743. dateChange.ChangeType = 1
  744. dateChangeList = append(dateChangeList, dateChange)
  745. newConfig.DateChange = dateChangeList
  746. newConfByte, e := json.Marshal(newConfig)
  747. if e != nil {
  748. err = fmt.Errorf("日期计算额外配置,json序列化失败: %s", e.Error())
  749. return
  750. }
  751. newConf = string(newConfByte)
  752. return
  753. default:
  754. //errMsg = "错误的日期日期导入方式"
  755. //err = errors.New(fmt.Sprint("错误的日期日期导入方式:", config.Source))
  756. return
  757. }
  758. return
  759. }
  760. // handleSystemCalculateDateT
  761. // @Description: 处理系统日期计算后的日期
  762. // @author: Roc
  763. // @datetime2023-10-27 09:31:22
  764. // @param num int
  765. // @param frequency string
  766. // @return date string
  767. // @return err error
  768. // @return errMsg string
  769. func handleSystemCalculateDateT(num int, frequency string) (date string, err error, errMsg string) {
  770. if err != nil {
  771. return
  772. }
  773. currDate := time.Now()
  774. switch frequency {
  775. case "", "日":
  776. date = currDate.AddDate(0, 0, num).Format(utils.FormatDate)
  777. default:
  778. errMsg = "错误的日期频度:" + frequency
  779. err = errors.New(errMsg)
  780. return
  781. }
  782. return
  783. }
  784. // handleSystemAppointDateT
  785. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  786. // @author: Roc
  787. // @datetime2023-10-27 09:31:35
  788. // @param Frequency string
  789. // @param Day string
  790. // @return date string
  791. // @return err error
  792. // @return errMsg string
  793. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  794. //currDate := time.Now()
  795. switch frequency {
  796. case "本周":
  797. day := int(currDate.Weekday())
  798. if day == 0 { // 周日
  799. day = 7
  800. }
  801. num := 0
  802. switch appointDay {
  803. case "周一":
  804. num = 1
  805. case "周二":
  806. num = 2
  807. case "周三":
  808. num = 3
  809. case "周四":
  810. num = 4
  811. case "周五":
  812. num = 5
  813. case "周六":
  814. num = 6
  815. case "周日":
  816. num = 7
  817. }
  818. day = num - day
  819. date = currDate.AddDate(0, 0, day).Format(utils.FormatDate)
  820. case "本旬":
  821. day := currDate.Day()
  822. var tmpDate time.Time
  823. switch appointDay {
  824. case "第一天":
  825. if day <= 10 {
  826. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  827. } else if day <= 20 {
  828. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  829. } else {
  830. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  831. }
  832. case "最后一天":
  833. if day <= 10 {
  834. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  835. } else if day <= 20 {
  836. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  837. } else {
  838. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  839. }
  840. }
  841. date = tmpDate.Format(utils.FormatDate)
  842. case "本月":
  843. var tmpDate time.Time
  844. switch appointDay {
  845. case "第一天":
  846. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  847. case "最后一天":
  848. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  849. }
  850. date = tmpDate.Format(utils.FormatDate)
  851. case "本季":
  852. month := currDate.Month()
  853. var tmpDate time.Time
  854. switch appointDay {
  855. case "第一天":
  856. if month <= 3 {
  857. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  858. } else if month <= 6 {
  859. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  860. } else if month <= 9 {
  861. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  862. } else {
  863. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  864. }
  865. case "最后一天":
  866. if month <= 3 {
  867. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  868. } else if month <= 6 {
  869. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  870. } else if month <= 9 {
  871. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  872. } else {
  873. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  874. }
  875. }
  876. date = tmpDate.Format(utils.FormatDate)
  877. case "本半年":
  878. month := currDate.Month()
  879. var tmpDate time.Time
  880. switch appointDay {
  881. case "第一天":
  882. if month <= 6 {
  883. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  884. } else {
  885. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  886. }
  887. case "最后一天":
  888. if month <= 6 {
  889. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  890. } else {
  891. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  892. }
  893. }
  894. date = tmpDate.Format(utils.FormatDate)
  895. case "本年":
  896. var tmpDate time.Time
  897. switch appointDay {
  898. case "第一天":
  899. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  900. case "最后一天":
  901. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  902. }
  903. date = tmpDate.Format(utils.FormatDate)
  904. default:
  905. errMsg = "错误的日期频度:" + frequency
  906. err = errors.New(errMsg)
  907. return
  908. }
  909. return
  910. }
  911. // calculateByCellList
  912. // @Description: 根据单元格来进行公式计算
  913. // @author: Roc
  914. // @datetime2023-11-14 16:17:38
  915. // @param calculateFormula string
  916. // @param tagList []utils.CellPosition
  917. // @return calVal string
  918. // @return errMsg string
  919. // @return err error
  920. func calculateByCellList(calculateFormula string, tagList []utils.CellPosition) (calVal float64, errMsg string, err error) {
  921. if calculateFormula == "" {
  922. errMsg = "公式异常"
  923. err = errors.New(errMsg)
  924. return
  925. }
  926. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  927. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  928. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  929. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  930. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  931. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  932. rowList := make([]int, 0)
  933. rowListMap := make(map[int][]utils.CellPosition)
  934. for _, v := range tagList {
  935. tmpRowList, ok := rowListMap[v.Row]
  936. if !ok {
  937. rowList = append(rowList, v.Row)
  938. tmpRowList = make([]utils.CellPosition, 0)
  939. }
  940. tmpRowList = append(tmpRowList, v)
  941. rowListMap[v.Row] = tmpRowList
  942. }
  943. sort.Ints(rowList)
  944. list := make([]utils.CellPosition, 0)
  945. for _, row := range rowList {
  946. list = append(list, rowListMap[row]...)
  947. }
  948. formulaFormStr := utils.ReplaceFormulaByCellList(list, calculateFormula)
  949. //计算公式异常,那么就移除该指标
  950. if formulaFormStr == `` {
  951. errMsg = "公式异常"
  952. err = errors.New(errMsg)
  953. return
  954. }
  955. expression := formula.NewExpression(formulaFormStr)
  956. calResult, err := expression.Evaluate()
  957. if err != nil {
  958. errMsg = "计算失败"
  959. err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  960. // 分母为0的报错
  961. if strings.Contains(err.Error(), "divide by zero") {
  962. errMsg = "分母不能为0"
  963. err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  964. }
  965. return
  966. }
  967. // 如果计算结果是NAN,那么就提示报错
  968. if calResult.IsNan() {
  969. errMsg = "计算失败"
  970. err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  971. return
  972. }
  973. calVal, err = calResult.Float64()
  974. if err != nil {
  975. return
  976. }
  977. // 转Decimal然后四舍五入
  978. calVal, _ = decimal.NewFromFloat(calVal).Round(4).Float64()
  979. return
  980. }
  981. // handlerDateCalculate 处理日期计算
  982. func handlerDateCalculate(dateCalculateList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  983. config = oldConfig
  984. if len(dateCalculateList) == 0 {
  985. return
  986. }
  987. if len(dateCalculateList) > 0 {
  988. for _, cellKey := range dateCalculateList {
  989. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  990. cellPosition, ok := calculateCellMap[cellKey]
  991. if !ok {
  992. utils.FileLog.Error("找不到单元格位置:", cellKey)
  993. continue
  994. }
  995. cell := config[cellPosition.Column][cellPosition.Row]
  996. if cell.DataType != request.DateCalculateDataDT { // 判断公式计算(A+B这种)类型,不是的话也过滤了
  997. continue
  998. }
  999. val, tmpErr, tmpErrMsg := DateCalculatePrepare(calculateCellMap, cell.Value)
  1000. if tmpErr != nil {
  1001. cell.ShowValue = ""
  1002. config[cellPosition.Column][cellPosition.Row] = cell
  1003. utils.FileLog.Error(fmt.Sprintf("%s 日期计算报错:Err:%s:%s", cellKey, tmpErr, tmpErrMsg))
  1004. continue
  1005. }
  1006. cell.ShowValue = utils.FormatMixTableDataShowValue(val)
  1007. config[cellPosition.Column][cellPosition.Row] = cell
  1008. }
  1009. }
  1010. return
  1011. }
  1012. // DateCalculatePrepare 单个单元格的日期计算
  1013. func DateCalculatePrepare(calculateCellMap map[string]Cell, config string) (val float64, err error, errMsg string) {
  1014. var edbDateConf request.MixDateCalculateConf
  1015. err = json.Unmarshal([]byte(config), &edbDateConf)
  1016. if err != nil {
  1017. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1018. return
  1019. }
  1020. if len(edbDateConf.RelationCellList) == 0 {
  1021. err = fmt.Errorf("日期计算 未配置日期单元格失败: %s", config)
  1022. return
  1023. }
  1024. valMap := make(map[string]int)
  1025. for _, v := range edbDateConf.RelationCellList {
  1026. // 查找单元格数据
  1027. cell, ok := calculateCellMap[v.Uid]
  1028. if !ok {
  1029. err = fmt.Errorf("查找单元格:%s 的数据失败", v.Uid)
  1030. return
  1031. }
  1032. colData := cell.CellInfo
  1033. // 如果不是基础计算单元格,直接返回
  1034. _, err = time.ParseInLocation(utils.FormatDate, colData.ShowValue, time.Local)
  1035. if err != nil {
  1036. err = fmt.Errorf("%s 的单元格非日期类型, Err: %s", colData.ShowValue, err.Error())
  1037. return
  1038. }
  1039. // todo 把日期转换成excel里的天数
  1040. realDiffDay := utils.GetDaysDiff1900(colData.ShowValue)
  1041. valMap[strings.ToUpper(v.Tag)] = realDiffDay
  1042. }
  1043. // 计算
  1044. val, errMsg, err = DateCalculateFormula(valMap, strings.ToUpper(edbDateConf.Formula))
  1045. if err != nil {
  1046. return
  1047. }
  1048. return
  1049. }
  1050. func DateCalculateFormula(valTagMap map[string]int, calculateFormula string) (calVal float64, errMsg string, err error) {
  1051. if calculateFormula == "" {
  1052. errMsg = "公式异常"
  1053. err = errors.New(errMsg)
  1054. return
  1055. }
  1056. calculateFormula = strings.TrimPrefix(calculateFormula, "=")
  1057. calculateFormula = strings.Replace(calculateFormula, "(", "(", -1)
  1058. calculateFormula = strings.Replace(calculateFormula, ")", ")", -1)
  1059. calculateFormula = strings.Replace(calculateFormula, ",", ",", -1)
  1060. calculateFormula = strings.Replace(calculateFormula, "。", ".", -1)
  1061. calculateFormula = strings.Replace(calculateFormula, "%", "*0.01", -1)
  1062. formulaFormStr := utils.ReplaceFormulaByTagMap(valTagMap, calculateFormula)
  1063. if formulaFormStr == `` {
  1064. errMsg = "公式异常"
  1065. err = errors.New(errMsg)
  1066. return
  1067. }
  1068. fmt.Println("公式:" + formulaFormStr)
  1069. expression := formula.NewExpression(formulaFormStr)
  1070. calResult, err := expression.Evaluate()
  1071. if err != nil {
  1072. errMsg = "公式错误,请重新填写"
  1073. err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  1074. // 分母为0的报错
  1075. if strings.Contains(err.Error(), "divide by zero") {
  1076. errMsg = "分母不能为0"
  1077. err = errors.New("分母不能为空,计算公式:" + formulaFormStr)
  1078. }
  1079. return
  1080. }
  1081. // 如果计算结果是NAN,那么就提示报错
  1082. if calResult.IsNan() {
  1083. errMsg = "公式错误,请重新填写"
  1084. err = errors.New("计算失败:计算结果是:NAN;formulaStr:" + formulaFormStr)
  1085. return
  1086. }
  1087. calVal, err = calResult.Float64()
  1088. if err != nil {
  1089. return
  1090. }
  1091. // 转Decimal然后四舍五入
  1092. calVal, _ = decimal.NewFromFloat(calVal).Round(4).Float64()
  1093. return
  1094. }
  1095. // handleMixCellShowStyle 处理混合表格中,显示计算的逻辑
  1096. func handleMixCellShowStyle(showStyleList []string, calculateCellMap map[string]Cell, oldConfig [][]request.MixedTableCellDataReq) (config [][]request.MixedTableCellDataReq, err error, errMsg string) {
  1097. config = oldConfig
  1098. if len(showStyleList) == 0 {
  1099. return
  1100. }
  1101. if len(showStyleList) > 0 {
  1102. for _, cellKey := range showStyleList {
  1103. // 查找这个单元格的位置,直接map找了,而不是遍历整个单元格
  1104. cellPosition, ok := calculateCellMap[cellKey]
  1105. if !ok {
  1106. utils.FileLog.Error("找不到单元格位置:", cellKey)
  1107. continue
  1108. }
  1109. cell := config[cellPosition.Column][cellPosition.Row]
  1110. val := cell.ShowValue
  1111. // 前端不支持手动输入的%数
  1112. // isPercent := false
  1113. // if strings.Contains(val, "%") {
  1114. // isPercent = true
  1115. // val = strings.Trim(val, "%")
  1116. // }
  1117. // 如果没有showValue, 则使用value
  1118. if cell.ShowValue == "" {
  1119. _, err := strconv.ParseFloat(cell.Value, 64)
  1120. if err == nil {
  1121. val = cell.Value
  1122. cell.ShowValue = cell.Value
  1123. }
  1124. }
  1125. _, e := strconv.ParseFloat(val, 64) // 将字符串转换成float类型
  1126. if e != nil { // 如果没有错误发生则返回true,说明该字符串是一个合法的数字
  1127. var styleConf request.MixCellShowStyle
  1128. err = json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  1129. if err != nil {
  1130. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1131. return
  1132. }
  1133. // 前端传过来的json中有可能有glObj,需要去掉
  1134. if styleConf.GlObj != nil {
  1135. styleConf.GlObj = nil
  1136. }
  1137. tmpStyleConf, err := json.Marshal(styleConf)
  1138. if err == nil {
  1139. cell.ShowStyle = string(tmpStyleConf)
  1140. }
  1141. config[cellPosition.Column][cellPosition.Row] = cell
  1142. continue
  1143. }
  1144. var styleConf request.MixCellShowStyle
  1145. err = json.Unmarshal([]byte(cell.ShowStyle), &styleConf)
  1146. if err != nil {
  1147. err = fmt.Errorf("日期计算配置json解析失败失败: %s, Err:%s", config, err.Error())
  1148. return
  1149. }
  1150. hasPercent := false
  1151. if styleConf.Nt == "percent" {
  1152. hasPercent = true
  1153. }
  1154. if styleConf.Pn != 0 || styleConf.Nt != "" {
  1155. // val = changePointDecimalPlaces(val, styleConf.Pn, styleConf.Nt, hasPercent)
  1156. // cell.ShowFormatValue = val
  1157. // 修复历史数据,没有保存小数位数,重置小数位数
  1158. if styleConf.Pn != 0 {
  1159. if styleConf.Decimal == nil {
  1160. styleConf.Decimal = new(int)
  1161. }
  1162. *styleConf.Decimal += styleConf.Pn
  1163. if *styleConf.Decimal < 0 {
  1164. *styleConf.Decimal = 0
  1165. }
  1166. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1167. styleConf.Pn = 0
  1168. } else if styleConf.Decimal != nil {
  1169. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1170. } else {
  1171. if hasPercent {
  1172. numDecimal, _ := decimal.NewFromString(cell.ShowValue)
  1173. tmpStr := numDecimal.Mul(decimal.NewFromInt(100)).String()
  1174. cell.ShowFormatValue = tmpStr + "%"
  1175. } else {
  1176. cell.ShowFormatValue = cell.ShowValue
  1177. }
  1178. }
  1179. } else if styleConf.Decimal != nil {
  1180. cell.ShowFormatValue = utils.RoundNumber(cell.ShowValue, *styleConf.Decimal, hasPercent)
  1181. } else {
  1182. cell.ShowFormatValue = cell.ShowValue
  1183. }
  1184. // 前端传过来的json中有可能有glObj,需要去掉
  1185. styleConf.GlObj = nil
  1186. tmpStyleConf, err := json.Marshal(styleConf)
  1187. if err == nil {
  1188. cell.ShowStyle = string(tmpStyleConf)
  1189. }
  1190. config[cellPosition.Column][cellPosition.Row] = cell
  1191. }
  1192. }
  1193. return
  1194. }
  1195. func getDecimalLen(str string, isPercent bool) (decimalPlaces int) {
  1196. dotIndex := strings.Index(str, ".") // 查找小数点的位置
  1197. if dotIndex == -1 {
  1198. decimalPlaces = 0
  1199. } else {
  1200. decimalPlaces = len(str) - dotIndex - 1
  1201. }
  1202. if isPercent && decimalPlaces >= 1 {
  1203. decimalPlaces -= 1
  1204. }
  1205. return
  1206. }
  1207. // changePointDecimalPlaces 小数点位数加减和百分比格式
  1208. func changePointDecimalPlaces(str string, changeNum int, numberType string, isPercent bool) (newStr string) {
  1209. newStr = str
  1210. var decimalPlaces int
  1211. dotIndex := strings.Index(newStr, ".") // 查找小数点的位置
  1212. if dotIndex == -1 {
  1213. decimalPlaces = 0
  1214. } else {
  1215. decimalPlaces = len(newStr) - dotIndex - 1
  1216. }
  1217. // 把字符串转成浮点数
  1218. val, _ := strconv.ParseFloat(str, 64)
  1219. if isPercent {
  1220. if numberType == "number" { //百分数转成小数
  1221. val = val / 100
  1222. if decimalPlaces > 2 {
  1223. decimalPlaces += 2
  1224. } else if decimalPlaces == 1 {
  1225. decimalPlaces += 1
  1226. } else if decimalPlaces == 0 {
  1227. if len(str) == 1 {
  1228. decimalPlaces = 2
  1229. } else if len(str) == 2 {
  1230. if str[1] == '0' {
  1231. decimalPlaces = 1
  1232. } else {
  1233. decimalPlaces = 2
  1234. }
  1235. }
  1236. }
  1237. isPercent = false
  1238. }
  1239. } else {
  1240. if numberType == "percent" {
  1241. if decimalPlaces > 2 {
  1242. decimalPlaces -= 2
  1243. } else if decimalPlaces == 1 {
  1244. decimalPlaces = 0
  1245. }
  1246. val = val * 100
  1247. }
  1248. }
  1249. if decimalPlaces > 0 {
  1250. val, _ = decimal.NewFromFloat(val).Round(int32(decimalPlaces)).Float64()
  1251. newStr = strconv.FormatFloat(val, 'f', decimalPlaces, 64)
  1252. } else {
  1253. // 此处用%.f避免科学计数法, 从而导致后面出现很多位0
  1254. newStr = fmt.Sprintf("%.f", val)
  1255. }
  1256. // 计算小数位数
  1257. decimalPlaces = 0
  1258. dotIndex = strings.Index(newStr, ".") // 查找小数点的位置
  1259. if dotIndex == -1 {
  1260. decimalPlaces = 0
  1261. } else {
  1262. decimalPlaces = len(newStr) - dotIndex - 1
  1263. }
  1264. decimalPlaces += changeNum
  1265. if decimalPlaces < 0 {
  1266. decimalPlaces = 0
  1267. }
  1268. val, _ = decimal.NewFromFloat(val).Round(int32(decimalPlaces)).Float64()
  1269. newStr = strconv.FormatFloat(val, 'f', decimalPlaces, 64)
  1270. if numberType == "percent" || isPercent {
  1271. newStr += "%"
  1272. }
  1273. return
  1274. }
  1275. func fixCalculateValueConfig(conf string, edbInfoId int) (newConf string, err error) {
  1276. newConf = conf
  1277. if edbInfoId == 0 {
  1278. return
  1279. }
  1280. var tmpConfig request.CalculateConf
  1281. err = json.Unmarshal([]byte(conf), &tmpConfig)
  1282. if err != nil {
  1283. return
  1284. }
  1285. if tmpConfig.EdbInfoId == 0 {
  1286. tmpConfig.EdbInfoId = edbInfoId
  1287. newConfByte, _ := json.Marshal(tmpConfig)
  1288. newConf = string(newConfByte)
  1289. return
  1290. }
  1291. return
  1292. }