util.go 16 KB

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