123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770 |
- package util
- import (
- "bytes"
- "crypto/sha1"
- "fmt"
- "github.com/faabiosr/cachego/file"
- "github.com/fastwego/dingding"
- "github.com/robfig/cron/v3"
- "html/template"
- "io/ioutil"
- "log"
- "net/http"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
- "github.com/fastwego/offiaccount"
- template1 "github.com/fastwego/offiaccount/apis/message/template"
- "github.com/fastwego/offiaccount/apis/oauth"
- user1 "github.com/fastwego/offiaccount/apis/user"
- "github.com/fastwego/offiaccount/type/type_message"
- "github.com/fastwego/offiaccount/util"
- "github.com/fastwego/wxwork/corporation"
- "github.com/fastwego/wxwork/corporation/apis/external_contact/customer"
- message1 "github.com/fastwego/wxwork/corporation/apis/message"
- "github.com/gin-gonic/gin"
- "kpt.xdmy/apiserver/routers/restful"
- "kpt.xdmy/pkg/logging"
- "kpt.xdmy/pkg/setting"
- )
- //企业微信
- var OffiAccount *offiaccount.OffiAccount
- var Corp *corporation.Corporation
- var App *corporation.App
- var MsgChan chan []map[string]string
- type UserMsg struct {
- Touser string `json:"touser"`
- Msgtype string `json:"msgtype"`
- Agentid string `json:"agentid"`
- Text interface{} `json:"text"`
- }
- func CronWXwork() {
- defer func() { // 必须要先声明defer
- if err := recover(); err != nil {
- fmt.Printf("CronTest pnic err%+v \n", err)
- logging.Error("panic recover err ", err)
- }
- }()
- //initWXwork()
- initDingDing()
- go SendRun()
- log.Println("Starting CronWXwork...")
- c := cron.New()
- _, err := c.AddFunc("00 00 06 * * *", Getuseinfor) //* * * * *, 从分钟开始
- if err != nil {
- println("cron4 err", err.Error())
- }
- GetMsg()
- _, err = c.AddFunc("@every 2m0s", GetMsg) //* * * * *, 从分钟开始
- _, err = c.AddFunc("00 00 07 * * *", GetPartsInfo) //* * * * *, 每天七点
- cronMaintainPush()
- c.AddFunc("@every 2m0s", cronMaintainPush)
- if err != nil {
- println("cron5 err", err.Error())
- }
- c.Start()
- }
- func Ceshi() {
- fmt.Println("sasdsdadasa")
- }
- func GetPartsInfo() {
- tx, err1 := restful.Dbs.Beginx()
- defer func() {
- switch {
- case err1 != nil:
- println("tx.Begin 事务启动失败__error:", err1.Error())
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err1 = tx.Commit()
- }
- }
- }()
- query, err := restful.MapStrListTx(tx, "select count(*) success,(select count(*) from parts ps "+
- " where ps.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and ps.issync=0 ) woring "+
- " from parts where parts.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and parts.issync=1 ")
- query1, err := restful.MapStrListTx(tx, " select empid from user where id in(select user_id from user_role "+
- "where role_id in (select id from role where easInformationReception = 1))")
- if err != nil {
- logging.Error("获取备件同步成功与否__error:", err.Error())
- } else {
- if len(query1) > 0 && len(query) > 0 {
- for i := 0; i < len(query1); i++ {
- success := query[0]["success"]
- personId := query1[i]["empid"]
- woring := query[0]["woring"]
- _, err = tx.Exec("INSERT INTO wxworkmsg(date,userid,msg,formcode,type,note) VALUES(?,?,?,?,?,?)",
- time.Now().Format("2006-01-02"), personId, "【eas】同步成功"+success+"条"+"同步失败"+woring+"条",
- "eas", 0, nil)
- if err != nil {
- }
- }
- }
- if err != nil {
- logging.Error("插入eas同步信息到微信信息表__error:", err.Error())
- }
- }
- }
- func Getuseinfor1() {
- logging.Error("PostDataByNames========= ")
- }
- func Getuseinfor() {
- defer func() { // 必须要先声明defer
- if err := recover(); err != nil {
- logging.Error("Getuseinfor pnic err", err) // 这里的err其实就是panic传入的内容,55
- }
- }()
- value := make(url.Values, 1)
- value.Add("department_id", "1")
- value.Add("fetch_child", "1")
- msgmap := make(map[string]interface{})
- resp, err := customer.List(App, value)
- if err != nil {
- println("contact.UserList err", err.Error())
- }
- err = json.Unmarshal(resp, &msgmap)
- if err != nil {
- println("json.Unmarshal err", err.Error())
- }
- tx, err1 := restful.Dbs.Beginx()
- defer func() {
- switch {
- case err1 != nil:
- logging.Error("tx.Begin 事务启动失败__error:", err.Error())
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- }()
- if _, ok := msgmap["userlist"]; ok {
- for _, value := range msgmap["userlist"].([]interface{}) {
- userid := value.(map[string]interface{})["userid"]
- name := value.(map[string]interface{})["name"]
- var department interface{}
- if len(value.(map[string]interface{})["department"].([]interface{})) > 0 {
- department = value.(map[string]interface{})["department"].([]interface{})[0]
- }
- var empcode interface{}
- if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) == 1 {
- empcode = value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})[0].(map[string]interface{})["value"]
- } else if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) > 1 {
- for _, va := range value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{}) {
- if va.(map[string]interface{})["name"] == "工号" {
- empcode = va.(map[string]interface{})["value"]
- break
- }
- }
- }
- //jvalue,_ :=json.Marshal(value)
- _, err = tx.Exec("insert into wxworkuser(userid,name,department,empcode)values(?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?,department=?", userid, name, department, empcode, empcode, department)
- //_,err =tx.Exec("insert into wxworkuser(userid,name,department,empcode,json)values(?,?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?",userid,name,department,empcode,string(jvalue),empcode)
- if err != nil {
- logging.Error("insert into wxworkuser err ", err.Error())
- }
- }
- }
- logging.Info("update wxworkuser success ")
- }
- func SendRun() {
- defer func() {
- if err := recover(); err != nil {
- logging.Error("GetMsg pnic err", err)
- }
- }()
- for {
- msgs := <-MsgChan
- println(len(msgs))
- for _, value := range msgs {
- /*
- content := make(map[string]interface{})
- content["content"] = value["msg"]
- msg := UserMsg{
- Touser: value["userid"],
- Agentid: setting.ServerSetting.WXworkAgentid,
- Text: content,
- Msgtype: "text",
- }
- msgbyte, err := json.Marshal(msg)
- if err != nil {
- logging.Error("json.Marshal err ", err.Error())
- }
- _, err = message1.Send(App, msgbyte)
- if err != nil {
- logging.Error("message1.Send err ", err.Error())
- fmt.Println("message1.Send err", err.Error())
- } else {
- }
- */
- ///*
- if value["dingdingCode"] == "" {
- //restful.MapStr(` select`)
- params := url.Values{}
- params.Add("mobile", value["tel"])
- //params.Add("mobile", "18317742428")
- req, _ := http.NewRequest(http.MethodGet, "/user/get_by_mobile?"+params.Encode(), nil)
- resp, err := DingClient.Do(req)
- if err != nil {
- continue
- }
- fmt.Println(value["111"], value["userid"], value["empId"])
- dingTalkUser := new(dingTalkUserId)
- json.Unmarshal(resp, dingTalkUser)
- _, err = restful.Dbs.Exec(` update emp set dingdingCode = ? where (tel = ? ) `, dingTalkUser.Userid, value["tel"])
- if err != nil {
- continue
- }
- value["dingdingCode"] = dingTalkUser.Userid
- }
- //306804033029907132
- //306804033029907132
- // 调用 api
- if value["dingdingCode"] == "" {
- continue
- }
- dingTalkSendReq := new(DingTalkSendReq)
- dingTalkSendReq.AgentId = setting.ServerSetting.DingTalkAgentid
- dingTalkSendReq.UseridList = value["dingdingCode"]
- dingTalkSendReq.Msg.Msgtype = "text"
- dingTalkSendReq.Msg.Text.Content = value["msg"]
- dingTalkSendReqByte, _ := json.Marshal(dingTalkSendReq)
- sendReq, _ := http.NewRequest(http.MethodPost, "/topapi/message/corpconversation/asyncsend_v2", bytes.NewBuffer(dingTalkSendReqByte))
- sendResp, err := DingClient.Do(sendReq)
- if err != nil {
- continue
- }
- fmt.Println(string(sendResp))
- //*/
- }
- }
- }
- func GetMsgv1() {
- go GetMsgv2()
- }
- func GetMsgv2() {
- defer func() { // 必须要先声明defer
- if err := recover(); err != nil {
- logging.Error("GetMsg pnic err", err) // 这里的err其实就是panic传入的内容,55
- }
- }()
- time.Sleep(time.Second)
- a := 0
- b := 1 / a
- println(b)
- }
- func GetMsg() {
- defer func() { // 必须要先声明defer
- if err := recover(); err != nil {
- logging.Error("GetMsg pnic err", err) // 这里的err其实就是panic传入的内容,55
- }
- }()
- tx, err1 := restful.Dbs.Beginx()
- defer func() {
- switch {
- case err1 != nil:
- println("tx.Begin 事务启动失败__error:", err1.Error())
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err1 = tx.Commit()
- }
- }
- }()
- sqls, err := restful.MapStrListTx(tx, "select sqlstr from apisql where sqlname in ('getWXworkMsg','updateWXworkMsg') order by sqlname")
- if err != nil {
- logging.Error("select from sqls err ", err.Error())
- }
- if len(sqls) < 2 {
- return
- }
- sqlmsg := sqls[0]["sqlstr"]
- sqlupdate := sqls[1]["sqlstr"]
- var query []map[string]string
- if len(sqls) > 0 {
- query, err = restful.MapStrListTx(tx, sqlmsg)
- if err != nil {
- logging.Error("select from wxworkmsg err ", err.Error(), len(query))
- } else {
- _, err = tx.Exec(sqlupdate)
- if err != nil {
- logging.Error("update wxworkmsg err ", err.Error(), len(query))
- }
- }
- }
- if len(query) > 0 {
- go func() {
- msgs := query
- MsgChan <- msgs
- }()
- }
- }
- func SendMsgtest() {
- message1.Send(App, []byte(`{
- "touser": "18322596935",
- "toparty": "PartyID1|PartyID2",
- "totag": "TagID1 | TagID2",
- "msgtype": "text",
- "agentid": 1000022,
- "text": {
- "content": "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
- },
- "safe": 0,
- "enable_id_trans": 0,
- "enable_duplicate_check": 0
- }`))
- }
- func initOffiAccount() {
- // 加载配置文件
- // 创建公众号实例
- OffiAccount = offiaccount.New(offiaccount.Config{
- // wxe1cc563ba393dd1a
- Appid: "wxe1cc563ba393dd1a",
- Secret: "25e56243da9581eab6f4d67a12ef4658",
- Token: "123",
- // 6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f
- EncodingAESKey: "6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f",
- })
- //payload := []byte(`
- //{
- // "button":[
- // {
- // "name":"菜单",
- // "sub_button":[
- // {
- // "type":"view",
- // "name":"搜索",
- // "url":"http://www.baidu.com/"
- // }]
- // }]
- //}`)
- //resp, err := menu.Create(OffiAccount, payload)
- //fmt.Println(resp, err)
- //guide.SetGuideConfig(OffiAccount,[]byte("欢迎关注"))
- }
- func initWXwork() {
- // 加载配置文件
- // 创建企业微信实例
- Corp = corporation.New(corporation.Config{Corpid: setting.ServerSetting.WXworkCorpid})
- App = Corp.NewApp(corporation.AppConfig{
- AgentId: setting.ServerSetting.WXworkAgentid,
- Secret: setting.ServerSetting.WXworkSecret,
- Token: "",
- EncodingAESKey: "",
- })
- MsgChan = make(chan []map[string]string, 100)
- }
- func initDingDing() {
- atm := &dingding.DefaultAccessTokenManager{
- Id: setting.ServerSetting.DingTalkAppKey,
- Name: "access_token",
- GetRefreshRequestFunc: func() *http.Request {
- params := url.Values{}
- params.Add("appkey", setting.ServerSetting.DingTalkAppKey)
- params.Add("appsecret", setting.ServerSetting.DingTalkAppSecret)
- req, _ := http.NewRequest(http.MethodGet, dingding.ServerUrl+"/gettoken?"+params.Encode(), nil)
- return req
- },
- Cache: file.New(os.TempDir()),
- }
- // 钉钉 客户端
- DingClient = dingding.NewClient(atm)
- MsgChan = make(chan []map[string]string, 100)
- }
- func InitRouter() *gin.Engine {
- r := gin.New()
- // ginpprof.Wrap(r)
- r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
- // 你的自定义格式
- return fmt.Sprintf(" %+v \n",
- param.Keys,
- )
- }))
- r.Use(gin.Logger()) // 日志
- //r.Use(Cors()) // 跨域请求rolemenus
- r.Use(gin.Recovery())
- r.GET("/", func(c *gin.Context) {
- //OffiAccount.Server.EchoStr(c.Writer, c.Request)
- config, err := jsapiConfig(c)
- if err != nil {
- fmt.Println("==========1", err)
- return
- }
- t1, err := template.ParseFiles("index.html")
- if err != nil {
- fmt.Println("==========2", err)
- return
- }
- println("===========", t1.Name())
- t1.Execute(c.Writer, config)
- })
- r.POST("/", HandleMessage)
- return r
- }
- func jsapiConfig(c *gin.Context) (config template.JS, err error) {
- // 优先从环缓存获取
- jsapi_ticket, err := OffiAccount.AccessToken.Cache.Fetch("jsapi_ticket:" + OffiAccount.Config.Appid)
- if len(jsapi_ticket) == 0 {
- var ttl int64
- jsapi_ticket, ttl, err = oauth.GetJSApiTicket(OffiAccount)
- if err != nil {
- return
- }
- err = OffiAccount.AccessToken.Cache.Save("jsapi_ticket:"+OffiAccount.Config.Appid, jsapi_ticket, time.Duration(ttl)*time.Second)
- if err != nil {
- return
- }
- }
- nonceStr := util.GetRandString(6)
- timestamp := strconv.FormatInt(time.Now().Unix(), 10)
- pageUrl := "http://" + c.Request.Host + c.Request.RequestURI
- plain := "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + pageUrl
- signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain)))
- fmt.Println(plain, signature)
- configMap := map[string]string{
- "url": pageUrl,
- "nonceStr": nonceStr,
- "appid": OffiAccount.Config.Appid,
- "timestamp": timestamp,
- "signature": signature,
- }
- marshal, err := json.Marshal(configMap)
- if err != nil {
- return
- }
- return template.JS(marshal), nil
- }
- func HandleMessage(c *gin.Context) {
- // 区分不同账号
- //account := path.Base(c.Request.URL.Path)
- // 调用相应公众号服务
- body, _ := ioutil.ReadAll(c.Request.Body)
- log.Println(string(body))
- message, err := OffiAccount.Server.ParseXML(body)
- if err != nil {
- log.Println(err)
- }
- var output interface{}
- switch message.(type) {
- case type_message.MessageText: // 文本 消息
- msg := message.(type_message.MessageText)
- // 回复文本消息
- output = type_message.ReplyMessageText{
- ReplyMessage: type_message.ReplyMessage{
- ToUserName: type_message.CDATA(msg.FromUserName),
- FromUserName: type_message.CDATA(msg.ToUserName),
- CreateTime: strconv.FormatInt(time.Now().Unix(), 10),
- MsgType: type_message.ReplyMsgTypeText,
- },
- Content: type_message.CDATA(msg.Content),
- }
- resp, err := template1.Send(OffiAccount, []byte(`
- {
- "touser":"`+msg.FromUserName+`",
- "template_id":"BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo",
- "data":{
- "first": {
- "value":"恭喜你购买成功!",
- "color":"#173177"
- },
- "keyword1":{
- "value":"巧克力",
- "color":"#173177"
- },
- "keyword2": {
- "value":"39.8元",
- "color":"#173177"
- },
- "keyword3": {
- "value":"2014年9月22日",
- "color":"#173177"
- },
- "remark":{
- "value":"欢迎再次购买!",
- "color":"#173177"
- }
- }
- }`))
- println("msg", resp, err, msg.FromUserName)
- }
- res, _ := user1.Get(OffiAccount, nil)
- println("res======", string(res))
- OffiAccount.Server.Response(c.Writer, c.Request, output)
- }
- func cronMaintainPush() {
- tx, err := restful.Dbs.Beginx()
- defer func() {
- switch {
- case err != nil:
- println("tx.Begin 事务启动失败__error:", err.Error())
- if tx != nil {
- tx.Rollback()
- }
- default:
- if tx != nil {
- err = tx.Commit()
- }
- }
- }()
- 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 " +
- "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') ")
- if err != nil {
- log.Println(err)
- return
- }
- eqIdList := []string{}
- for _, main := range maintainList {
- fmt.Println(main["requestTime"])
- eqIdList = append(eqIdList, main["eqId"])
- }
- if len(eqIdList) == 0 {
- return
- }
- equipmentList, err := restful.MapStrList(fmt.Sprintf(" select levelone,leveltwo,levelthree,id, maintenance,(select empcode from emp where e.maintenance= id ) maintenancecode,"+
- "levelone, (select userid from wxworkuser where empCode = (select empcode from emp where e.levelone= id )) levelonecode,"+
- "(select userid from wxworkuser where empCode = (select empcode from emp where e.leveltwo= id )) leveltwocode,"+
- "levelthree ,(select userid from wxworkuser where empCode = (select empcode from emp where e.levelthree= id )) levelthreecode,"+
- " 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, ",")))
- if err != nil {
- log.Println(err)
- return
- }
- maintainpushList, err := restful.MapStrList("select id,maintainId,eqId,level,usercode,DATE_FORMAT(pushTime,'%Y-%m-%d %H:%i:%S') pushTime " +
- "from maintainpush where DATE_FORMAT(pushTime,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d') order by pushTime desc ")
- if err != nil {
- log.Println(err)
- return
- }
- for _, main := range maintainList {
- var levelonecode, leveltwocode, levelthreecode, levelone, leveltwo, levelthree, onetel, twotel, threetel, onedingdingCode, twodingdingCode, threedingdingCode string
- var leveloneTime, leveltwoTime, levelthreeTime int
- requestTime, err := time.ParseInLocation("2006-01-02 15:04:05", main["requestTime"], time.Local)
- if err != nil {
- log.Println(err)
- return
- }
- for _, eq := range equipmentList {
- if eq["id"] == main["eqId"] {
- //maintenancecode = main["pickId"]
- levelonecode = eq["levelonecode"]
- leveltwocode = eq["leveltwocode"]
- levelthreecode = eq["levelthreecode"]
- leveloneTime, _ = strconv.Atoi(eq["leveloneTime"])
- leveltwoTime, _ = strconv.Atoi(eq["leveltwoTime"])
- levelthreeTime, _ = strconv.Atoi(eq["levelthreeTime"])
- levelone = eq["levelone"]
- leveltwo = eq["leveltwo"]
- levelthree = eq["levelthree"]
- onetel = eq["onetel"]
- twotel = eq["twotel"]
- threetel = eq["threetel"]
- onedingdingCode = eq["onedingdingCode"]
- twodingdingCode = eq["twodingdingCode"]
- threedingdingCode = eq["threedingdingCode"]
- //push, _ = strconv.ParseInt(eq["pushTime"], 10, 64)
- break
- }
- }
- if leveloneTime == 0 || leveltwoTime == 0 || levelthreeTime == 0 {
- continue
- }
- var onePushTime, twoPushTime, threePushTime string
- for _, maintainpush := range maintainpushList {
- if maintainpush["eqId"] == main["eqId"] && maintainpush["maintainId"] == main["id"] {
- mainLevel, _ := strconv.ParseInt(maintainpush["level"], 10, 64)
- if mainLevel == 1 && onePushTime == "" {
- onePushTime = maintainpush["pushTime"]
- } else if mainLevel == 2 && twoPushTime == "" {
- twoPushTime = maintainpush["pushTime"]
- } else if mainLevel == 3 && threePushTime == "" {
- threePushTime = maintainpush["pushTime"]
- }
- }
- }
- pushData := make([]map[string]string, 0)
- empList, err := restful.MapStrList(` select empname from emp where FIND_IN_SET(id,?) `, main["pickId"])
- if err != nil {
- log.Println(err)
- return
- }
- var empName []string
- for _, emp := range empList {
- empName = append(empName, emp["empname"])
- }
- if onePushTime != "" {
- lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", onePushTime, time.Local)
- if err != nil {
- log.Println(err)
- return
- }
- minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
- if minute >= int64((leveloneTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": levelonecode, "empId": levelone, "tel": onetel, "dingdingCode": onedingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备主管督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 1, levelonecode, main["id"])
- }
- } else {
- minute := (time.Now().Unix() - requestTime.Unix()) / 60
- if minute >= int64((leveloneTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": levelonecode, "empId": levelone, "tel": onetel, "dingdingCode": onedingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备主管督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- _, err := tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 1, levelonecode, main["id"])
- fmt.Println(err)
- }
- }
- if twoPushTime != "" {
- lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", twoPushTime, time.Local)
- if err != nil {
- log.Println(err)
- return
- }
- minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
- if minute >= int64((leveltwoTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": leveltwocode, "empId": leveltwo, "tel": twotel, "dingdingCode": twodingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备助理督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 2, leveltwocode, main["id"])
- }
- } else {
- minute := (time.Now().Unix() - requestTime.Unix()) / 60
- if minute >= int64((leveltwoTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": leveltwocode, "empId": leveltwo, "tel": twotel, "dingdingCode": twodingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未维修完成。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n设备助理督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 2, leveltwocode, main["id"])
- }
- }
- if threePushTime != "" {
- lastPushTime, err := time.ParseInLocation("2006-01-02 15:04:05", threePushTime, time.Local)
- if err != nil {
- log.Println(err)
- return
- }
- minute := (time.Now().Unix() - lastPushTime.Unix()) / 60
- if minute >= int64((levelthreeTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": levelthreecode, "empId": levelthree, "tel": threetel, "dingdingCode": threedingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未完成维修。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n牧场总经理督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 3, levelthreecode, main["id"])
- }
- } else {
- minute := (time.Now().Unix() - requestTime.Unix()) / 60
- if minute >= int64((levelthreeTime * 60)) {
- pushData = append(pushData, map[string]string{"userid": levelthreecode, "empId": levelthree, "tel": threetel, "dingdingCode": threedingdingCode,
- "msg": fmt.Sprintf("【维修督办】报修单号%s超时未完成维修。\n设备资产编号:%s\n用途:%s\n故障类型:%s\n报修时间:%s\n推送时间:%s\n维修人:%s\n报修人:%s\n牧场总经理督办提醒,请至设备管理平台操作(若已处理请忽略)",
- main["repairCode"], main["eqCode"], main["purpose"], main["details"], main["requestTime"], time.Now().Format("2006-01-02 15:04:05"), strings.Join(empName, ","), main["requestername"])})
- tx.Exec(` insert into maintainpush(eqId,level,usercode,pushTime,maintainId)values(?,?,?,now(),?)`, main["eqId"], 3, levelthreecode, main["id"])
- }
- }
- go func(pushData []map[string]string) {
- MsgChan <- pushData
- }(pushData)
- }
- }
- var DingClient *dingding.Client
- type DingTalkSendReq struct {
- AgentId string `json:"agent_id"`
- UseridList string `json:"userid_list"`
- Msg msgDingTalkSend `json:"msg"`
- }
- type msgDingTalkSend struct {
- Msgtype string `json:"msgtype"`
- Text textDingTalkSend `json:"text"`
- }
- type textDingTalkSend struct {
- Content string `json:"content"`
- }
- type dingTalkUserId struct {
- Userid string `json:"userid"`
- }
|