mixed_table.go 34 KB

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