wxwork.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "fmt"
  6. "github.com/faabiosr/cachego/file"
  7. "github.com/fastwego/dingding"
  8. "github.com/robfig/cron/v3"
  9. "html/template"
  10. "io/ioutil"
  11. "log"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/fastwego/offiaccount"
  19. template1 "github.com/fastwego/offiaccount/apis/message/template"
  20. "github.com/fastwego/offiaccount/apis/oauth"
  21. user1 "github.com/fastwego/offiaccount/apis/user"
  22. "github.com/fastwego/offiaccount/type/type_message"
  23. "github.com/fastwego/offiaccount/util"
  24. "github.com/fastwego/wxwork/corporation"
  25. "github.com/fastwego/wxwork/corporation/apis/external_contact/customer"
  26. message1 "github.com/fastwego/wxwork/corporation/apis/message"
  27. "github.com/gin-gonic/gin"
  28. "kpt.xdmy/apiserver/routers/restful"
  29. "kpt.xdmy/pkg/logging"
  30. "kpt.xdmy/pkg/setting"
  31. )
  32. //企业微信
  33. var OffiAccount *offiaccount.OffiAccount
  34. var Corp *corporation.Corporation
  35. var App *corporation.App
  36. var MsgChan chan []map[string]string
  37. type UserMsg struct {
  38. Touser string `json:"touser"`
  39. Msgtype string `json:"msgtype"`
  40. Agentid string `json:"agentid"`
  41. Text interface{} `json:"text"`
  42. }
  43. func CronWXwork() {
  44. defer func() { // 必须要先声明defer
  45. if err := recover(); err != nil {
  46. fmt.Printf("CronTest pnic err%+v \n", err)
  47. logging.Error("panic recover err ", err)
  48. }
  49. }()
  50. //initWXwork()
  51. initDingDing()
  52. go SendRun()
  53. log.Println("Starting CronWXwork...")
  54. c := cron.New()
  55. _, err := c.AddFunc("00 00 06 * * *", Getuseinfor) //* * * * *, 从分钟开始
  56. if err != nil {
  57. println("cron4 err", err.Error())
  58. }
  59. GetMsg()
  60. _, err = c.AddFunc("@every 2m0s", GetMsg) //* * * * *, 从分钟开始
  61. _, err = c.AddFunc("00 00 07 * * *", GetPartsInfo) //* * * * *, 每天七点
  62. cronMaintainPush()
  63. c.AddFunc("@every 2m0s", cronMaintainPush)
  64. if err != nil {
  65. println("cron5 err", err.Error())
  66. }
  67. c.Start()
  68. }
  69. func Ceshi() {
  70. fmt.Println("sasdsdadasa")
  71. }
  72. func GetPartsInfo() {
  73. tx, err1 := restful.Dbs.Beginx()
  74. defer func() {
  75. switch {
  76. case err1 != nil:
  77. println("tx.Begin 事务启动失败__error:", err1.Error())
  78. if tx != nil {
  79. tx.Rollback()
  80. }
  81. default:
  82. if tx != nil {
  83. err1 = tx.Commit()
  84. }
  85. }
  86. }()
  87. query, err := restful.MapStrListTx(tx, "select count(*) success,(select count(*) from parts ps "+
  88. " where ps.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and ps.issync=0 ) woring "+
  89. " from parts where parts.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and parts.issync=1 ")
  90. query1, err := restful.MapStrListTx(tx, " select empid from user where id in(select user_id from user_role "+
  91. "where role_id in (select id from role where easInformationReception = 1))")
  92. if err != nil {
  93. logging.Error("获取备件同步成功与否__error:", err.Error())
  94. } else {
  95. if len(query1) > 0 && len(query) > 0 {
  96. for i := 0; i < len(query1); i++ {
  97. success := query[0]["success"]
  98. personId := query1[i]["empid"]
  99. woring := query[0]["woring"]
  100. _, err = tx.Exec("INSERT INTO wxworkmsg(date,userid,msg,formcode,type,note) VALUES(?,?,?,?,?,?)",
  101. time.Now().Format("2006-01-02"), personId, "【eas】同步成功"+success+"条"+"同步失败"+woring+"条",
  102. "eas", 0, nil)
  103. if err != nil {
  104. }
  105. }
  106. }
  107. if err != nil {
  108. logging.Error("插入eas同步信息到微信信息表__error:", err.Error())
  109. }
  110. }
  111. }
  112. func Getuseinfor1() {
  113. logging.Error("PostDataByNames========= ")
  114. }
  115. func Getuseinfor() {
  116. defer func() { // 必须要先声明defer
  117. if err := recover(); err != nil {
  118. logging.Error("Getuseinfor pnic err", err) // 这里的err其实就是panic传入的内容,55
  119. }
  120. }()
  121. value := make(url.Values, 1)
  122. value.Add("department_id", "1")
  123. value.Add("fetch_child", "1")
  124. msgmap := make(map[string]interface{})
  125. resp, err := customer.List(App, value)
  126. if err != nil {
  127. println("contact.UserList err", err.Error())
  128. }
  129. err = json.Unmarshal(resp, &msgmap)
  130. if err != nil {
  131. println("json.Unmarshal err", err.Error())
  132. }
  133. tx, err1 := restful.Dbs.Beginx()
  134. defer func() {
  135. switch {
  136. case err1 != nil:
  137. logging.Error("tx.Begin 事务启动失败__error:", err.Error())
  138. if tx != nil {
  139. tx.Rollback()
  140. }
  141. default:
  142. if tx != nil {
  143. err = tx.Commit()
  144. }
  145. }
  146. }()
  147. if _, ok := msgmap["userlist"]; ok {
  148. for _, value := range msgmap["userlist"].([]interface{}) {
  149. userid := value.(map[string]interface{})["userid"]
  150. name := value.(map[string]interface{})["name"]
  151. var department interface{}
  152. if len(value.(map[string]interface{})["department"].([]interface{})) > 0 {
  153. department = value.(map[string]interface{})["department"].([]interface{})[0]
  154. }
  155. var empcode interface{}
  156. if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) == 1 {
  157. empcode = value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})[0].(map[string]interface{})["value"]
  158. } else if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) > 1 {
  159. for _, va := range value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{}) {
  160. if va.(map[string]interface{})["name"] == "工号" {
  161. empcode = va.(map[string]interface{})["value"]
  162. break
  163. }
  164. }
  165. }
  166. //jvalue,_ :=json.Marshal(value)
  167. _, err = tx.Exec("insert into wxworkuser(userid,name,department,empcode)values(?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?,department=?", userid, name, department, empcode, empcode, department)
  168. //_,err =tx.Exec("insert into wxworkuser(userid,name,department,empcode,json)values(?,?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?",userid,name,department,empcode,string(jvalue),empcode)
  169. if err != nil {
  170. logging.Error("insert into wxworkuser err ", err.Error())
  171. }
  172. }
  173. }
  174. logging.Info("update wxworkuser success ")
  175. }
  176. func SendRun() {
  177. defer func() {
  178. if err := recover(); err != nil {
  179. logging.Error("GetMsg pnic err", err)
  180. }
  181. }()
  182. for {
  183. msgs := <-MsgChan
  184. println(len(msgs))
  185. for _, value := range msgs {
  186. /*
  187. content := make(map[string]interface{})
  188. content["content"] = value["msg"]
  189. msg := UserMsg{
  190. Touser: value["userid"],
  191. Agentid: setting.ServerSetting.WXworkAgentid,
  192. Text: content,
  193. Msgtype: "text",
  194. }
  195. msgbyte, err := json.Marshal(msg)
  196. if err != nil {
  197. logging.Error("json.Marshal err ", err.Error())
  198. }
  199. _, err = message1.Send(App, msgbyte)
  200. if err != nil {
  201. logging.Error("message1.Send err ", err.Error())
  202. fmt.Println("message1.Send err", err.Error())
  203. } else {
  204. }
  205. */
  206. ///*
  207. if value["dingdingCode"] == "" {
  208. //restful.MapStr(` select`)
  209. params := url.Values{}
  210. params.Add("mobile", value["tel"])
  211. //params.Add("mobile", "18317742428")
  212. req, _ := http.NewRequest(http.MethodGet, "/user/get_by_mobile?"+params.Encode(), nil)
  213. resp, err := DingClient.Do(req)
  214. if err != nil {
  215. continue
  216. }
  217. fmt.Println(value["111"], value["userid"], value["empId"])
  218. dingTalkUser := new(dingTalkUserId)
  219. json.Unmarshal(resp, dingTalkUser)
  220. _, err = restful.Dbs.Exec(` update emp set dingdingCode = ? where (tel = ? ) `, dingTalkUser.Userid, value["tel"])
  221. if err != nil {
  222. continue
  223. }
  224. value["dingdingCode"] = dingTalkUser.Userid
  225. }
  226. //306804033029907132
  227. //306804033029907132
  228. // 调用 api
  229. if value["dingdingCode"] == "" {
  230. continue
  231. }
  232. dingTalkSendReq := new(DingTalkSendReq)
  233. dingTalkSendReq.AgentId = setting.ServerSetting.DingTalkAgentid
  234. dingTalkSendReq.UseridList = value["dingdingCode"]
  235. dingTalkSendReq.Msg.Msgtype = "text"
  236. dingTalkSendReq.Msg.Text.Content = value["msg"]
  237. dingTalkSendReqByte, _ := json.Marshal(dingTalkSendReq)
  238. sendReq, _ := http.NewRequest(http.MethodPost, "/topapi/message/corpconversation/asyncsend_v2", bytes.NewBuffer(dingTalkSendReqByte))
  239. sendResp, err := DingClient.Do(sendReq)
  240. if err != nil {
  241. continue
  242. }
  243. fmt.Println(string(sendResp))
  244. //*/
  245. }
  246. }
  247. }
  248. func GetMsgv1() {
  249. go GetMsgv2()
  250. }
  251. func GetMsgv2() {
  252. defer func() { // 必须要先声明defer
  253. if err := recover(); err != nil {
  254. logging.Error("GetMsg pnic err", err) // 这里的err其实就是panic传入的内容,55
  255. }
  256. }()
  257. time.Sleep(time.Second)
  258. a := 0
  259. b := 1 / a
  260. println(b)
  261. }
  262. func GetMsg() {
  263. defer func() { // 必须要先声明defer
  264. if err := recover(); err != nil {
  265. logging.Error("GetMsg pnic err", err) // 这里的err其实就是panic传入的内容,55
  266. }
  267. }()
  268. tx, err1 := restful.Dbs.Beginx()
  269. defer func() {
  270. switch {
  271. case err1 != nil:
  272. println("tx.Begin 事务启动失败__error:", err1.Error())
  273. if tx != nil {
  274. tx.Rollback()
  275. }
  276. default:
  277. if tx != nil {
  278. err1 = tx.Commit()
  279. }
  280. }
  281. }()
  282. sqls, err := restful.MapStrListTx(tx, "select sqlstr from apisql where sqlname in ('getWXworkMsg','updateWXworkMsg') order by sqlname")
  283. if err != nil {
  284. logging.Error("select from sqls err ", err.Error())
  285. }
  286. if len(sqls) < 2 {
  287. return
  288. }
  289. sqlmsg := sqls[0]["sqlstr"]
  290. sqlupdate := sqls[1]["sqlstr"]
  291. var query []map[string]string
  292. if len(sqls) > 0 {
  293. query, err = restful.MapStrListTx(tx, sqlmsg)
  294. if err != nil {
  295. logging.Error("select from wxworkmsg err ", err.Error(), len(query))
  296. } else {
  297. _, err = tx.Exec(sqlupdate)
  298. if err != nil {
  299. logging.Error("update wxworkmsg err ", err.Error(), len(query))
  300. }
  301. }
  302. }
  303. if len(query) > 0 {
  304. go func() {
  305. msgs := query
  306. MsgChan <- msgs
  307. }()
  308. }
  309. }
  310. func SendMsgtest() {
  311. message1.Send(App, []byte(`{
  312. "touser": "18322596935",
  313. "toparty": "PartyID1|PartyID2",
  314. "totag": "TagID1 | TagID2",
  315. "msgtype": "text",
  316. "agentid": 1000022,
  317. "text": {
  318. "content": "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
  319. },
  320. "safe": 0,
  321. "enable_id_trans": 0,
  322. "enable_duplicate_check": 0
  323. }`))
  324. }
  325. func initOffiAccount() {
  326. // 加载配置文件
  327. // 创建公众号实例
  328. OffiAccount = offiaccount.New(offiaccount.Config{
  329. // wxe1cc563ba393dd1a
  330. Appid: "wxe1cc563ba393dd1a",
  331. Secret: "25e56243da9581eab6f4d67a12ef4658",
  332. Token: "123",
  333. // 6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f
  334. EncodingAESKey: "6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f",
  335. })
  336. //payload := []byte(`
  337. //{
  338. // "button":[
  339. // {
  340. // "name":"菜单",
  341. // "sub_button":[
  342. // {
  343. // "type":"view",
  344. // "name":"搜索",
  345. // "url":"http://www.baidu.com/"
  346. // }]
  347. // }]
  348. //}`)
  349. //resp, err := menu.Create(OffiAccount, payload)
  350. //fmt.Println(resp, err)
  351. //guide.SetGuideConfig(OffiAccount,[]byte("欢迎关注"))
  352. }
  353. func initWXwork() {
  354. // 加载配置文件
  355. // 创建企业微信实例
  356. Corp = corporation.New(corporation.Config{Corpid: setting.ServerSetting.WXworkCorpid})
  357. App = Corp.NewApp(corporation.AppConfig{
  358. AgentId: setting.ServerSetting.WXworkAgentid,
  359. Secret: setting.ServerSetting.WXworkSecret,
  360. Token: "",
  361. EncodingAESKey: "",
  362. })
  363. MsgChan = make(chan []map[string]string, 100)
  364. }
  365. func initDingDing() {
  366. atm := &dingding.DefaultAccessTokenManager{
  367. Id: setting.ServerSetting.DingTalkAppKey,
  368. Name: "access_token",
  369. GetRefreshRequestFunc: func() *http.Request {
  370. params := url.Values{}
  371. params.Add("appkey", setting.ServerSetting.DingTalkAppKey)
  372. params.Add("appsecret", setting.ServerSetting.DingTalkAppSecret)
  373. req, _ := http.NewRequest(http.MethodGet, dingding.ServerUrl+"/gettoken?"+params.Encode(), nil)
  374. return req
  375. },
  376. Cache: file.New(os.TempDir()),
  377. }
  378. // 钉钉 客户端
  379. DingClient = dingding.NewClient(atm)
  380. MsgChan = make(chan []map[string]string, 100)
  381. }
  382. func InitRouter() *gin.Engine {
  383. r := gin.New()
  384. // ginpprof.Wrap(r)
  385. r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  386. // 你的自定义格式
  387. return fmt.Sprintf(" %+v \n",
  388. param.Keys,
  389. )
  390. }))
  391. r.Use(gin.Logger()) // 日志
  392. //r.Use(Cors()) // 跨域请求rolemenus
  393. r.Use(gin.Recovery())
  394. r.GET("/", func(c *gin.Context) {
  395. //OffiAccount.Server.EchoStr(c.Writer, c.Request)
  396. config, err := jsapiConfig(c)
  397. if err != nil {
  398. fmt.Println("==========1", err)
  399. return
  400. }
  401. t1, err := template.ParseFiles("index.html")
  402. if err != nil {
  403. fmt.Println("==========2", err)
  404. return
  405. }
  406. println("===========", t1.Name())
  407. t1.Execute(c.Writer, config)
  408. })
  409. r.POST("/", HandleMessage)
  410. return r
  411. }
  412. func jsapiConfig(c *gin.Context) (config template.JS, err error) {
  413. // 优先从环缓存获取
  414. jsapi_ticket, err := OffiAccount.AccessToken.Cache.Fetch("jsapi_ticket:" + OffiAccount.Config.Appid)
  415. if len(jsapi_ticket) == 0 {
  416. var ttl int64
  417. jsapi_ticket, ttl, err = oauth.GetJSApiTicket(OffiAccount)
  418. if err != nil {
  419. return
  420. }
  421. err = OffiAccount.AccessToken.Cache.Save("jsapi_ticket:"+OffiAccount.Config.Appid, jsapi_ticket, time.Duration(ttl)*time.Second)
  422. if err != nil {
  423. return
  424. }
  425. }
  426. nonceStr := util.GetRandString(6)
  427. timestamp := strconv.FormatInt(time.Now().Unix(), 10)
  428. pageUrl := "http://" + c.Request.Host + c.Request.RequestURI
  429. plain := "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + pageUrl
  430. signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain)))
  431. fmt.Println(plain, signature)
  432. configMap := map[string]string{
  433. "url": pageUrl,
  434. "nonceStr": nonceStr,
  435. "appid": OffiAccount.Config.Appid,
  436. "timestamp": timestamp,
  437. "signature": signature,
  438. }
  439. marshal, err := json.Marshal(configMap)
  440. if err != nil {
  441. return
  442. }
  443. return template.JS(marshal), nil
  444. }
  445. func HandleMessage(c *gin.Context) {
  446. // 区分不同账号
  447. //account := path.Base(c.Request.URL.Path)
  448. // 调用相应公众号服务
  449. body, _ := ioutil.ReadAll(c.Request.Body)
  450. log.Println(string(body))
  451. message, err := OffiAccount.Server.ParseXML(body)
  452. if err != nil {
  453. log.Println(err)
  454. }
  455. var output interface{}
  456. switch message.(type) {
  457. case type_message.MessageText: // 文本 消息
  458. msg := message.(type_message.MessageText)
  459. // 回复文本消息
  460. output = type_message.ReplyMessageText{
  461. ReplyMessage: type_message.ReplyMessage{
  462. ToUserName: type_message.CDATA(msg.FromUserName),
  463. FromUserName: type_message.CDATA(msg.ToUserName),
  464. CreateTime: strconv.FormatInt(time.Now().Unix(), 10),
  465. MsgType: type_message.ReplyMsgTypeText,
  466. },
  467. Content: type_message.CDATA(msg.Content),
  468. }
  469. resp, err := template1.Send(OffiAccount, []byte(`
  470. {
  471. "touser":"`+msg.FromUserName+`",
  472. "template_id":"BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
  473. "data":{
  474. "first": {
  475. "value":"恭喜你购买成功!",
  476. "color":"#173177"
  477. },
  478. "keyword1":{
  479. "value":"巧克力",
  480. "color":"#173177"
  481. },
  482. "keyword2": {
  483. "value":"39.8元",
  484. "color":"#173177"
  485. },
  486. "keyword3": {
  487. "value":"2014年9月22日",
  488. "color":"#173177"
  489. },
  490. "remark":{
  491. "value":"欢迎再次购买!",
  492. "color":"#173177"
  493. }
  494. }
  495. }`))
  496. println("msg", resp, err, msg.FromUserName)
  497. }
  498. res, _ := user1.Get(OffiAccount, nil)
  499. println("res======", string(res))
  500. OffiAccount.Server.Response(c.Writer, c.Request, output)
  501. }
  502. func cronMaintainPush() {
  503. tx, err := restful.Dbs.Beginx()
  504. defer func() {
  505. switch {
  506. case err != nil:
  507. println("tx.Begin 事务启动失败__error:", err.Error())
  508. if tx != nil {
  509. tx.Rollback()
  510. }
  511. default:
  512. if tx != nil {
  513. err = tx.Commit()
  514. }
  515. }
  516. }()
  517. maintainList, err := restful.MapStrList("select m.id,m.repairCode,m.eqId,DATE_FORMAT(m.requestTime,'%Y-%m-%d %H:%i:%S') requestTime,e.purpose,e.eqCode,m.pickId,m.details,(select empname from emp where id = m.requesterId) as requestername " +
  518. "from maintain m join equipment e on e.id = m.eqid where m.stopTime is null and DATE_FORMAT(m.requestTime,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d') ")
  519. if err != nil {
  520. log.Println(err)
  521. return
  522. }
  523. eqIdList := []string{}
  524. for _, main := range maintainList {
  525. fmt.Println(main["requestTime"])
  526. eqIdList = append(eqIdList, main["eqId"])
  527. }
  528. if len(eqIdList) == 0 {
  529. return
  530. }
  531. equipmentList, err := restful.MapStrList(fmt.Sprintf(" select levelone,leveltwo,levelthree,id, maintenance,(select empcode from emp where e.maintenance= id ) maintenancecode,"+
  532. "levelone, (select userid from wxworkuser where empCode = (select empcode from emp where e.levelone= id )) levelonecode,"+
  533. "(select userid from wxworkuser where empCode = (select empcode from emp where e.leveltwo= id )) leveltwocode,"+
  534. "levelthree ,(select userid from wxworkuser where empCode = (select empcode from emp where e.levelthree= id )) levelthreecode,"+
  535. " ifnull(leveloneTime,0) leveloneTime,ifnull(leveltwoTime,0) leveltwoTime,ifnull(levelthreeTime,0) levelthreeTime ,(select tel from emp where id = e.levelone ) onetel,(select tel from emp where id = e.leveltwo ) twotel,(select tel from emp where id = e.levelthree ) threetel,(select dingdingCode from emp where id = e.levelone ) onedingdingCode,(select dingdingCode from emp where id = e.leveltwo ) twodingdingCode,(select dingdingCode from emp where id = e.levelthree ) threedingdingCode from equipment e where e.id in(%s) ", strings.Join(eqIdList, ",")))
  536. if err != nil {
  537. log.Println(err)
  538. return
  539. }
  540. maintainpushList, err := restful.MapStrList("select id,maintainId,eqId,level,usercode,DATE_FORMAT(pushTime,'%Y-%m-%d %H:%i:%S') pushTime " +
  541. "from maintainpush where DATE_FORMAT(pushTime,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d') order by pushTime desc ")
  542. if err != nil {
  543. log.Println(err)
  544. return
  545. }
  546. for _, main := range maintainList {
  547. var levelonecode, leveltwocode, levelthreecode, levelone, leveltwo, levelthree, onetel, twotel, threetel, onedingdingCode, twodingdingCode, threedingdingCode string
  548. var leveloneTime, leveltwoTime, levelthreeTime int
  549. requestTime, err := time.ParseInLocation("2006-01-02 15:04:05", main["requestTime"], time.Local)
  550. if err != nil {
  551. log.Println(err)
  552. return
  553. }
  554. for _, eq := range equipmentList {
  555. if eq["id"] == main["eqId"] {
  556. //maintenancecode = main["pickId"]
  557. levelonecode = eq["levelonecode"]
  558. leveltwocode = eq["leveltwocode"]
  559. levelthreecode = eq["levelthreecode"]
  560. leveloneTime, _ = strconv.Atoi(eq["leveloneTime"])
  561. leveltwoTime, _ = strconv.Atoi(eq["leveltwoTime"])
  562. levelthreeTime, _ = strconv.Atoi(eq["levelthreeTime"])
  563. levelone = eq["levelone"]
  564. leveltwo = eq["leveltwo"]
  565. levelthree = eq["levelthree"]
  566. onetel = eq["onetel"]
  567. twotel = eq["twotel"]
  568. threetel = eq["threetel"]
  569. onedingdingCode = eq["onedingdingCode"]
  570. twodingdingCode = eq["twodingdingCode"]
  571. threedingdingCode = eq["threedingdingCode"]
  572. //push, _ = strconv.ParseInt(eq["pushTime"], 10, 64)
  573. break
  574. }
  575. }
  576. if leveloneTime == 0 || leveltwoTime == 0 || levelthreeTime == 0 {
  577. continue
  578. }
  579. var onePushTime, twoPushTime, threePushTime string
  580. for _, maintainpush := range maintainpushList {
  581. if maintainpush["eqId"] == main["eqId"] && maintainpush["maintainId"] == main["id"] {
  582. mainLevel, _ := strconv.ParseInt(maintainpush["level"], 10, 64)
  583. if mainLevel == 1 && onePushTime == "" {
  584. onePushTime = maintainpush["pushTime"]
  585. } else if mainLevel == 2 && twoPushTime == "" {
  586. twoPushTime = maintainpush["pushTime"]
  587. } else if mainLevel == 3 && threePushTime == "" {
  588. threePushTime = maintainpush["pushTime"]
  589. }
  590. }
  591. }
  592. pushData := make([]map[string]string, 0)
  593. empList, err := restful.MapStrList(` select empname from emp where FIND_IN_SET(id,?) `, main["pickId"])
  594. if err != nil {
  595. log.Println(err)
  596. return
  597. }
  598. var empName []string
  599. for _, emp := range empList {
  600. empName = append(empName, emp["empname"])
  601. }
  602. if onePushTime != "" {
  603. lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", onePushTime, time.Local)
  604. if err != nil {
  605. log.Println(err)
  606. return
  607. }
  608. minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
  609. if minute >= int64((leveloneTime * 60)) {
  610. pushData = append(pushData, map[string]string{"userid": levelonecode, "empId": levelone, "tel": onetel, "dingdingCode": onedingdingCode,
  611. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备主管督办提醒,请至设备管理平台操作(若已处理请忽略)",
  612. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  613. tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 1, levelonecode, main["id"])
  614. }
  615. } else {
  616. minute := (time.Now().Unix() - requestTime.Unix()) / 60
  617. if minute >= int64((leveloneTime * 60)) {
  618. pushData = append(pushData, map[string]string{"userid": levelonecode, "empId": levelone, "tel": onetel, "dingdingCode": onedingdingCode,
  619. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备主管督办提醒,请至设备管理平台操作(若已处理请忽略)",
  620. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  621. _, err := tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 1, levelonecode, main["id"])
  622. fmt.Println(err)
  623. }
  624. }
  625. if twoPushTime != "" {
  626. lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", twoPushTime, time.Local)
  627. if err != nil {
  628. log.Println(err)
  629. return
  630. }
  631. minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
  632. if minute >= int64((leveltwoTime * 60)) {
  633. pushData = append(pushData, map[string]string{"userid": leveltwocode, "empId": leveltwo, "tel": twotel, "dingdingCode": twodingdingCode,
  634. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备助理督办提醒,请至设备管理平台操作(若已处理请忽略)",
  635. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  636. tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 2, leveltwocode, main["id"])
  637. }
  638. } else {
  639. minute := (time.Now().Unix() - requestTime.Unix()) / 60
  640. if minute >= int64((leveltwoTime * 60)) {
  641. pushData = append(pushData, map[string]string{"userid": leveltwocode, "empId": leveltwo, "tel": twotel, "dingdingCode": twodingdingCode,
  642. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备助理督办提醒,请至设备管理平台操作(若已处理请忽略)",
  643. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  644. tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 2, leveltwocode, main["id"])
  645. }
  646. }
  647. if threePushTime != "" {
  648. lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", threePushTime, time.Local)
  649. if err != nil {
  650. log.Println(err)
  651. return
  652. }
  653. minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
  654. if minute >= int64((levelthreeTime * 60)) {
  655. pushData = append(pushData, map[string]string{"userid": levelthreecode, "empId": levelthree, "tel": threetel, "dingdingCode": threedingdingCode,
  656. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未完成维修。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n牧场总经理督办提醒,请至设备管理平台操作(若已处理请忽略)",
  657. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  658. tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 3, levelthreecode, main["id"])
  659. }
  660. } else {
  661. minute := (time.Now().Unix() - requestTime.Unix()) / 60
  662. if minute >= int64((levelthreeTime * 60)) {
  663. pushData = append(pushData, map[string]string{"userid": levelthreecode, "empId": levelthree, "tel": threetel, "dingdingCode": threedingdingCode,
  664. "msg": fmt.Sprintf("【维修督办】报修单号%s超时未完成维修。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n牧场总经理督办提醒,请至设备管理平台操作(若已处理请忽略)",
  665. main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
  666. tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 3, levelthreecode, main["id"])
  667. }
  668. }
  669. go func(pushData []map[string]string) {
  670. MsgChan <- pushData
  671. }(pushData)
  672. }
  673. }
  674. var DingClient *dingding.Client
  675. type DingTalkSendReq struct {
  676. AgentId string `json:"agent_id"`
  677. UseridList string `json:"userid_list"`
  678. Msg msgDingTalkSend `json:"msg"`
  679. }
  680. type msgDingTalkSend struct {
  681. Msgtype string `json:"msgtype"`
  682. Text textDingTalkSend `json:"text"`
  683. }
  684. type textDingTalkSend struct {
  685. Content string `json:"content"`
  686. }
  687. type dingTalkUserId struct {
  688. Userid string `json:"userid"`
  689. }