util.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. package util
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "regexp"
  7. "time"
  8. "gitee.com/xuyiping_admin/pkg/xerr"
  9. )
  10. const (
  11. LayoutTime = "2006-01-02 15:04:05"
  12. Layout = "2006-01-02"
  13. LayoutMonth = "2006-01"
  14. LetterBytes = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789"
  15. LetterIdxBits = 6 // 6 bits to represent a letter index
  16. LetterIdxMask = 1<<LetterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  17. LetterIdxMax = 63 / LetterIdxBits // # of letter indices fitting in 63 bits
  18. )
  19. var (
  20. FrameIdMap = map[int32]int32{
  21. 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 8: 8, // 00-02
  22. 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 18: 18, // 02-04
  23. 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 28: 28, // 04-06
  24. 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 38: 38, // 06-08
  25. 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 48: 48, // 08-10
  26. 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 58: 58, // 10-12
  27. 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 68: 68, // 12-14
  28. 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 78: 78, // 14-16
  29. 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 88: 88, // 16-18
  30. 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 98: 98, // 18-20
  31. 101: 101, 102: 102, 103: 103, 104: 104, 105: 105, 106: 106, 108: 108, // 20-22
  32. 111: 111, 112: 112, 113: 113, 114: 114, 115: 115, 116: 116, 118: 118, // 22-24
  33. }
  34. SpecialHours = map[int]int{8: 2, 18: 4, 28: 6, 38: 8, 48: 10, 58: 12, 68: 14, 78: 16, 88: 18, 98: 20, 108: 22, 118: 0}
  35. FrameIdMapReverse = map[int32]int32{
  36. 0: 8,
  37. 1: 8,
  38. 2: 18,
  39. 3: 18,
  40. 4: 28,
  41. 5: 28,
  42. 6: 38,
  43. 7: 38,
  44. 8: 48,
  45. 9: 48,
  46. 10: 58,
  47. 11: 58,
  48. 12: 68,
  49. 13: 68,
  50. 14: 78,
  51. 15: 78,
  52. 16: 88,
  53. 17: 88,
  54. 18: 98,
  55. 19: 98,
  56. 20: 108,
  57. 21: 108,
  58. 22: 118, // 04-06
  59. 23: 118,
  60. }
  61. ExpectedFrameIDs = []int32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
  62. )
  63. // GenerateRandomNumberString 生成指定长度的数字串
  64. func GenerateRandomNumberString(n int) string {
  65. result := make([]byte, n)
  66. // A rand.Int63() generates 63 random bits, enough for letterIdxMax characters!
  67. rand.Seed(time.Now().UnixNano())
  68. for i, cache, remain := n-1, rand.Int63(), LetterIdxMax; i >= 0; {
  69. if remain == 0 {
  70. cache, remain = rand.Int63(), LetterIdxMax
  71. }
  72. if idx := int(cache & LetterIdxMask); idx < len(LetterBytes) {
  73. result[i] = LetterBytes[idx]
  74. i--
  75. }
  76. cache >>= LetterIdxBits
  77. remain--
  78. }
  79. return string(result)
  80. }
  81. // TimeParseLocalUnix 获取当天零点的时间戳
  82. // eg 2023-02-22 => 1676995200
  83. func TimeParseLocalUnix(DayTime string) int64 {
  84. value := DayTime
  85. if len(DayTime) <= 11 {
  86. value = fmt.Sprintf("%s 00:00:00", DayTime)
  87. }
  88. theTime, _ := TimeParseLocal(LayoutTime, value)
  89. return theTime.Unix()
  90. }
  91. // TimeParseLocalEndUnix 获取当天24点的时间戳
  92. // eg 2023-02-22 => 1676995200
  93. func TimeParseLocalEndUnix(DayTime string) int64 {
  94. value := DayTime
  95. if len(DayTime) <= 11 {
  96. value = fmt.Sprintf("%s 23:59:59", DayTime)
  97. }
  98. theTime, _ := TimeParseLocal(LayoutTime, value)
  99. return theTime.Unix()
  100. }
  101. // ConvertParseLocalUnix 字符串转换当天时间戳
  102. // eg 15:04:05 => 1676998245
  103. func ConvertParseLocalUnix(timeParse string) (int64, error) {
  104. value := fmt.Sprintf("%s %s", time.Now().Format(Layout), timeParse)
  105. theTime, err := TimeParseLocal(LayoutTime, value)
  106. if err != nil {
  107. return 0, err
  108. }
  109. return theTime.Unix(), nil
  110. }
  111. // GetMonthRemainDay 获取当前月还剩几天
  112. func GetMonthRemainDay() int {
  113. now := time.Now()
  114. lastDayOfMonth := time.Date(now.Year(), now.Month()+1, 0, 23, 59, 59, 999999999, now.Location())
  115. return int(lastDayOfMonth.Sub(now).Hours()/24) + 1
  116. }
  117. // Ceil 向上取整函数
  118. func Ceil(x float64) float64 {
  119. // 使用 math.Floor 计算小于或等于 x 的最大整数
  120. // 然后检查 x 是否为整数,如果不是,则结果加 1
  121. // 注意:math.Floor 返回的是 float64 类型,所以我们需要进行比较
  122. // 来确定是否需要加 1
  123. intPart := math.Floor(x)
  124. if x-intPart > 0 {
  125. return intPart + 1
  126. }
  127. return intPart
  128. }
  129. // GetLastDayOfMonth
  130. // 接受一个字符串形式的月份(如 "2024-12"),
  131. // 并返回该月份的最后一天的日期(2024-12-31)
  132. func GetLastDayOfMonth(month string) (string, error) {
  133. t, err := TimeParseLocal(LayoutMonth, month)
  134. if err != nil {
  135. return "", err // 如果解析失败,返回错误
  136. }
  137. // 获取下个月的第一天
  138. nextMonth := t.AddDate(0, 1, 0)
  139. // 返回上个月的最后一天
  140. lastDay := nextMonth.AddDate(0, 0, -1)
  141. return lastDay.Format(Layout), nil
  142. }
  143. // GetMonthsInRange
  144. // 接受两个字符串形式的月份(如 "2024-01" 到 "2024-12"),
  145. // 并返回一个包含这两个月份之间所有月份的字符串切片。
  146. func GetMonthsInRange(startMonth, endMonth string) ([]string, error) {
  147. // 解析起始月份
  148. startTime, err := TimeParseLocal(LayoutMonth, startMonth)
  149. if err != nil {
  150. return nil, err
  151. }
  152. // 解析结束月份
  153. endTime, err := TimeParseLocal(LayoutMonth, endMonth)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // 初始化结果切片
  158. var months []string
  159. // 循环添加每个月份直到达到或超过结束月份
  160. for curr := startTime; curr.Before(endTime) || curr.Equal(endTime); curr = curr.AddDate(0, 1, 0) {
  161. months = append(months, curr.Format(LayoutMonth))
  162. }
  163. return months, nil
  164. }
  165. // RoundToTwoDecimals 四舍五入并保留两位小数
  166. func RoundToTwoDecimals(num float64) float64 {
  167. // 使用 math.Round 函数进行四舍五入
  168. // 先乘以 100,然后四舍五入,最后除以 100
  169. return math.Round(num*100) / 100
  170. }
  171. // Get21DayPeriods 获取范围时间内21天周期的切片
  172. // 从结束时间开始往前推算,超过开始时间,继续向前推算,直至凑整21天
  173. func Get21DayPeriods(startDay, endDay string) ([][]string, error) {
  174. startDate, err := TimeParseLocal(Layout, startDay)
  175. if err != nil {
  176. return nil, err
  177. }
  178. endDate, err := TimeParseLocal(Layout, endDay)
  179. if err != nil {
  180. return nil, err
  181. }
  182. if startDate.After(endDate) {
  183. return nil, xerr.Custom("start date is after end date")
  184. }
  185. var periods [][]string
  186. for date := endDate; date.After(startDate); {
  187. // Calculate the end of the current period
  188. periodEnd := date.AddDate(0, 0, -20)
  189. // Append the current period to the result slice
  190. periods = append(periods, []string{periodEnd.Format(Layout), date.Format(Layout)})
  191. // Move on to the next day
  192. date = periodEnd.AddDate(0, 0, -1)
  193. }
  194. reverseRows(periods)
  195. return periods, nil
  196. }
  197. func reverseRows(matrix [][]string) {
  198. // 获取矩阵的行数
  199. rows := len(matrix)
  200. if rows == 0 {
  201. return // 如果矩阵为空,则直接返回
  202. }
  203. // 初始化两个指针,一个指向开始,一个指向末尾
  204. for i, j := 0, rows-1; i < j; i, j = i+1, j-1 {
  205. // 交换当前行和对应行
  206. matrix[i], matrix[j] = matrix[j], matrix[i]
  207. }
  208. }
  209. // GetRangeDayMiddleDay 获取指定日期范围中间的某一天
  210. func GetRangeDayMiddleDay(dateRange []string, middleDay int32) (string, error) {
  211. if len(dateRange) < 2 {
  212. return "", xerr.Custom("date range is not enough")
  213. }
  214. if middleDay < 0 {
  215. return "", xerr.Custom("middle day is not enough")
  216. }
  217. startDate, _ := TimeParseLocal(Layout, dateRange[0])
  218. return startDate.AddDate(0, 0, int(middleDay)-1).Format(Layout), nil
  219. }
  220. // GetRangeDayByDays 获取指定范围日期内按照指定天数来切割
  221. // (2024-10-01 ~ 2024-10-31,5)=> [[2024-10-01,2024-10-05], [2024-10-06,2024-10-10], [2024-10-11,2024-10-15], [2024-10-16,2024-10-20], [2024-10-21,2024-10-25], [2024-10-26,2024-10-30],[2024-10-31,2024-10-31]]
  222. func GetRangeDayByDays(startDay, endDay string, days int32) ([][]string, error) {
  223. var res [][]string
  224. if days <= 0 {
  225. return res, nil
  226. }
  227. startDate, err := TimeParseLocal(Layout, startDay)
  228. if err != nil {
  229. return nil, err
  230. }
  231. endDate, err := TimeParseLocal(Layout, endDay)
  232. if err != nil {
  233. return nil, err
  234. }
  235. if startDate.After(endDate) {
  236. return nil, xerr.Custom("start date is after end date")
  237. }
  238. if startDate == endDate {
  239. return [][]string{{startDay, endDay}}, nil
  240. }
  241. for date := startDate; date.Before(endDate) || date.Equal(endDate); date = date.AddDate(0, 0, int(days)) {
  242. if date.AddDate(0, 0, int(days)-1).After(endDate) {
  243. res = append(res, []string{date.Format(Layout), endDate.Format(Layout)})
  244. break
  245. }
  246. res = append(res, []string{date.Format(Layout), date.AddDate(0, 0, int(days)-1).Format(Layout)})
  247. }
  248. return res, nil
  249. }
  250. // 计算样本均值
  251. func mean(data []float64) float64 {
  252. sum := 0.0
  253. for _, v := range data {
  254. sum += v
  255. }
  256. return sum / float64(len(data))
  257. }
  258. // 计算样本标准差
  259. func stddev(data []float64, mean float64) float64 {
  260. sum := 0.0
  261. for _, v := range data {
  262. sum += (v - mean) * (v - mean)
  263. }
  264. variance := sum / float64(len(data)-1)
  265. return math.Sqrt(variance)
  266. }
  267. // ConfidenceInterval 计算95%置信区间
  268. func ConfidenceInterval(data []float64) (float64, float64) {
  269. n := float64(len(data))
  270. meanVal := mean(data)
  271. stdDev := stddev(data, meanVal)
  272. z := 1.96 // 95%置信水平对应的Z值
  273. marginOfError := z * (stdDev / math.Sqrt(n))
  274. lowerBound := meanVal - marginOfError
  275. upperBound := meanVal + marginOfError
  276. return lowerBound, upperBound
  277. }
  278. // ConfidenceInterval2 计算95%置信区间
  279. func ConfidenceInterval2(p float64, total float64) (min, max float64) {
  280. if p <= 0 || total <= 0 {
  281. return 0, 0
  282. }
  283. z := 1.96 // 95%置信水平对应的Z值
  284. marginOf := z * math.Sqrt(p*(1-p)/total) * 100
  285. return math.Max(0, p*100-math.Ceil(marginOf)), math.Max(1, p*100+math.Ceil(marginOf))
  286. }
  287. // RemoveDuplicates 去除切片中的重复元素
  288. func RemoveDuplicates(slice []string) []string {
  289. if len(slice) <= 0 {
  290. return slice
  291. }
  292. // 创建一个map来跟踪已经遇到的元素
  293. seen := make(map[string]struct{})
  294. // 创建一个新的切片来存储不重复的元素
  295. var result []string
  296. // 遍历原始切片
  297. for _, v := range slice {
  298. // 如果元素尚未在map中,则将其添加到结果切片和map中
  299. if _, exists := seen[v]; !exists {
  300. seen[v] = struct{}{}
  301. result = append(result, v)
  302. }
  303. }
  304. // 返回不重复的切片
  305. return result
  306. }
  307. // DaysBetween 计算两个日期(时间戳)之间的天数差
  308. func DaysBetween(startDayUnix int64, endDayUnix int64) int64 {
  309. time1 := time.Unix(startDayUnix, 0)
  310. time2 := time.Unix(endDayUnix, 0)
  311. // Truncate to the start of the day (00:00:00)
  312. startOfDay1 := time.Date(time1.Year(), time1.Month(), time1.Day(), 0, 0, 0, 0, time1.Location())
  313. startOfDay2 := time.Date(time2.Year(), time2.Month(), time2.Day(), 0, 0, 0, 0, time2.Location())
  314. // Calculate the difference in days
  315. daysDiff := int64(startOfDay2.Sub(startOfDay1).Hours() / 24)
  316. return daysDiff
  317. }
  318. // GetDaysBetween 获取两个日期之间的所有天数
  319. // 2024-10-01 ~ 2024-10-07 => [2024-10-01,2024-10-02,2024-10-03,2024-10-04,2024-10-05,2024-10-06,2024-10-07]
  320. func GetDaysBetween(startDate, endDate string) ([]string, error) {
  321. // 解析日期
  322. start, err := TimeParseLocal(Layout, startDate)
  323. if err != nil {
  324. return nil, fmt.Errorf("解析开始日期失败: %v", err)
  325. }
  326. end, err := TimeParseLocal(Layout, endDate)
  327. if err != nil {
  328. return nil, fmt.Errorf("解析结束日期失败: %v", err)
  329. }
  330. // 确保开始日期早于或等于结束日期
  331. if start.After(end) {
  332. return nil, fmt.Errorf("开始日期不能晚于结束日期")
  333. }
  334. // 存储日期的数组
  335. var days []string
  336. // 遍历日期
  337. for current := start; !current.After(end); current = current.AddDate(0, 0, 1) {
  338. days = append(days, current.Format(Layout))
  339. }
  340. return days, nil
  341. }
  342. // GetMonthsBetween 返回两个日期之间的所有月份
  343. // 参数格式为 "YYYY-MM",例如 "2025-01"
  344. func GetMonthsBetween(start, end string) ([]string, error) {
  345. // 检查参数合法性
  346. if err := validateDate(start); err != nil {
  347. return nil, fmt.Errorf("invalid start date: %v", err)
  348. }
  349. if err := validateDate(end); err != nil {
  350. return nil, fmt.Errorf("invalid end date: %v", err)
  351. }
  352. // 解析起始日期和结束日期
  353. startTime, err := TimeParseLocal(LayoutMonth, start)
  354. if err != nil {
  355. return nil, fmt.Errorf("failed to parse start date: %v", err)
  356. }
  357. endTime, err := TimeParseLocal(LayoutMonth, end)
  358. if err != nil {
  359. return nil, fmt.Errorf("failed to parse end date: %v", err)
  360. }
  361. // 检查起始日期是否早于结束日期
  362. if startTime.After(endTime) {
  363. return nil, xerr.Custom("start date must be before or equal to end date")
  364. }
  365. // 生成月份列表
  366. var months []string
  367. for current := startTime; !current.After(endTime); current = current.AddDate(0, 1, 0) {
  368. months = append(months, current.Format(LayoutMonth))
  369. }
  370. return months, nil
  371. }
  372. // validateDate 检查日期字符串的合法性
  373. func validateDate(date string) error {
  374. if len(date) != 7 || date[4] != '-' {
  375. return xerr.Custom("date format must be YYYY-MM")
  376. }
  377. _, err := TimeParseLocal(LayoutMonth, date)
  378. if err != nil {
  379. return xerr.Customf("invalid date: %v", err)
  380. }
  381. return nil
  382. }
  383. // MsgFormat 格式化消息字符串 字符串里面有多个冒号,仅删除冒号前后的空格(如果存在)
  384. func MsgFormat(input string) string {
  385. // 定义正则表达式,用于匹配冒号两边的空格
  386. re := regexp.MustCompile(`\s*:\s*`)
  387. // 使用正则表达式替换所有匹配的部分
  388. return re.ReplaceAllString(input, ":")
  389. }
  390. // IsValidFrameId 检查 FrameId 是否有效
  391. func IsValidFrameId(frameId int32) bool {
  392. _, ok := FrameIdMap[frameId]
  393. return ok
  394. }
  395. /*
  396. GetNeckRingActiveTimer
  397. 1. frameId值如果是:1到6代表每天的0点到2点,11-16 代表每天的2点到4点, 21-26 代表每天的4点到6点,31-36代表每天的6点到8点,
  398. 41-46 代表每天的8点到10点,51-56代表每天的10点到12点,61-66代表每天的12-14点,71-76代表每天的14-16点,81-86代表每天的16-18点,
  399. 91-96代表每天的18-20点,101-106代表每天的20-22点,111-116代表每天的22-24点。其中每个数字代表20分钟。
  400. 2. 如果frameId大于当前时间点,并往前推20个小时,如果在这个20小时范围内, 就代表frameId是昨天的。
  401. 3. 如果farmId的值出现8,18,28,3848,58,68,78,88,98,108,118数字分别代表2个小时,从0-2点开始,以此类推。
  402. 帮我根据frameId值,获取对应的时间(YYYY-MM-DD)和小时
  403. */
  404. func GetNeckRingActiveTimer(frameId int32) (dateTime string, hours int) {
  405. if frameId < 0 || frameId > 118 {
  406. return "", 0
  407. }
  408. if _, ok := FrameIdMap[frameId]; !ok {
  409. return "", 0
  410. }
  411. nowTime := time.Now()
  412. currHour := nowTime.Hour()
  413. // 处理2小时的特殊 farmId
  414. hours, ok := SpecialHours[int(frameId)]
  415. day := 0
  416. if ok {
  417. if hours == 0 {
  418. hours = 24
  419. }
  420. if hours > currHour {
  421. day = -1
  422. }
  423. hours = 0
  424. dateTime = nowTime.AddDate(0, 0, day).Format(Layout)
  425. return
  426. }
  427. hours = int(math.Floor(float64(frameId)/10) * 2)
  428. units := int(frameId % 10)
  429. hours += units / 3
  430. if hours > currHour {
  431. for i := 0; i <= 20; i++ {
  432. twentyHoursAgo := nowTime.Add(-time.Duration(i) * time.Hour).Hour()
  433. if twentyHoursAgo == 0 {
  434. twentyHoursAgo = 24
  435. }
  436. if hours == twentyHoursAgo {
  437. day = -1
  438. break
  439. }
  440. }
  441. }
  442. dateTime = nowTime.AddDate(0, 0, day).Format(Layout)
  443. return
  444. }
  445. // XFrameId 获取XFrameId
  446. func XFrameId(frameid int32) int32 {
  447. return int32(math.Floor(float64(frameid / 10)))
  448. }
  449. // FrameIds 获取FrameIds
  450. func FrameIds(xFrameId int32) []int32 {
  451. frameIds := make([]int32, 0)
  452. for i := 1; i <= 8; i++ {
  453. if i == 7 {
  454. continue
  455. }
  456. frameIds = append(frameIds, xFrameId*10+int32(i))
  457. }
  458. return frameIds
  459. }