gpr_risk.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "eta/eta_crawler/services/alarm_msg"
  6. "eta/eta_crawler/utils"
  7. "fmt"
  8. "github.com/xuri/excelize/v2"
  9. "io"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "strconv"
  14. "time"
  15. )
  16. // GprRiskIndex 美国农业部指标数据
  17. type GprRiskIndex struct {
  18. ClassifyName string `description:"指标目录"`
  19. ParentClassifyName string `description:"父级指标目录"`
  20. ClassifySort int `description:"指标目录排序号"`
  21. IndexName string `description:"指标名称"`
  22. IndexCode string `description:"指标编码"`
  23. Unit string `description:"单位"`
  24. Sort int `description:"排序号"`
  25. Frequency string `description:"频度"`
  26. TerminalCode string `description:"编码"`
  27. ExcelDataMap map[string]string
  28. }
  29. func DownloadGprRiskFile() (err error) {
  30. defer func() {
  31. if err != nil {
  32. msg := "失败提醒" + "DownloadGprRiskFile ErrMsg:" + err.Error()
  33. fmt.Println("msg:", msg)
  34. utils.FileLog.Info(msg)
  35. go alarm_msg.SendAlarmMsg(msg, 3)
  36. }
  37. }()
  38. url := "https://www.matteoiacoviello.com/gpr_files/data_gpr_daily_recent.xls"
  39. destDir := "static"
  40. fileName := fmt.Sprintf("data_gpr_daily_recent_%s.xls", time.Now().Format(utils.FormatDateTimeUnSpace))
  41. //fileName := filepath.Base(url)
  42. destPath := filepath.Join(destDir, fileName)
  43. fmt.Println(destPath)
  44. //创建文件
  45. out, err := os.Create(destPath)
  46. if err != nil {
  47. err = fmt.Errorf("failed to create file: %w", err)
  48. return
  49. }
  50. defer out.Close()
  51. // 发起下载请求
  52. fmt.Println(time.Now().Format(utils.FormatDateTime), "开始下载 GPR地缘风险指数 文件")
  53. resp, err := http.Get(url)
  54. if err != nil {
  55. err = fmt.Errorf("failed to make request: %w", err)
  56. return
  57. }
  58. defer resp.Body.Close()
  59. // 检查HTTP状态码
  60. if resp.StatusCode != http.StatusOK {
  61. err = fmt.Errorf("bad status: %s", resp.Status)
  62. return
  63. }
  64. fmt.Println(time.Now().Format(utils.FormatDateTime), "下载 GPR地缘风险指数 文件完成")
  65. fmt.Println(time.Now().Format(utils.FormatDateTime), "开始写入文件")
  66. // 将内容写入文件
  67. buf := make([]byte, 4*1024*1024) // 4MB buffer
  68. _, err = io.CopyBuffer(out, resp.Body, buf)
  69. if err != nil {
  70. err = fmt.Errorf("failed to copy content: %w", err)
  71. return
  72. }
  73. fmt.Println(time.Now().Format(utils.FormatDateTime), "开始转换文件格式")
  74. // 转换文件格式
  75. downloadFileXlsx := destPath + "x"
  76. err = ConvertXlsToXlsx(destPath, downloadFileXlsx)
  77. if err != nil {
  78. err = fmt.Errorf("文件格式转换失败 convert excel, Err:%w", err)
  79. return
  80. }
  81. fmt.Println(time.Now().Format(utils.FormatDateTime), "文件格式转换完成")
  82. // 使用通道等待解析完成
  83. done := make(chan error)
  84. go func() {
  85. done <- ParseGprRiskExcel(downloadFileXlsx)
  86. }()
  87. // 等待解析完成或超时
  88. select {
  89. case err = <-done:
  90. if err != nil {
  91. err = fmt.Errorf("parse excel, Err:%w", err)
  92. return
  93. }
  94. }
  95. // 删除临时文件
  96. defer func() {
  97. os.Remove(destPath)
  98. }()
  99. fmt.Printf(" GPR地缘风险指数 File downloaded successfully: %s\n", destPath)
  100. return
  101. }
  102. func DownloadGPRRiskTask(cont context.Context) (err error) {
  103. err = DownloadGprRiskFile()
  104. return
  105. }
  106. func ParseGprRiskExcel(path string) (err error) {
  107. defer func() {
  108. if err != nil {
  109. msg := "失败提醒" + "ParseGprRiskExcel ErrMsg:" + err.Error()
  110. fmt.Println("msg:", msg)
  111. utils.FileLog.Info(msg)
  112. go alarm_msg.SendAlarmMsg(msg, 3)
  113. }
  114. }()
  115. //var xlFile *xlsx.File
  116. exist, err := PathExists(path)
  117. if err != nil {
  118. fmt.Println(err)
  119. err = fmt.Errorf("文件地址不存在 err:%s", err.Error())
  120. return
  121. }
  122. if !exist {
  123. err = fmt.Errorf("文件地址不存在")
  124. return
  125. }
  126. //xlFile, err = xlsx.OpenFile(path)
  127. xlFile, err := excelize.OpenFile(path)
  128. if err != nil {
  129. fmt.Println("OpenFile err:", err)
  130. err = fmt.Errorf("打开文件失败 err:%s", err.Error())
  131. return
  132. }
  133. defer func() {
  134. // 关闭工作簿
  135. if err = xlFile.Close(); err != nil {
  136. fmt.Println(err)
  137. }
  138. os.Remove(path)
  139. }()
  140. sheetName := xlFile.GetSheetName(0)
  141. fmt.Println("Sheet Name:", sheetName)
  142. //解析出表头第7行
  143. //拼接指标名称
  144. // 指标名称
  145. indexMap := make(map[string]*GprRiskIndex)
  146. indexList := make([]*GprRiskIndex, 0)
  147. sort := 0
  148. rows, err := xlFile.GetRows(sheetName)
  149. dataK := 0
  150. unit := "无"
  151. indexName := "GPR地缘风险指数"
  152. inCode := "gprdyfxzs"
  153. classifyName := "GPR地缘风险指数"
  154. //for _, sheet := range xlFile.Sheets {
  155. //遍历行读取
  156. for i, row := range rows {
  157. if i == 0 {
  158. for k, text := range row {
  159. if text == "GPRD" {
  160. dataK = k
  161. break
  162. }
  163. }
  164. } else {
  165. dateStr := ""
  166. for k, text := range row {
  167. if k == 0 {
  168. dateT, e := time.ParseInLocation("20060102", text, time.Local)
  169. if e != nil {
  170. utils.FileLog.Info("日期格式转换失败 err:%s", err.Error())
  171. continue
  172. }
  173. dateStr = dateT.Format(utils.FormatDate)
  174. } else if k == dataK {
  175. date := dateStr
  176. dataVal := text
  177. indexItem, okIndex := indexMap[indexName]
  178. if !okIndex {
  179. // 新增指标
  180. indexItem = new(GprRiskIndex)
  181. indexItem.IndexName = indexName
  182. indexItem.ClassifyName = classifyName
  183. indexItem.ParentClassifyName = ""
  184. indexItem.ClassifySort = 0
  185. indexItem.IndexCode = inCode
  186. indexItem.Frequency = "日度"
  187. indexItem.Sort = sort
  188. indexItem.Unit = unit
  189. indexItem.ExcelDataMap = make(map[string]string)
  190. sort++
  191. }
  192. val, e := strconv.ParseFloat(dataVal, 64)
  193. if e != nil {
  194. utils.FileLog.Info("数据转换失败 err:%s", e.Error())
  195. continue
  196. }
  197. indexItem.ExcelDataMap[date] = fmt.Sprintf("%.2f", utils.FloatFormatRound(val, 2))
  198. indexMap[indexName] = indexItem
  199. }
  200. }
  201. }
  202. }
  203. //}
  204. for _, v := range indexMap {
  205. //fmt.Printf("IndexName: %s \n", v.IndexName)
  206. //fmt.Printf("IndexCode: %s \n", v.IndexCode)
  207. indexList = append(indexList, v)
  208. if len(indexList) > 100 {
  209. err = addGprRiskData(indexList)
  210. if err != nil {
  211. return
  212. }
  213. indexList = []*GprRiskIndex{}
  214. }
  215. }
  216. if len(indexList) > 0 {
  217. err = addGprRiskData(indexList)
  218. if err != nil {
  219. return
  220. }
  221. }
  222. fmt.Println("GPR地缘风险指数 执行成功")
  223. return
  224. }
  225. func addGprRiskData(indexList []*GprRiskIndex) (err error) {
  226. sheetName := "GPR地缘风险指数"
  227. if len(indexList) > 0 {
  228. params := make(map[string]interface{})
  229. params["List"] = indexList
  230. params["TerminalCode"] = ""
  231. result, e := utils.PostEdbLib(params, "gpr_risk/handle/excel_data")
  232. if e != nil {
  233. err = fmt.Errorf("sheet :%s PostEdbLib err: %s", sheetName, e.Error())
  234. b, _ := json.Marshal(params)
  235. utils.FileLog.Info(fmt.Sprintf("sheet :%s PostEdbLib err: %s, params: %s", sheetName, e.Error(), string(b)))
  236. return
  237. }
  238. resp := new(utils.BaseEdbLibResponse)
  239. if e := json.Unmarshal(result, &resp); e != nil {
  240. err = fmt.Errorf("sheet :%s json.Unmarshal err: %s", sheetName, e)
  241. utils.FileLog.Info(fmt.Sprintf("sheet :%s json.Unmarshal err: %s", sheetName, e))
  242. return
  243. }
  244. if resp.Ret != 200 {
  245. err = fmt.Errorf("sheet :%s Msg: %s, ErrMsg: %s", sheetName, resp.Msg, resp.ErrMsg)
  246. utils.FileLog.Info(fmt.Sprintf("sheet :%s Msg: %s, ErrMsg: %s", sheetName, resp.Msg, resp.ErrMsg))
  247. return
  248. }
  249. }
  250. return
  251. }