common.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "image"
  14. "image/png"
  15. "io"
  16. "math"
  17. "math/rand"
  18. "net"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/shopspring/decimal"
  28. "gorm.io/gorm"
  29. )
  30. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  31. func GetRandString(size int) string {
  32. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  33. randomSb := ""
  34. digitSize := len(allLetterDigit)
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func GetRandStringNoSpecialChar(size int) string {
  41. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  42. randomSb := ""
  43. digitSize := len(allLetterDigit)
  44. for i := 0; i < size; i++ {
  45. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  46. }
  47. return randomSb
  48. }
  49. func StringsToJSON(str string) string {
  50. rs := []rune(str)
  51. jsons := ""
  52. for _, r := range rs {
  53. rint := int(r)
  54. if rint < 128 {
  55. jsons += string(r)
  56. } else {
  57. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  58. }
  59. }
  60. return jsons
  61. }
  62. func ToString(v interface{}) string {
  63. data, _ := json.Marshal(v)
  64. return string(data)
  65. }
  66. func MD5(data string) string {
  67. m := md5.Sum([]byte(data))
  68. return hex.EncodeToString(m[:])
  69. }
  70. func GetRandDigit(n int) string {
  71. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  72. }
  73. func GetRandNumber(n int) int {
  74. return rnd.Intn(n)
  75. }
  76. func GetRandInt(min, max int) int {
  77. if min >= max || min == 0 || max == 0 {
  78. return max
  79. }
  80. return rand.Intn(max-min) + min
  81. }
  82. func GetToday(format string) string {
  83. today := time.Now().Format(format)
  84. return today
  85. }
  86. func GetTodayLastSecond() time.Duration {
  87. today := GetToday(FormatDate) + " 23:59:59"
  88. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  89. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  90. }
  91. func GetBrithDate(idcard string) string {
  92. l := len(idcard)
  93. var s string
  94. if l == 15 {
  95. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  96. return s
  97. }
  98. if l == 18 {
  99. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  100. return s
  101. }
  102. return GetToday(FormatDate)
  103. }
  104. func WhichSexByIdcard(idcard string) string {
  105. var sexs = [2]string{"女", "男"}
  106. length := len(idcard)
  107. if length == 18 {
  108. sex, _ := strconv.Atoi(string(idcard[16]))
  109. return sexs[sex%2]
  110. } else if length == 15 {
  111. sex, _ := strconv.Atoi(string(idcard[14]))
  112. return sexs[sex%2]
  113. }
  114. return "男"
  115. }
  116. func SubFloatToString(f float64, m int) string {
  117. n := strconv.FormatFloat(f, 'f', -1, 64)
  118. if n == "" {
  119. return ""
  120. }
  121. if m >= len(n) {
  122. return n
  123. }
  124. newn := strings.Split(n, ".")
  125. if m == 0 {
  126. return newn[0]
  127. }
  128. if len(newn) < 2 || m >= len(newn[1]) {
  129. return n
  130. }
  131. return newn[0] + "." + newn[1][:m]
  132. }
  133. func SubFloatToFloat(f float64, m int) float64 {
  134. newn := SubFloatToString(f, m)
  135. newf, _ := strconv.ParseFloat(newn, 64)
  136. return newf
  137. }
  138. func SubFloatToFloatStr(f float64, m int) string {
  139. newn := SubFloatToString(f, m)
  140. return newn
  141. }
  142. func GetYearDiffer(start_time, end_time string) int {
  143. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  144. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  145. age := t2.Year() - t1.Year()
  146. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  147. age--
  148. }
  149. return age
  150. }
  151. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  152. diff := end_time.Unix() - start_time.Unix()
  153. return diff
  154. }
  155. func FixFloat(f float64, m int) float64 {
  156. newn := SubFloatToString(f+0.00000001, m)
  157. newf, _ := strconv.ParseFloat(newn, 64)
  158. return newf
  159. }
  160. func StrListToString(strList []string) (str string) {
  161. if len(strList) > 0 {
  162. for k, v := range strList {
  163. if k == 0 {
  164. str = v
  165. } else {
  166. str = str + "," + v
  167. }
  168. }
  169. return
  170. }
  171. return ""
  172. }
  173. func ErrNoRow() string {
  174. return "<QuerySeter> no row found"
  175. }
  176. func IsErrNoRow(err error) bool {
  177. if err == nil {
  178. return false
  179. }
  180. return errors.Is(err, gorm.ErrRecordNotFound)
  181. }
  182. func ValidateEmailFormatat(email string) bool {
  183. reg := regexp.MustCompile(RegularEmail)
  184. return reg.MatchString(email)
  185. }
  186. func ValidateMobileFormatat(mobileNum string) bool {
  187. reg := regexp.MustCompile(RegularMobile)
  188. return reg.MatchString(mobileNum)
  189. }
  190. func FileIsExist(filePath string) bool {
  191. _, err := os.Stat(filePath)
  192. return err == nil || os.IsExist(err)
  193. }
  194. func GetImgExt(file string) (ext string, err error) {
  195. var headerByte []byte
  196. headerByte = make([]byte, 8)
  197. fd, err := os.Open(file)
  198. if err != nil {
  199. return "", err
  200. }
  201. defer fd.Close()
  202. _, err = fd.Read(headerByte)
  203. if err != nil {
  204. return "", err
  205. }
  206. xStr := fmt.Sprintf("%x", headerByte)
  207. switch {
  208. case xStr == "89504e470d0a1a0a":
  209. ext = ".png"
  210. case xStr == "0000010001002020":
  211. ext = ".ico"
  212. case xStr == "0000020001002020":
  213. ext = ".cur"
  214. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  215. ext = ".gif"
  216. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  217. ext = ".tga"
  218. case xStr[:8] == "464f524d":
  219. ext = ".iff"
  220. case xStr[:8] == "52494646":
  221. ext = ".ani"
  222. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  223. ext = ".tiff"
  224. case xStr[:4] == "424d":
  225. ext = ".bmp"
  226. case xStr[:4] == "ffd8":
  227. ext = ".jpg"
  228. case xStr[:2] == "0a":
  229. ext = ".pcx"
  230. default:
  231. ext = ""
  232. }
  233. return ext, nil
  234. }
  235. func SaveImage(path string, img image.Image) (err error) {
  236. imgfile, err := os.Create(path)
  237. defer imgfile.Close()
  238. err = png.Encode(imgfile, img)
  239. return err
  240. }
  241. func DownloadImage(imgUrl string) (filePath string, err error) {
  242. imgPath := "./static/imgs/"
  243. fileName := path.Base(imgUrl)
  244. res, err := http.Get(imgUrl)
  245. if err != nil {
  246. fmt.Println("A error occurred!")
  247. return
  248. }
  249. defer res.Body.Close()
  250. reader := bufio.NewReaderSize(res.Body, 32*1024)
  251. filePath = imgPath + fileName
  252. file, err := os.Create(filePath)
  253. if err != nil {
  254. return
  255. }
  256. writer := bufio.NewWriter(file)
  257. written, _ := io.Copy(writer, reader)
  258. fmt.Printf("Total length: %d \n", written)
  259. return
  260. }
  261. func SaveBase64ToFile(content, path string) error {
  262. data, err := base64.StdEncoding.DecodeString(content)
  263. if err != nil {
  264. return err
  265. }
  266. f, err := os.Create(path)
  267. defer f.Close()
  268. if err != nil {
  269. return err
  270. }
  271. f.Write(data)
  272. return nil
  273. }
  274. func SaveBase64ToFileBySeek(content, path string) (err error) {
  275. data, err := base64.StdEncoding.DecodeString(content)
  276. exist, err := PathExists(path)
  277. if err != nil {
  278. return
  279. }
  280. if !exist {
  281. f, err := os.Create(path)
  282. if err != nil {
  283. return err
  284. }
  285. n, _ := f.Seek(0, 2)
  286. _, err = f.WriteAt([]byte(data), n)
  287. defer f.Close()
  288. } else {
  289. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  290. if err != nil {
  291. return err
  292. }
  293. n, _ := f.Seek(0, 2)
  294. _, err = f.WriteAt([]byte(data), n)
  295. defer f.Close()
  296. }
  297. return nil
  298. }
  299. func PathExists(path string) (bool, error) {
  300. _, err := os.Stat(path)
  301. if err == nil {
  302. return true, nil
  303. }
  304. if os.IsNotExist(err) {
  305. return false, nil
  306. }
  307. return false, err
  308. }
  309. func StartIndex(page, pagesize int) int {
  310. if page > 1 {
  311. return (page - 1) * pagesize
  312. }
  313. return 0
  314. }
  315. func PageCount(count, pagesize int) int {
  316. if count%pagesize > 0 {
  317. return count/pagesize + 1
  318. } else {
  319. return count / pagesize
  320. }
  321. }
  322. func TrimHtml(src string) string {
  323. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  324. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  325. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  326. src = re.ReplaceAllString(src, "[图片]")
  327. re, _ = regexp.Compile("class[\\S\\s]+?>")
  328. src = re.ReplaceAllString(src, "")
  329. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  330. src = re.ReplaceAllString(src, "")
  331. return strings.TrimSpace(src)
  332. }
  333. func TimeToTimestamp() {
  334. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  335. }
  336. func ToUnicode(text string) string {
  337. textQuoted := strconv.QuoteToASCII(text)
  338. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  339. return textUnquoted
  340. }
  341. func VersionToInt(version string) int {
  342. version = strings.Replace(version, ".", "", -1)
  343. n, _ := strconv.Atoi(version)
  344. return n
  345. }
  346. func IsCheckInList(list []int, s int) bool {
  347. for _, v := range list {
  348. if v == s {
  349. return true
  350. }
  351. }
  352. return false
  353. }
  354. func round(num float64) int {
  355. return int(num + math.Copysign(0.5, num))
  356. }
  357. func toFixed(num float64, precision int) float64 {
  358. output := math.Pow(10, float64(precision))
  359. return float64(round(num*output)) / output
  360. }
  361. func GetWilsonScore(p, n float64) float64 {
  362. if p == 0 && n == 0 {
  363. return 0
  364. }
  365. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  366. }
  367. func ChangeWordsToNum(str string) (numStr string) {
  368. words := ([]rune)(str)
  369. num := 0
  370. n := 0
  371. for i := 0; i < len(words); i++ {
  372. word := string(words[i : i+1])
  373. switch word {
  374. case "万":
  375. if n == 0 {
  376. n = 1
  377. }
  378. n = n * 10000
  379. num = num*10000 + n
  380. n = 0
  381. case "千":
  382. if n == 0 {
  383. n = 1
  384. }
  385. n = n * 1000
  386. num += n
  387. n = 0
  388. case "百":
  389. if n == 0 {
  390. n = 1
  391. }
  392. n = n * 100
  393. num += n
  394. n = 0
  395. case "十":
  396. if n == 0 {
  397. n = 1
  398. }
  399. n = n * 10
  400. num += n
  401. n = 0
  402. case "一":
  403. n += 1
  404. case "二":
  405. n += 2
  406. case "三":
  407. n += 3
  408. case "四":
  409. n += 4
  410. case "五":
  411. n += 5
  412. case "六":
  413. n += 6
  414. case "七":
  415. n += 7
  416. case "八":
  417. n += 8
  418. case "九":
  419. n += 9
  420. case "零":
  421. default:
  422. if n > 0 {
  423. num += n
  424. n = 0
  425. }
  426. if num == 0 {
  427. numStr += word
  428. } else {
  429. numStr += strconv.Itoa(num) + word
  430. num = 0
  431. }
  432. }
  433. }
  434. if n > 0 {
  435. num += n
  436. n = 0
  437. }
  438. if num != 0 {
  439. numStr += strconv.Itoa(num)
  440. }
  441. return
  442. }
  443. func Sha1(data string) string {
  444. sha1 := sha1.New()
  445. sha1.Write([]byte(data))
  446. return hex.EncodeToString(sha1.Sum([]byte("")))
  447. }
  448. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  449. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  450. out, err := exec.Command("bash", "-c", cmd).Output()
  451. if err != nil {
  452. return
  453. }
  454. outTimes := string(out)
  455. fmt.Println("outTimes:", outTimes)
  456. if outTimes != "" {
  457. timeArr := strings.Split(outTimes, ":")
  458. h := timeArr[0]
  459. m := timeArr[1]
  460. s := timeArr[2]
  461. hInt, err := strconv.Atoi(h)
  462. if err != nil {
  463. return playSeconds, err
  464. }
  465. mInt, err := strconv.Atoi(m)
  466. if err != nil {
  467. return playSeconds, err
  468. }
  469. s = strings.Trim(s, " ")
  470. s = strings.Trim(s, "\n")
  471. sInt, err := strconv.ParseFloat(s, 64)
  472. if err != nil {
  473. return playSeconds, err
  474. }
  475. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  476. }
  477. return
  478. }
  479. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  480. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  481. tradeCode = strings.Trim(tradeCode, " ")
  482. tradeCodeInt, err := strconv.Atoi(tradeCode)
  483. if err != nil {
  484. return
  485. }
  486. tradeCodeInt = tradeCodeInt + 1
  487. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  488. return
  489. }
  490. func ConvertToFormatDay(excelDaysString string) string {
  491. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  492. curDiffDay := excelDaysString
  493. b, _ := strconv.Atoi(curDiffDay)
  494. realDiffDay := b - baseDiffDay
  495. realDiffSecond := realDiffDay * 24 * 3600
  496. baseOriginSecond := 1136185445
  497. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  498. return resultTime
  499. }
  500. func CheckPwd(pwd string) bool {
  501. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  502. reg := regexp.MustCompile(compile)
  503. flag := reg.MatchString(pwd)
  504. return flag
  505. }
  506. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  507. if len(myMonth) == 1 {
  508. myMonth = "0" + myMonth
  509. }
  510. yInt, _ := strconv.Atoi(myYear)
  511. timeLayout := "2006-01-02 15:04:05"
  512. loc, _ := time.LoadLocation("Local")
  513. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  514. newMonth := theTime.Month()
  515. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  516. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  517. return t1, t2
  518. }
  519. func TrimStr(str string) (str2 string) {
  520. return strings.Replace(str, " ", "", -1)
  521. }
  522. func StrTimeToTime(strTime string) time.Time {
  523. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  524. loc, _ := time.LoadLocation("Local") //重要:获取时区
  525. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  526. return resultTime
  527. }
  528. func GetOrmInReplace(num int) string {
  529. template := make([]string, num)
  530. for i := 0; i < num; i++ {
  531. template[i] = "?"
  532. }
  533. return strings.Join(template, ",")
  534. }
  535. func GetGormInReplace(num int) string {
  536. if num == 0 {
  537. return ""
  538. }
  539. return "?"
  540. }
  541. func RevSlice(slice []int) []int {
  542. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  543. slice[i], slice[j] = slice[j], slice[i]
  544. }
  545. return slice
  546. }
  547. func GetTimeSubDay(t1, t2 time.Time) int {
  548. var day int
  549. swap := false
  550. if t1.Unix() > t2.Unix() {
  551. t1, t2 = t2, t1
  552. swap = true
  553. }
  554. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  555. day = int(t2.Sub(t1).Hours() / 24)
  556. if t1_.Day() != t1.Day() {
  557. day += 1
  558. }
  559. if swap {
  560. day = -day
  561. }
  562. return day
  563. }
  564. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  565. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  566. if err != nil {
  567. return 0, err
  568. }
  569. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  570. if err != nil {
  571. return 0, err
  572. }
  573. return int(date1.Sub(date2).Hours() / 24), nil
  574. }
  575. type MapSorter []Item
  576. type Item struct {
  577. Key int
  578. Val float64
  579. }
  580. func NewMapSorter(m map[int]float64) MapSorter {
  581. ms := make(MapSorter, 0, len(m))
  582. for k, v := range m {
  583. ms = append(ms, Item{k, v})
  584. }
  585. return ms
  586. }
  587. func (ms MapSorter) Len() int {
  588. return len(ms)
  589. }
  590. func (ms MapSorter) Less(i, j int) bool {
  591. return ms[i].Val > ms[j].Val // 按值排序
  592. }
  593. func (ms MapSorter) Swap(i, j int) {
  594. ms[i], ms[j] = ms[j], ms[i]
  595. }
  596. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  597. for _, id := range idIntList {
  598. if id == searchId {
  599. has = true
  600. return
  601. }
  602. }
  603. return
  604. }
  605. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  606. for _, id := range idStrList {
  607. if id == searchId {
  608. has = true
  609. return
  610. }
  611. }
  612. return
  613. }
  614. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  615. startDate = tmpStartDate
  616. endDate = tmpEndDate
  617. switch dateType {
  618. case 1:
  619. startDate = "2000-01-01"
  620. endDate = ""
  621. case 2:
  622. startDate = "2010-01-01"
  623. endDate = ""
  624. case 3:
  625. startDate = "2015-01-01"
  626. endDate = ""
  627. case 4:
  628. startDate = "2021-01-01"
  629. endDate = ""
  630. case 5:
  631. case 6:
  632. endDate = ""
  633. case 7:
  634. startDate = "2018-01-01"
  635. endDate = ""
  636. case 8:
  637. startDate = "2019-01-01"
  638. endDate = ""
  639. case 9:
  640. startDate = "2020-01-01"
  641. endDate = ""
  642. case 11:
  643. startDate = "2022-01-01"
  644. endDate = ""
  645. }
  646. {
  647. if strings.Count(startDate, "-") == 1 {
  648. startDate = startDate + "-01"
  649. }
  650. if strings.Count(endDate, "-") == 1 {
  651. endDate = endDate + "-01"
  652. }
  653. }
  654. return
  655. }
  656. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  657. switch dateType {
  658. case 1:
  659. startDate = currDate.AddDate(0, -3, 0)
  660. case 2:
  661. startDate = currDate.AddDate(0, -6, 0)
  662. case 3:
  663. startDate = currDate.AddDate(-1, 0, 0)
  664. case 4:
  665. startDate = currDate.AddDate(-2, 0, 0)
  666. case 5:
  667. startDate = currDate.AddDate(-3, 0, 0)
  668. case 6:
  669. startDate = currDate.AddDate(-5, 0, 0)
  670. case 7:
  671. startDate = currDate.AddDate(-10, 0, 0)
  672. }
  673. return
  674. }
  675. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  676. if num >= 1 {
  677. tmpNum := int(math.Ceil(num)) // 向上取整
  678. str := strconv.Itoa(tmpNum)
  679. lenStr := len(str)
  680. if lenStr > baseLen {
  681. newNumStr := str[0:baseLen]
  682. newNumInt, _ := strconv.Atoi(newNumStr)
  683. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  684. if newNum < num {
  685. newNumInt += 1
  686. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  687. }
  688. } else {
  689. newNum = float64(tmpNum)
  690. }
  691. return
  692. } else if num > 0 {
  693. str := strconv.FormatFloat(num, 'f', -1, 64)
  694. str = removeDecimalPoint(str)
  695. lenStr := len(str)
  696. if lenStr > baseLen {
  697. newNumStr := str[0:baseLen]
  698. newNumInt, _ := strconv.Atoi(newNumStr)
  699. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  700. if newNum < num {
  701. newNumInt += 1
  702. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  703. }
  704. } else {
  705. newNum = num
  706. }
  707. } else if num > -1 {
  708. str := strconv.FormatFloat(num, 'f', -1, 64)
  709. str = removeDecimalPoint(str)
  710. lenStr := len(str)
  711. if lenStr > baseLen {
  712. newNumStr := str[0:baseLen]
  713. newNumInt, _ := strconv.Atoi(newNumStr)
  714. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  715. newNum = -newNum
  716. if newNum < num {
  717. newNumInt -= 1
  718. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  719. newNum = -newNum
  720. }
  721. } else {
  722. newNum = num
  723. }
  724. if newNum == -0 {
  725. newNum = 0
  726. }
  727. } else { // 小于等于-1
  728. tmpNumFloat := math.Abs(num)
  729. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  730. str := strconv.Itoa(tmpNum)
  731. lenStr := len(str)
  732. if lenStr > baseLen {
  733. newNumStr := str[0:baseLen]
  734. newNumInt, _ := strconv.Atoi(newNumStr)
  735. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  736. newNum = -newNum
  737. if newNum < num {
  738. newNumInt -= 1
  739. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  740. newNum = -newNum
  741. }
  742. } else {
  743. newNum = float64(-tmpNum)
  744. }
  745. }
  746. return
  747. }
  748. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  749. if num >= 1 {
  750. tmpNum := int(math.Floor(num)) // 向上取整
  751. str := strconv.Itoa(tmpNum)
  752. lenStr := len(str)
  753. if lenStr > baseLen {
  754. newNumStr := str[0:baseLen]
  755. newNumInt, _ := strconv.Atoi(newNumStr)
  756. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  757. if newNum < num {
  758. newNumInt -= 1
  759. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  760. }
  761. } else {
  762. newNum = float64(tmpNum)
  763. }
  764. return
  765. } else if num > 0 {
  766. str := strconv.FormatFloat(num, 'f', -1, 64)
  767. str = removeDecimalPoint(str)
  768. lenStr := len(str)
  769. if lenStr > baseLen {
  770. newNumStr := str[0:baseLen]
  771. newNumInt, _ := strconv.Atoi(newNumStr)
  772. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  773. if newNum > num {
  774. newNumInt -= 1
  775. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  776. }
  777. } else {
  778. newNum = num
  779. }
  780. } else if num > -1 {
  781. str := strconv.FormatFloat(num, 'f', -1, 64)
  782. str = removeDecimalPoint(str)
  783. lenStr := len(str)
  784. if lenStr > baseLen {
  785. newNumStr := str[0:baseLen]
  786. newNumInt, _ := strconv.Atoi(newNumStr)
  787. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  788. newNum = -newNum
  789. if newNum > num {
  790. newNumInt += 1
  791. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  792. newNum = -newNum
  793. }
  794. } else {
  795. newNum = num
  796. }
  797. if newNum == -0 {
  798. newNum = 0
  799. }
  800. } else { // 小于等于-1
  801. tmpNumFloat := math.Abs(num)
  802. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  803. str := strconv.Itoa(tmpNum)
  804. lenStr := len(str)
  805. if lenStr > baseLen {
  806. newNumStr := str[0:baseLen]
  807. newNumInt, _ := strconv.Atoi(newNumStr)
  808. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  809. newNum = -newNum
  810. if newNum > num {
  811. newNumInt += 1
  812. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  813. newNum = -newNum
  814. }
  815. } else {
  816. newNum = float64(-tmpNum)
  817. }
  818. }
  819. return
  820. }
  821. func removeDecimalPoint(str string) string {
  822. str = str[strings.Index(str, ".")+1:]
  823. return str
  824. }
  825. func GetLocalIP() (ip string, err error) {
  826. addrs, err := net.InterfaceAddrs()
  827. if err != nil {
  828. return
  829. }
  830. for _, addr := range addrs {
  831. ipAddr, ok := addr.(*net.IPNet)
  832. if !ok {
  833. continue
  834. }
  835. if ipAddr.IP.IsLoopback() {
  836. continue
  837. }
  838. if !ipAddr.IP.IsGlobalUnicast() {
  839. continue
  840. }
  841. return ipAddr.IP.String(), nil
  842. }
  843. return
  844. }
  845. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  846. startDate = tmpStartDate
  847. endDate = tmpEndDate
  848. switch dateType {
  849. case 1:
  850. startDate = "2000-01-01"
  851. endDate = ""
  852. case 2:
  853. startDate = "2010-01-01"
  854. endDate = ""
  855. case 3:
  856. startDate = "2015-01-01"
  857. endDate = ""
  858. case 4:
  859. startDate = "2021-01-01"
  860. endDate = ""
  861. case 5:
  862. case 6:
  863. endDate = ""
  864. case 7:
  865. startDate = "2018-01-01"
  866. endDate = ""
  867. case 8:
  868. startDate = "2019-01-01"
  869. endDate = ""
  870. case 9:
  871. startDate = "2020-01-01"
  872. endDate = ""
  873. case 11:
  874. startDate = "2022-01-01"
  875. endDate = ""
  876. case DateTypeNYears:
  877. if startYear == 0 { //默认取最近5年
  878. startYear = 5
  879. }
  880. if yearMax == 0 {
  881. return
  882. }
  883. startYear = startYear - 1
  884. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  885. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  886. endDate = ""
  887. }
  888. {
  889. if strings.Count(startDate, "-") == 1 {
  890. startDate = startDate + "-01"
  891. }
  892. if strings.Count(endDate, "-") == 1 {
  893. endDate = endDate + "-01"
  894. }
  895. }
  896. return
  897. }
  898. func GetColorMap() map[int]string {
  899. colorMap := make(map[int]string)
  900. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  901. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  902. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  903. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  904. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  905. for k, v := range colors {
  906. colorMap[k] = v
  907. }
  908. return colorMap
  909. }
  910. func GetDaysDiff1900(date string) int {
  911. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  912. if err != nil {
  913. return 0
  914. }
  915. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  916. if err != nil {
  917. return 0
  918. }
  919. duration := tEnd.Sub(tStart).Hours() / 24
  920. days := int(duration)
  921. return days
  922. }
  923. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  924. funMap := getFormulaMap()
  925. for k, v := range funMap {
  926. formulaStr = strings.Replace(formulaStr, k, v, -1)
  927. }
  928. replaceCount := 0
  929. for tag, val := range valTagMap {
  930. dvStr := fmt.Sprintf("%v", val)
  931. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  932. replaceCount++
  933. }
  934. for k, v := range funMap {
  935. formulaStr = strings.Replace(formulaStr, v, k, -1)
  936. }
  937. return formulaStr
  938. }
  939. func GetFrequencyEn(frequency string) (frequencyEn string) {
  940. switch frequency {
  941. case "日度":
  942. frequencyEn = "day"
  943. return
  944. case "周度":
  945. frequencyEn = "week"
  946. return
  947. case "旬度":
  948. frequencyEn = "ten days"
  949. return
  950. case "月度":
  951. frequencyEn = "month"
  952. return
  953. case "季度":
  954. frequencyEn = "quarter"
  955. return
  956. case "年度":
  957. frequencyEn = "year"
  958. return
  959. }
  960. return
  961. }
  962. func DateConvMysqlConvMongo(dateCon string) string {
  963. cond := ""
  964. switch dateCon {
  965. case "=":
  966. cond = "$eq"
  967. case "<":
  968. cond = "$lt"
  969. case "<=":
  970. cond = "$lte"
  971. case ">":
  972. cond = "$gt"
  973. case ">=":
  974. cond = "$gte"
  975. }
  976. return cond
  977. }
  978. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  979. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  980. remain := len(result) % 8
  981. if remain > 0 {
  982. mod := 8 - remain
  983. for i := 0; i < mod; i++ {
  984. result = append(result, 0)
  985. }
  986. }
  987. origData, err := TripleDesDecrypt(result, []byte(desKey))
  988. if err != nil {
  989. panic(any(err))
  990. }
  991. return origData
  992. }
  993. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  994. block, err := des.NewTripleDESCipher(key)
  995. if err != nil {
  996. return nil, err
  997. }
  998. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  999. origData := make([]byte, len(crypted))
  1000. blockMode.CryptBlocks(origData, crypted)
  1001. origData = PKCS5UnPadding(origData)
  1002. return origData, nil
  1003. }
  1004. func PKCS5UnPadding(origData []byte) []byte {
  1005. length := len(origData)
  1006. unpadding := int(origData[length-1])
  1007. return origData[:(length - unpadding)]
  1008. }
  1009. func TimeTransferString(format string, t time.Time) string {
  1010. str := t.Format(format)
  1011. if t.IsZero() {
  1012. return ""
  1013. }
  1014. return str
  1015. }
  1016. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1017. switch frequency {
  1018. case "本周":
  1019. day := int(currDate.Weekday())
  1020. if day == 0 { // 周日
  1021. day = 7
  1022. }
  1023. num := 0
  1024. switch appointDay {
  1025. case "周一":
  1026. num = 1
  1027. case "周二":
  1028. num = 2
  1029. case "周三":
  1030. num = 3
  1031. case "周四":
  1032. num = 4
  1033. case "周五":
  1034. num = 5
  1035. case "周六":
  1036. num = 6
  1037. case "周日":
  1038. num = 7
  1039. }
  1040. day = num - day
  1041. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1042. case "本旬":
  1043. day := currDate.Day()
  1044. var tmpDate time.Time
  1045. switch appointDay {
  1046. case "第一天":
  1047. if day <= 10 {
  1048. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1049. } else if day <= 20 {
  1050. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1051. } else {
  1052. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1053. }
  1054. case "最后一天":
  1055. if day <= 10 {
  1056. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1057. } else if day <= 20 {
  1058. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1059. } else {
  1060. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1061. }
  1062. }
  1063. date = tmpDate.Format(FormatDate)
  1064. case "本月":
  1065. var tmpDate time.Time
  1066. switch appointDay {
  1067. case "第一天":
  1068. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1069. case "最后一天":
  1070. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1071. }
  1072. date = tmpDate.Format(FormatDate)
  1073. case "本季":
  1074. month := currDate.Month()
  1075. var tmpDate time.Time
  1076. switch appointDay {
  1077. case "第一天":
  1078. if month <= 3 {
  1079. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1080. } else if month <= 6 {
  1081. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1082. } else if month <= 9 {
  1083. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1084. } else {
  1085. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1086. }
  1087. case "最后一天":
  1088. if month <= 3 {
  1089. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1090. } else if month <= 6 {
  1091. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1092. } else if month <= 9 {
  1093. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1094. } else {
  1095. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1096. }
  1097. }
  1098. date = tmpDate.Format(FormatDate)
  1099. case "本半年":
  1100. month := currDate.Month()
  1101. var tmpDate time.Time
  1102. switch appointDay {
  1103. case "第一天":
  1104. if month <= 6 {
  1105. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1106. } else {
  1107. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1108. }
  1109. case "最后一天":
  1110. if month <= 6 {
  1111. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1112. } else {
  1113. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1114. }
  1115. }
  1116. date = tmpDate.Format(FormatDate)
  1117. case "本年":
  1118. var tmpDate time.Time
  1119. switch appointDay {
  1120. case "第一天":
  1121. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1122. case "最后一天":
  1123. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1124. }
  1125. date = tmpDate.Format(FormatDate)
  1126. default:
  1127. errMsg = "错误的日期频度:" + frequency
  1128. err = errors.New(errMsg)
  1129. return
  1130. }
  1131. return
  1132. }
  1133. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1134. switch op {
  1135. case "=":
  1136. return a == b
  1137. case ">":
  1138. return a > b
  1139. case ">=":
  1140. return a >= b
  1141. case "<=":
  1142. return a <= b
  1143. case "<":
  1144. return a < b
  1145. }
  1146. return false
  1147. }
  1148. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1149. formatStr = originalString
  1150. if !strings.Contains(originalString, "T") {
  1151. return
  1152. }
  1153. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1154. if err != nil {
  1155. fmt.Println("Error parsing time:", err)
  1156. return
  1157. }
  1158. formatStr = t.Format(FormatDateTime)
  1159. return
  1160. }
  1161. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1162. formatStr = originalString
  1163. if !strings.Contains(originalString, "T") {
  1164. return
  1165. }
  1166. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1167. if err != nil {
  1168. fmt.Println("Error parsing time:", err)
  1169. return
  1170. }
  1171. formatStr = t.Format(FormatDate)
  1172. return
  1173. }
  1174. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1175. numDecimal, _ := decimal.NewFromString(num)
  1176. if hasPercent {
  1177. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1178. }
  1179. numFloat, _ := numDecimal.Round(int32(decimalPlaces)).Float64()
  1180. numStr := strconv.FormatFloat(numFloat, 'f', decimalPlaces, 64)
  1181. if hasPercent {
  1182. numStr += "%"
  1183. }
  1184. return numStr
  1185. }