| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684 | 
							- package api
 
- import (
 
- 	"bytes"
 
- 	"context"
 
- 	"encoding/json"
 
- 	"fmt"
 
- 	"io/ioutil"
 
- 	"log"
 
- 	"net/http"
 
- 	"os"
 
- 	"reflect"
 
- 	"strconv"
 
- 	"strings"
 
- 	"time"
 
- 	"tmr-watch/conf/setting"
 
- 	"tmr-watch/http/handle/restful"
 
- 	"tmr-watch/pkg/app"
 
- 	"tmr-watch/pkg/e"
 
- 	"tmr-watch/pkg/logging"
 
- 	"github.com/Anderson-Lu/gofasion/gofasion"
 
- 	"github.com/astaxie/beego/logs"
 
- 	"github.com/gin-gonic/gin"
 
- 	"github.com/robfig/cron"
 
- 	"github.com/xormplus/xorm"
 
- )
 
- func CronScheduled(ctx context.Context) {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	pastureinfo := new(udPastureInfo)
 
- 	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS
 
- 	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
 
- 	if err != nil {
 
- 		logs.Error(err)
 
- 		return
 
- 	}
 
- 	// duetimecst, _ := time.ParseInLocation("15:04:05", "00:10:00", time.Local)
 
- 	// duetimecst1, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
 
- 	// spec := fmt.Sprintf("@every %v", duetimecst.Sub(duetimecst1))
 
- 	// c := cron.New()
 
- 	// c.AddFunc(spec, func() {
 
- 	// 	tx1 := restful.Engine.NewSession()
 
- 	// 	defer tx1.Close()
 
- 	// 	exist, err := tx1.Table("notice").Where("status = 1").And("content = ? ", "downloadedplan_log").Exist()
 
- 	// 	if err != nil {
 
- 	// 		logs.Error("CronScheduled-error-1:", err)
 
- 	// 		return
 
- 	// 	}
 
- 	// 	if exist {
 
- 	// 		_, err := tx.SQL(`update notice set status = 0  where content =  ? `, "downloadedplan_log").Execute()
 
- 	// 		if err != nil {
 
- 	// 			logs.Error("CronScheduled-error-2:", err)
 
- 	// 			return
 
- 	// 		}
 
- 	// 		Scheduled(ctx, tx1, pastureinfo)
 
- 	// 	}
 
- 	// })
 
- 	// c.Start()
 
- 	//消息提醒
 
- 	duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
 
- 	duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
 
- 	spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
 
- 	downloadplandtl1 := cron.New()
 
- 	downloadplandtl1.AddFunc(spec1, func() {
 
- 		dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ? `, pastureinfo.Pastureid).Query().List()
 
- 		if err != nil {
 
- 			logs.Error("CronScheduled-error-3:", err)
 
- 			return
 
- 		}
 
- 		for _, data := range dataList {
 
- 			var openIdList []string
 
- 			if _, ok := data["user"]; ok {
 
- 				openIdList = strings.Split(data["user"].(string), ",")
 
- 			}
 
- 			if data["function"].(string) == "processAnalysisEarlyWarning" {
 
- 				if len(openIdList) > 0 {
 
- 					processAnalysisEarlyWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
 
- 				}
 
- 			} else if data["function"].(string) == "abnormalMixingDelay" {
 
- 				if len(openIdList) > 0 {
 
- 					abnormalMixingDelay(openIdList, pastureinfo.Pastureid, data["id"].(int64))
 
- 				}
 
- 			} else if data["function"].(string) == "endOfShift" {
 
- 				if len(openIdList) > 0 {
 
- 					endOfShift(openIdList, pastureinfo.Pastureid, data["id"].(int64))
 
- 				}
 
- 			} else if data["function"].(string) == "plansToComplete" {
 
- 				if len(openIdList) > 0 {
 
- 					plansToComplete(openIdList, pastureinfo.Pastureid, data["id"].(int64))
 
- 				}
 
- 			}
 
- 		}
 
- 	})
 
- 	downloadplandtl1.Start()
 
- 	dayCron := cron.New()
 
- 	dayCron.AddFunc("30 23 * * *", func() {
 
- 		dataList, err := tx.SQL(` select user,function,id from remind where pastureid = ?  and  function = ? `, pastureinfo.Pastureid, "inventoryWarning").Query().List()
 
- 		if err != nil {
 
- 			logs.Error("CronScheduled-error-5:", err)
 
- 			return
 
- 		}
 
- 		for _, data := range dataList {
 
- 			var openIdList []string
 
- 			if _, ok := data["user"]; ok {
 
- 				openIdList = strings.Split(data["user"].(string), ",")
 
- 			}
 
- 			if data["function"].(string) == "inventoryWarning" {
 
- 				if len(openIdList) > 0 {
 
- 					inventoryWarning(openIdList, pastureinfo.Pastureid, data["id"].(int64))
 
- 				}
 
- 			}
 
- 		}
 
- 	})
 
- 	dayCron.Start()
 
- 	// //圣牧自动同步前天有进行中的任务
 
- 	manualUdData(pastureinfo)
 
- }
 
- type ScheduledInfo struct {
 
- 	Id      int64  `xorm:"id"`
 
- 	Sname   string `xorm:"sname"`
 
- 	Action  int64  `xorm:"action"`
 
- 	Childid int64  `xorm:"childid"`
 
- 	Times   string `xorm:"times"`
 
- 	Enable  string `xorm:"enable"`
 
- }
 
- type ScheduledUpInfo struct {
 
- 	Id         int64  `xorm:"id"`
 
- 	Company    string `xorm:"company"`
 
- 	Addres     string `xorm:"addres"`
 
- 	Datatype   int64  `xorm:"datatype"`
 
- 	Package    string `xorm:"Package"`
 
- 	Datasql    string `xorm:"datasql"`
 
- 	Automatic  int64  `xorm:"automatic"`
 
- 	Manual     int64  `xorm:"manual"`
 
- 	Targetdata string `xorm:"targetdata"`
 
- }
 
- type ScheduledDownInfo struct {
 
- 	Id          int64  `xorm:"id"`
 
- 	Datatype    int64  `xorm:"datatype"`
 
- 	Addres      string `xorm:"addres"`
 
- 	Adressparam string `xorm:"adressparam"`
 
- 	Targetdata  string `xorm:"targetdata"`
 
- 	Manual      int64  `xorm:"manual"`
 
- 	Methods     string `xorm:"methods"`
 
- }
 
- type ScheduledDownChildInfo struct {
 
- 	Id        int64  `xorm:"id"`
 
- 	Parentid  int64  `xorm:"parentid"`
 
- 	Fieldname string `xorm:"fieldname"`
 
- 	Checksql  string `xorm:"checksql"`
 
- 	Dosql     string `xorm:"dosql"`
 
- }
 
- func Scheduled(ctx context.Context, tx *xorm.Session, pastureinfo *udPastureInfo) {
 
- 	times := new(ScheduledInfo)
 
- 	err := tx.SQL("  select  times  from  scheduled  where  action = 0 group by times").GetFirst(times).Error
 
- 	if err != nil {
 
- 		logs.Error(err)
 
- 		return
 
- 	}
 
- 	if times.Times == "0" {
 
- 		downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') `).Query().List()
 
- 		if err != nil {
 
- 			logs.Error(err)
 
- 			return
 
- 		}
 
- 		ids := []string{}
 
- 		for _, item := range downloadedplanLogList {
 
- 			ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
 
- 		}
 
- 		fmt.Println(ids, time.Now())
 
- 		err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
 
- 		if err != nil {
 
- 			return
 
- 		}
 
- 	} else if times.Times == "1" {
 
- 		downloadedplanLogList, err := tx.SQL(` select times from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') and status = 0  group by times`).Query().List()
 
- 		if err != nil {
 
- 			logs.Error(err)
 
- 			return
 
- 		}
 
- 		for _, item := range downloadedplanLogList {
 
- 			count, err := tx.SQL(`  select  count(1)  from  downloadedplan  where  pastureid = ? and mydate = date_format(now(),'%Y-%m-%d') 
 
- 			and iscompleted = 0 and times  = ? and enable = 1 `,
 
- 				pastureinfo.Pastureid, item["times"]).Count()
 
- 			if err != nil {
 
- 				logs.Error(err)
 
- 				return
 
- 			}
 
- 			if count == 0 {
 
- 				//推送
 
- 				downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d')
 
- 				 and times  = ? `, item["times"]).Query().List()
 
- 				if err != nil {
 
- 					logs.Error(err)
 
- 					return
 
- 				}
 
- 				ids := []string{}
 
- 				for _, item := range downloadedplanLogList {
 
- 					ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
 
- 				}
 
- 				err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
 
- 				if err != nil {
 
- 					return
 
- 				}
 
- 			}
 
- 		}
 
- 	} else if times.Times == "2" {
 
- 		count, err := tx.SQL("  select  count(1)  from  downloadedplan  where  pastureid = ? and mydate = date_format(now(),'%Y-%m-%d') and iscompleted = 0  and enable = 1 ",
 
- 			pastureinfo.Pastureid).Count()
 
- 		if err != nil {
 
- 			logs.Error(err)
 
- 			return
 
- 		}
 
- 		if count == 0 {
 
- 			//推送
 
- 			downloadedplanLogList, err := tx.SQL(` select id from downloadedplan_log  where  date = date_format(now(),'%Y-%m-%d') `).Query().List()
 
- 			if err != nil {
 
- 				logs.Error(err)
 
- 				return
 
- 			}
 
- 			ids := []string{}
 
- 			for _, item := range downloadedplanLogList {
 
- 				ids = append(ids, strconv.FormatInt(item["id"].(int64), 10))
 
- 			}
 
- 			err = UpdatePush(ctx, tx, true, ids, pastureinfo, "", time.Now().Format("2006-01-02"))
 
- 			if err != nil {
 
- 				return
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func UpdateScheduledStatus(c *gin.Context) {
 
- 	appG := app.Gin{C: c}
 
- 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 	fsion := gofasion.NewFasion(string(dataByte))
 
- 	idList := fsion.Get("id").Array()
 
- 	automatic := fsion.Get("automatic").ValueStr()
 
- 	manual := fsion.Get("manual").ValueStr()
 
- 	company := fsion.Get("company").ValueStr()
 
- 	//type 0 上传,1 下载
 
- 	typee := fsion.Get("type").ValueStr()
 
- 	ids := []string{}
 
- 	for _, item := range idList {
 
- 		ids = append(ids, item.ValueStr())
 
- 	}
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	tx.Begin()
 
- 	sqlstr := ""
 
- 	sqlstr1 := ""
 
- 	// var args []interface{}
 
- 	if typee == "0" {
 
- 		if len(ids) > 0 {
 
- 			sqlstr = `update scheduled s  join scheduled_up su on su.id = s.childid set `
 
- 			sqlstr1 = `update scheduled s  join scheduled_up su on su.id = s.childid set `
 
- 			if automatic != "" {
 
- 				sqlstr += " su.automatic = 1 "
 
- 				sqlstr1 += " su.automatic = 0 "
 
- 			} else if manual != "" {
 
- 				sqlstr += " su.manual = 1 "
 
- 				sqlstr1 += " su.manual = 0 "
 
- 			}
 
- 			id := strings.Join(ids, ",")
 
- 			sqlstr += fmt.Sprintf(" where s.id in (%s)  and s.action = 0 and su.company = '%s' ", id, company)
 
- 			sqlstr1 += fmt.Sprintf(" where s.id not in (%s) and s.action = 0 and su.company ='%s' ", id, company)
 
- 		} else {
 
- 			sqlstr = `update scheduled s  join scheduled_up su on su.id = s.childid set `
 
- 			if automatic != "" {
 
- 				sqlstr += " su.automatic = 0 "
 
- 			} else if manual != "" {
 
- 				sqlstr += " su.manual = 0 "
 
- 			}
 
- 			sqlstr += fmt.Sprintf(" where  s.action = 0 and su.company = '%s' ", company)
 
- 		}
 
- 	} else {
 
- 		if len(ids) > 0 {
 
- 			sqlstr = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
 
- 			sqlstr1 = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
 
- 			sqlstr += " sd.manual = 1 "
 
- 			sqlstr1 += " sd.manual = 0 "
 
- 			id := strings.Join(ids, ",")
 
- 			sqlstr += fmt.Sprintf(" where s.id in (%s)  and s.action = 1 and sd.company = '%s' ", id, company)
 
- 			sqlstr1 += fmt.Sprintf(" where s.id not in (%s)  and s.action = 1  and sd.company = '%s' ", id, company)
 
- 		} else {
 
- 			sqlstr = `update scheduled s  join scheduled_down sd on sd.id = s.childid set `
 
- 			sqlstr += " sd.manual = 0 "
 
- 			sqlstr += fmt.Sprintf(" where  s.action = 1 and sd.company = '%s' ", company)
 
- 		}
 
- 	}
 
- 	_, err := tx.SQL(sqlstr).Execute()
 
- 	if err != nil {
 
- 		log.Println("UpdateScheduledStatus-error-1: ", err)
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
 
- 		tx.Rollback()
 
- 	}
 
- 	if len(sqlstr1) > 0 {
 
- 		_, err = tx.SQL(sqlstr1).Execute()
 
- 		if err != nil {
 
- 			log.Println("UpdateScheduledStatus-error-2: ", err)
 
- 			appG.Response(http.StatusInternalServerError, e.ERROR, err)
 
- 			tx.Rollback()
 
- 		}
 
- 	}
 
- 	err = tx.Commit()
 
- 	if err != nil {
 
- 		log.Println("UpdateScheduledStatus-error-3: ", err)
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, err)
 
- 		tx.Rollback()
 
- 	}
 
- 	appG.Response(http.StatusOK, e.SUCCESS, true)
 
- }
 
- func SynchronizeNow(c *gin.Context) {
 
- 	appG := app.Gin{C: c}
 
- 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 	fsion := gofasion.NewFasion(string(dataByte))
 
- 	company := fsion.Get("company").ValueStr()
 
- 	date := fsion.Get("date").ValueStr()
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	pastureinfo := new(udPastureInfo)
 
- 	err := tx.SQL(`select column_default  as pastureid   from    information_schema.COLUMNS 
 
- 	WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
 
- 	if err != nil {
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 
- 		return
 
- 	}
 
- 	dataList, err := tx.SQL(`select id from downloadedplan where mydate = date_format(?,'%Y-%m-%d') `, date).Query().List()
 
- 	if err != nil {
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 
- 		return
 
- 	}
 
- 	var idList []string
 
- 	for _, data := range dataList {
 
- 		idList = append(idList, strconv.FormatInt(data["id"].(int64), 10))
 
- 	}
 
- 	err = UpdatePush(c, tx, false, idList, pastureinfo, company, date)
 
- 	if err != nil {
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 
- 		return
 
- 	}
 
- 	UpdateDown(c, tx, nil, pastureinfo, company)
 
- 	if err != nil {
 
- 		appG.Response(http.StatusInternalServerError, e.ERROR, false)
 
- 		return
 
- 	}
 
- 	appG.Response(http.StatusOK, e.SUCCESS, true)
 
- }
 
- func UpdatePush(ctx context.Context, tx *xorm.Session, auto bool, idList []string, pastureinfo *udPastureInfo, company, date string) error {
 
- 	upList := make([]*ScheduledUpInfo, 0)
 
- 	up := tx.Table("scheduled_up")
 
- 	if company != "" {
 
- 		up.Where("company = ? ", company)
 
- 	}
 
- 	if auto {
 
- 		up.Where("automatic = 1")
 
- 	} else {
 
- 		up.Where("manual = 1")
 
- 	}
 
- 	err := up.Find(&upList)
 
- 	if err != nil {
 
- 		log.Println("UpdataPush-error-1: ", err)
 
- 		return err
 
- 	}
 
- 	for _, item := range upList {
 
- 		if item.Datasql != "" {
 
- 			if item.Datatype == 3 || item.Datatype == 4 {
 
- 				targetdataList := strings.Split(item.Targetdata, ",")
 
- 				var args []interface{}
 
- 				for _, targetdata := range targetdataList {
 
- 					if targetdata == "pastureid" {
 
- 						args = append(args, pastureinfo.Pastureid)
 
- 					} else if targetdata == "idlist" {
 
- 						// args = append(args, strings.Join(idList, ","))
 
- 						item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
 
- 					} else if targetdata == "date" {
 
- 						args = append(args, date)
 
- 					}
 
- 				}
 
- 				data, err := tx.SQL(item.Datasql, args...).Query().List()
 
- 				if err != nil {
 
- 					log.Println("UpdataPush-error-2: ", err)
 
- 					continue
 
- 				}
 
- 				if len(data) > 0 {
 
- 					databyte, err := json.Marshal(data)
 
- 					if err != nil {
 
- 						log.Println("UpdataPush-error-3: ", err)
 
- 						continue
 
- 					}
 
- 					var method string
 
- 					// if item.Datatype == 4 {
 
- 					// 	continue
 
- 					// method = "uploadnewdiliverdata"
 
- 					// }
 
- 					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
 
- 				}
 
- 				if len(idList) > 0 {
 
- 					_, err := tx.SQL(fmt.Sprintf(" update downloadedplan_log set status = 1  where id in (%s)", strings.Join(idList, ","))).Execute()
 
- 					if err != nil {
 
- 						log.Println("UpdataPush-error-4: ", err)
 
- 						continue
 
- 					}
 
- 				}
 
- 			} else {
 
- 				targetdataList := strings.Split(item.Targetdata, ",")
 
- 				var args []interface{}
 
- 				for _, targetdata := range targetdataList {
 
- 					if targetdata == "pastureid" {
 
- 						args = append(args, pastureinfo.Pastureid)
 
- 					} else if targetdata == "idlist" {
 
- 						// args = append(args, strings.Join(idList, ","))
 
- 						item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
 
- 					}
 
- 				}
 
- 				data, err := tx.SQL(item.Datasql, args...).Query().List()
 
- 				if err != nil {
 
- 					log.Println("UpdataPush-error-5: ", err)
 
- 					// return err
 
- 				}
 
- 				if len(data) > 0 {
 
- 					databyte, err := json.Marshal(data)
 
- 					if err != nil {
 
- 						log.Println("UpdataPush-error-6: ", err)
 
- 						// return err
 
- 						continue
 
- 					}
 
- 					// d, err := OpenFile("a.txt")
 
- 					// d.WriteString()
 
- 					// UDPostPush(fmt.Sprintf(item.Package, string(databyte), len(data)), "application/json")
 
- 					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), "")
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- // OpenFile 判断文件是否存在  存在则OpenFile 不存在则Create
 
- func OpenFile(filename string) (*os.File, error) {
 
- 	if _, err := os.Stat(filename); os.IsNotExist(err) {
 
- 		fmt.Println("文件不存在")
 
- 		return os.Create(filename) //创建文件
 
- 	}
 
- 	fmt.Println("文件存在")
 
- 	return os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
 
- }
 
- func UpdateDown(ctx context.Context, tx *xorm.Session, idList []string, pastureinfo *udPastureInfo, company string) error {
 
- 	downList := make([]*ScheduledDownInfo, 0)
 
- 	down := tx.Table("scheduled_down")
 
- 	if company != "" {
 
- 		down.Where("company = ? ", company)
 
- 	}
 
- 	down.Where("manual = 1")
 
- 	err := down.Find(&downList)
 
- 	if err != nil {
 
- 		log.Println("UpdateDown-error-1: ", err)
 
- 		return err
 
- 	}
 
- 	for _, item := range downList {
 
- 		list := httpGetMC(item.Addres, item.Targetdata)
 
- 		if item.Methods != "" {
 
- 			s := ScheduledDown{}
 
- 			value := reflect.ValueOf(&s)
 
- 			f := value.MethodByName(item.Methods)
 
- 			f.Call([]reflect.Value{reflect.ValueOf(pastureinfo.Pastureid), reflect.ValueOf(list)})
 
- 			// value := reflect.ValueOf(&s)
 
- 			// f := value.MethodByName("Ccaa")
 
- 			// f.Call([]reflect.Value{reflect.ValueOf(list)})
 
- 		} else {
 
- 			childList := make([]*ScheduledDownChildInfo, 0)
 
- 			child := tx.Table("scheduled_down")
 
- 			child.Where("parentid = ? ", item.Id)
 
- 			err = child.Find(&childList)
 
- 			if err != nil {
 
- 				log.Println("UpdateDown-error-2: ", err)
 
- 				return err
 
- 			}
 
- 			if len(childList) > 0 {
 
- 				tx.Begin()
 
- 				for _, c := range childList {
 
- 					fieldnames := strings.Split(c.Fieldname, ",")
 
- 					for _, data := range list {
 
- 						var args []interface{}
 
- 						dataMap := data.(map[string]interface{})
 
- 						for _, fieldname := range fieldnames {
 
- 							args = append(args, dataMap[fieldname])
 
- 						}
 
- 						_, err = tx.SQL(c.Dosql, args...).Execute()
 
- 						if err != nil {
 
- 							tx.Rollback()
 
- 							log.Println("UpdateDown-error-3: ", err)
 
- 							return err
 
- 						}
 
- 					}
 
- 				}
 
- 				err := tx.Commit()
 
- 				if err != nil {
 
- 					tx.Rollback()
 
- 					log.Println("UpdateDown-error-4: ", err)
 
- 					return err
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- func httpGetMC(url, targetdata string) []interface{} {
 
- 	// url := fmt.Sprintf("https://wdc.unidairy.cn/copartner_downloads/?farmId=%s&method=%s", farmId, method)
 
- 	res, err := http.Get(url)
 
- 	if err != nil {
 
- 		return nil
 
- 	}
 
- 	robots, err := ioutil.ReadAll(res.Body)
 
- 	res.Body.Close()
 
- 	if err != nil {
 
- 		return nil
 
- 	}
 
- 	var data map[string][]interface{}
 
- 	json.Unmarshal(robots, &data)
 
- 	return data[targetdata]
 
- }
 
- type ScheduledDown struct {
 
- }
 
- func (h *ScheduledDown) SyncFeed(pastureid string, feedList []interface{}) {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	err := tx.Begin()
 
- 	if err != nil {
 
- 		tx.Rollback()
 
- 		logs.Error("syncFeed-error-1:", err)
 
- 		return
 
- 	}
 
- 	for _, f := range feedList {
 
- 		feed := f.(map[string]interface{})
 
- 		var feedcode, fname, fclass, fclassid, dry interface{}
 
- 		if _, ok := feed["feedcode"]; ok {
 
- 			feedcode = feed["feedcode"]
 
- 		}
 
- 		if _, ok := feed["feedname"]; ok {
 
- 			fname = feed["feedname"]
 
- 		}
 
- 		if _, ok := feed["feedclass"]; ok {
 
- 			fclass = feed["feedclass"]
 
- 		}
 
- 		if _, ok := feed["drymatter"]; ok {
 
- 			dry = feed["drymatter"]
 
- 		}
 
- 		fclassExist, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).Exist()
 
- 		if err != nil {
 
- 			tx.Rollback()
 
- 			logs.Error("syncFeed-error-2:", err)
 
- 			return
 
- 		}
 
- 		if fclassExist {
 
- 			fclassDataList, err := tx.SQL(" select id from feedclass where pastureid = ? and fcname = ?", pastureid, fclass).QueryString()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeed-error-3:", err)
 
- 				return
 
- 			}
 
- 			for _, fclassData := range fclassDataList {
 
- 				fclassid = fclassData["id"]
 
- 			}
 
- 		} else {
 
- 			ids, err := setting.SnowIds.NextId()
 
- 			if err != nil {
 
- 				ids = time.Now().UnixNano()
 
- 				logging.Info("create SnowIds err", err)
 
- 			}
 
- 			_, err = tx.SQL("insert into feedclass(id,pastureid,fccode,fcname,bigfeedclassname,bigfeedclassid,sort)VALUES(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from feedclass f  where f.pastureid =? ))",
 
- 				ids, pastureid, fclass, fclass, fclass, ids, pastureid).Execute()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeed-error-4:", err)
 
- 				return
 
- 			}
 
- 			fclassid = ids
 
- 		}
 
- 		ids, err := setting.SnowIds.NextId()
 
- 		if err != nil {
 
- 			ids = time.Now().UnixNano()
 
- 			logging.Info("create SnowIds err", err)
 
- 		}
 
- 		insertSql := `insert into feed(id,pastureid,feedcode,fname,fclassid,fclass,dry)VALUES(?,?,?,?,?,?,?) 
 
- 		ON DUPLICATE KEY UPDATE fname = ? ,dry = ? `
 
- 		_, err = tx.SQL(insertSql, ids, pastureid, feedcode, fname, fclassid, fclass, dry, fname, dry).Execute()
 
- 		if err != nil {
 
- 			tx.Rollback()
 
- 			logs.Error("syncFeed-error-5:", err)
 
- 			return
 
- 		}
 
- 	}
 
- 	err = tx.Commit()
 
- 	if err != nil {
 
- 		tx.Rollback()
 
- 		logs.Error("syncFeed-error-6:", err)
 
- 		return
 
- 	}
 
- 	return
 
- }
 
- func (h *ScheduledDown) SyncFeedp(pastureid string, feedpList []interface{}) error {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	err := tx.Begin()
 
- 	if err != nil {
 
- 		logs.Error("syncFeedp-error-1:", err)
 
- 		return err
 
- 	}
 
- 	for _, f := range feedpList {
 
- 		feedp := f.(map[string]interface{})
 
- 		var barName, barCode, feedtempletCode, barId interface{}
 
- 		var ftId, tname interface{}
 
- 		var cowCount interface{}
 
- 		if _, ok := feedp["barname"]; ok {
 
- 			barName = feedp["barname"]
 
- 		}
 
- 		if _, ok := feedp["barcode"]; ok {
 
- 			barCode = feedp["barcode"]
 
- 		}
 
- 		if _, ok := feedp["cowcount"]; ok {
 
- 			cowCount = feedp["cowcount"]
 
- 		}
 
- 		if _, ok := feedp["feedtempletcode"]; ok {
 
- 			feedtempletCode = feedp["feedtempletCode"]
 
- 		}
 
- 		barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barCode).Count()
 
- 		if err != nil {
 
- 			tx.Rollback()
 
- 			logs.Error("syncFeedp-error-2:", err)
 
- 			return err
 
- 		}
 
- 		if barCount > 0 {
 
- 			barDataList, err := tx.SQL(" select id from bar where pastureid = ? and bcode = ?", pastureid, barCode).QueryString()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeedp-error-3:", err)
 
- 				return err
 
- 			}
 
- 			for _, barData := range barDataList {
 
- 				barId = barData["id"]
 
- 			}
 
- 		} else {
 
- 			barReq, err := tx.SQL("insert into bar(pastureid,bname,bcode)VALUES(?,?,?)", pastureid, barName, barCode).Execute()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeedp-error-4:", err)
 
- 				return err
 
- 			}
 
- 			id, err := barReq.LastInsertId()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeedp-error-5:", err)
 
- 				return err
 
- 			}
 
- 			barId = strconv.FormatInt(id, 10)
 
- 		}
 
- 		if feedtempletCode != "" {
 
- 			feedtempletDataList, err := tx.SQL(" select id,tname from feedtemplet where pastureid = ? and tcode = ?", pastureid, feedtempletCode).QueryString()
 
- 			if err != nil {
 
- 				tx.Rollback()
 
- 				logs.Error("syncFeedp-error-6:", err)
 
- 				return err
 
- 			}
 
- 			for _, feedtemplet := range feedtempletDataList {
 
- 				ftId = feedtemplet
 
- 				tname = feedtemplet
 
- 			}
 
- 		}
 
- 		insertSql := `insert into feedp(pastureid,barname,barid,ccount,ftid,ftname)VALUES(?,?,?,?,?,?) 
 
- 		ON DUPLICATE KEY UPDATE ccount = ? ,ftid = ? ,ftname = ? `
 
- 		_, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, ftId, tname, cowCount, ftId, tname).Execute()
 
- 		if err != nil {
 
- 			tx.Rollback()
 
- 			logs.Error("syncFeedp-error-7:", err)
 
- 			return err
 
- 		}
 
- 	}
 
- 	err = tx.Commit()
 
- 	if err != nil {
 
- 		tx.Rollback()
 
- 		logs.Error("syncFeedp-error-8:", err)
 
- 		return err
 
- 	}
 
- 	return nil
 
- }
 
- func wxPush(target []string, content []interface{}, pastureId string, serviceId int64) {
 
- 	url := "http://tmrwatch.cn/notice/message"
 
- 	dataStr := `{
 
- 		"pasture_id":%s,
 
- 		"service_id":%d,
 
- 		"sys_name": "tmrWatch",
 
- 		"target": %s,
 
- 		"miniprogram": {
 
- 			"appid": "wx9ab2b5b25701da0a",
 
- 			"pagepath": "pages/login/login"
 
- 		},
 
- 		"keys": [
 
- 			"first",
 
- 			"keyword1",
 
- 			"keyword2",
 
- 			"remark"
 
- 		],
 
- 		"content":%s
 
- 	}`
 
- 	targetStr, _ := json.Marshal(target)
 
- 	contentStr, _ := json.Marshal(content)
 
- 	dataStr = fmt.Sprintf(dataStr, pastureId, serviceId, string(targetStr), string(contentStr))
 
- 	fmt.Println(dataStr)
 
- 	var jsonStr = []byte(dataStr)
 
- 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
 
- 	req.Header.Set("Content-Type", "application/json")
 
- 	client := &http.Client{}
 
- 	resp, err := client.Do(req)
 
- 	if err != nil {
 
- 		logs.Error(err)
 
- 	}
 
- 	defer resp.Body.Close()
 
- }
 
- func UDPostPush1(data, method string) {
 
- 	url := "https://wdc.unidairy.cn/copartner_uploads/"
 
- 	// 超时时间:5秒
 
- 	var jsonStr = []byte(data)
 
- 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
 
- 	fmt.Println(string(jsonStr))
 
- 	req.Header.Set("Content-Type", "application/json")
 
- 	client := &http.Client{}
 
- 	resp, err := client.Do(req)
 
- 	if err != nil {
 
- 		logs.Error(err)
 
- 	}
 
- 	defer resp.Body.Close()
 
- 	body, _ := ioutil.ReadAll(resp.Body)
 
- 	fmt.Println("response Body:", string(body))
 
- 	// file, err := os.Create("example.txt")
 
- 	// if err != nil {
 
- 	// 	fmt.Println(err)
 
- 	// 	return
 
- 	// }
 
- 	// defer file.Close()
 
- 	// // 创建一个写入器并将其与文件关联
 
- 	// writer := bufio.NewWriter(file)
 
- 	// // 将字符串写入缓冲区
 
- 	// // str := "Hello, world!"
 
- 	// _, err = writer.WriteString(data)
 
- 	// if err != nil {
 
- 	// 	fmt.Println(err)
 
- 	// 	return
 
- 	// }
 
- 	// // 刷新缓冲区,确保所有数据都已成功写入文件
 
- 	// err = writer.Flush()
 
- 	// if err != nil {
 
- 	// 	fmt.Println(err)
 
- 	// 	return
 
- 	// }
 
- 	logging.Info("response Body:", string(body))
 
- }
 
- func processAnalysisEarlyWarning(target []string, pastureId string, serviceId int64) {
 
- 	tx2 := restful.Engine.NewSession()
 
- 	defer tx2.Close()
 
- 	exist, err := tx2.Table("notice").Where("status = 1").And("content = ? ", "downloadplandtl1").Exist()
 
- 	if err != nil {
 
- 		logs.Error("processAnalysisEarlyWarning-error-1:", err)
 
- 		return
 
- 	}
 
- 	if exist {
 
- 		_, err := tx2.SQL(`update notice set status = 0  where content =  ? `, "downloadplandtl1").Execute()
 
- 		if err != nil {
 
- 			logs.Error("processAnalysisEarlyWarning-error-2:", err)
 
- 			return
 
- 		}
 
- 		dataList, err := tx2.SQL("select * from downloadplandtl1_log  where date = date_format(now(),'%Y-%m-%d') ").Query().List()
 
- 		if err != nil {
 
- 			logs.Error("processAnalysisEarlyWarning-error-3:", err)
 
- 			return
 
- 		}
 
- 		plandtl1SlIdMap := make(map[string][]int64, 0)
 
- 		// plandtl1HlIdMap := make(map[string][]string, 0)
 
- 		for _, data := range dataList {
 
- 			if data["type"].(int64) == 0 && data["plandtl1"] != nil {
 
- 				plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], data["plandtl1"].(int64))
 
- 			} else if data["type"].(int64) == 1 && data["plandtl1"] != nil {
 
- 				plandtl1SlIdMap["slplanid"] = append(plandtl1SlIdMap["slplanid"], data["plandtl1"].(int64))
 
- 			}
 
- 		}
 
- 		pastureList, err := tx2.SQL("select pasture_name from pasture  where pastureid = ? ", pastureId).Query().List()
 
- 		if err != nil {
 
- 			logs.Error("processAnalysisEarlyWarning-error-4:", err)
 
- 			return
 
- 		}
 
- 		var pastureName string
 
- 		for _, pasture := range pastureList {
 
- 			pastureName = pasture["pasture_name"].(string)
 
- 		}
 
- 		for _, data := range dataList {
 
- 			if data["type"].(int64) == 0 {
 
- 				plandtl1List, err := tx2.SQL(`select d.remark,d.projname,d1.fname,d.tmrtname,DATE_FORMAT(d1.intime, '%Y-%m-%d %H:%i:%S') as intime,d1.id,d1.feedallowratio,abs(d1.actualweightminus -d1.lweight ) errorvalue ,d1.actualweightminus,d1.lweight,
 
- 					if(d1.actualweightminus <= d1.lweight,ROUND(d1.actualweightminus/d1.lweight* 100,2),ROUND(d1.lweight/d1.actualweightminus* 100,2) ) as accuracy  from
 
- 					downloadplandtl1 d1
 
- 					join downloadedplan d on d.id = d1.pid
 
- 					where d1.pid = ?  and d1.sort = ?  and  d1.pastureid = ? and d1.intime is not null and d1.type = 0 `,
 
- 					data["planid"], data["sort"], data["pastureid"]).Query().List()
 
- 				if err != nil {
 
- 					logs.Error("processAnalysisEarlyWarning-error-5:", err)
 
- 					return
 
- 				}
 
- 				for _, plandtl1 := range plandtl1List {
 
- 					idexist := false
 
- 					//防止同顺序饲料多次推送
 
- 					for _, plandtl1Id := range plandtl1SlIdMap["planid"] {
 
- 						if plandtl1Id == plandtl1["id"].(int64) {
 
- 							idexist = true
 
- 							break
 
- 						}
 
- 					}
 
- 					if idexist {
 
- 						continue
 
- 					}
 
- 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
 
- 					if plandtl1["feedallowratio"].(float64) < errorvalue {
 
- 						var sendList []interface{}
 
- 						sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
 
- 							plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
 
- 						sendMap1 := make(map[string]interface{}, 0)
 
- 						sendMap1["value"] = "混料准确率异常"
 
- 						sendMap1["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap1)
 
- 						sendMap4 := make(map[string]interface{}, 0)
 
- 						sendMap4["value"] = sendStr
 
- 						sendMap4["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap4)
 
- 						sendMap2 := make(map[string]interface{}, 0)
 
- 						sendMap2["value"] = plandtl1["intime"]
 
- 						sendMap2["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap2)
 
- 						sendMap5 := make(map[string]interface{}, 0)
 
- 						sendMap5["value"] = "无备注"
 
- 						sendMap5["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap5)
 
- 						wxPush(target, sendList, pastureId, serviceId)
 
- 					}
 
- 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
 
- 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ?  and type =  0 ", plandtl1["id"], data["id"]).Execute()
 
- 					if err != nil {
 
- 						logs.Error("processAnalysisEarlyWarning-error-6:", err)
 
- 						return
 
- 					}
 
- 				}
 
- 			} else {
 
- 				plandtl1List, err := tx2.SQL(`select  d.remark,d2.id,d.projname,d2.fname,d.tmrtname,d2.id,ifnull(d2.allowratio,0) allowratio ,abs(d2.actualweightminus -d2.lweight ) errorvalue ,DATE_FORMAT(d2.intime, '%Y-%m-%d %H:%i:%S') as intime ,d2.actualweightminus,d2.lweight,
 
- 					if(d2.actualweightminus <= d2.lweight,ROUND(d2.actualweightminus/d2.lweight* 100,2),ROUND(d2.lweight/d2.actualweightminus* 100,2) ) as accuracy
 
- 				 from 	downloadplandtl2 d2
 
- 					join downloadedplan d on d.id = d2.pid
 
- 					where d2.pid = ?  and d2.sort = ?  and  d2.pastureid = ? and d2.intime is not null and d2.type = 0 `,
 
- 					data["planid"], data["sort"], data["pastureid"]).Query().List()
 
- 				// Where(" pid = ? ", data["planid"]).And("sort = ? ", data["sort"]).And(" pastureid = ? ", data["pastureid"]).And(" intime is not null").And("type = 0 ").Query().List()
 
- 				if err != nil {
 
- 					logs.Error("processAnalysisEarlyWarning-error-7:", err)
 
- 					return
 
- 				}
 
- 				for _, plandtl1 := range plandtl1List {
 
- 					idexist := false
 
- 					//防止同顺序饲料多次推送
 
- 					for _, plandtl1Id := range plandtl1SlIdMap["slplanid"] {
 
- 						if plandtl1Id == plandtl1["id"].(int64) {
 
- 							idexist = true
 
- 							break
 
- 						}
 
- 					}
 
- 					if idexist {
 
- 						continue
 
- 					}
 
- 					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)
 
- 					if float64(plandtl1["allowratio"].(int64)) < errorvalue && float64(plandtl1["allowratio"].(int64)) != 0 {
 
- 						fmt.Println(plandtl1, "推送")
 
- 						var sendList []interface{}
 
- 						sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n栏舍名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n误差值(kg):%v\n准确率(%%):%v",
 
- 							plandtl1["projname"], pastureName, plandtl1["tmrtname"], plandtl1["remark"], plandtl1["fname"], plandtl1["lweight"], plandtl1["actualweightminus"], plandtl1["errorvalue"], plandtl1["accuracy"])
 
- 						sendMap1 := make(map[string]interface{}, 0)
 
- 						sendMap1["value"] = "撒料准确率异常"
 
- 						sendMap1["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap1)
 
- 						sendMap4 := make(map[string]interface{}, 0)
 
- 						sendMap4["value"] = sendStr
 
- 						sendMap4["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap4)
 
- 						sendMap2 := make(map[string]interface{}, 0)
 
- 						sendMap2["value"] = plandtl1["intime"]
 
- 						sendMap2["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap2)
 
- 						sendMap5 := make(map[string]interface{}, 0)
 
- 						sendMap5["value"] = "无备注"
 
- 						sendMap5["color"] = "#173177"
 
- 						sendList = append(sendList, sendMap5)
 
- 						wxPush(target, sendList, pastureId, serviceId)
 
- 					}
 
- 					plandtl1SlIdMap["planid"] = append(plandtl1SlIdMap["planid"], plandtl1["id"].(int64))
 
- 					_, err := tx2.SQL(" update downloadplandtl1_log set plandtl1 = ? where id = ? and type = 1 ", plandtl1["id"], data["id"]).Execute()
 
- 					if err != nil {
 
- 						logs.Error("processAnalysisEarlyWarning-error-8:", err)
 
- 						return
 
- 					}
 
- 				}
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func manualUdData(pastureinfo *udPastureInfo) {
 
- 	c := cron.New()
 
- 	c.AddFunc("10 06 * * *", func() {
 
- 		tx := restful.Engine.NewSession()
 
- 		defer tx.Close()
 
- 		now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
 
- 		// now := "2023-02-22"
 
- 		dataList, err := tx.SQL(" select id  from downloadedplan where mydate = ? ", now).QueryString()
 
- 		if err != nil {
 
- 			logging.Error("manualUdData-error-1:", err)
 
- 			return
 
- 		}
 
- 		var idList []string
 
- 		for _, data := range dataList {
 
- 			idList = append(idList, data["id"])
 
- 		}
 
- 		upList := make([]*ScheduledUpInfo, 0)
 
- 		up := tx.Table("scheduled_up")
 
- 		up.Where("company = ? ", "ud")
 
- 		up.Where("datatype in (3,4)")
 
- 		up.Where("automatic = 1")
 
- 		err = up.Find(&upList)
 
- 		if err != nil {
 
- 			logging.Error("manualUdData-error-2: ", err)
 
- 			return
 
- 		}
 
- 		for _, item := range upList {
 
- 			if item.Datasql != "" {
 
- 				// if item.Datatype == 4 {
 
- 				targetdataList := strings.Split(item.Targetdata, ",")
 
- 				var args []interface{}
 
- 				for _, targetdata := range targetdataList {
 
- 					if targetdata == "pastureid" {
 
- 						args = append(args, pastureinfo.Pastureid)
 
- 					} else if targetdata == "idlist" {
 
- 						item.Datasql = strings.ReplaceAll(item.Datasql, "idlist", strings.Join(idList, ","))
 
- 					} else if targetdata == "date" {
 
- 						args = append(args, now)
 
- 					}
 
- 				}
 
- 				data, err := tx.SQL(item.Datasql, args...).Query().List()
 
- 				if err != nil {
 
- 					logging.Error("manualUdData-error-3: ", err)
 
- 					continue
 
- 				}
 
- 				if len(data) > 0 {
 
- 					databyte, err := json.Marshal(data)
 
- 					if err != nil {
 
- 						logging.Error("manualUdData-error-4: ", err)
 
- 						continue
 
- 					}
 
- 					var method string
 
- 					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)
 
- 				}
 
- 				// }
 
- 			}
 
- 		}
 
- 	})
 
- 	c.Start()
 
- }
 
- func abnormalMixingDelay(target []string, pastureId string, serviceId int64) {
 
- 	tx2 := restful.Engine.NewSession()
 
- 	defer tx2.Close()
 
- 	now := time.Now().Format("2006-01-02")
 
- 	dataList, err := tx2.SQL(` select  id,planid,sort from downloadplandtl1_log   where abnormalMixingDelay = 0 and type = 0 and  pastureid = ?  and date = ? `, pastureId, now).Query().List()
 
- 	if err != nil {
 
- 		logs.Error("abnormalMixingDelay-error-1:", err)
 
- 		return
 
- 	}
 
- 	if len(dataList) <= 0 {
 
- 		return
 
- 	}
 
- 	local, _ := time.LoadLocation("Asia/Shanghai")
 
- 	for _, data := range dataList {
 
- 		planList, err := tx2.SQL(`select  de.deviation,de.lweight,de.fname,de.processtime,de.stirdelay,d.tmrtname, d.projname, CONCAT(d.templetname,projname) as name ,
 
- 		d.datacaptureno,(select pasture_name from  pasture   where pastureid = ?) as pasturename,de.actualweightminus  from downloadplandtl1_exec  de 
 
- 		join downloadedplan  d  on de.pid = d.id   where de.pid = ? and de.sort = ? `, pastureId, data["planid"], data["sort"]).Query().List()
 
- 		if err != nil {
 
- 			logs.Error("abnormalMixingDelay-error-2:", err)
 
- 			return
 
- 		}
 
- 		for _, plan := range planList {
 
- 			showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", time.Now().Format("2006-01-02"), plan["processtime"]), local)
 
- 			nowTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")), local)
 
- 			if (showTime.Unix()-nowTime.Unix())/60 < plan["stirdelay"].(int64)-plan["deviation"].(int64) || (showTime.Unix()-nowTime.Unix())/60 > plan["stirdelay"].(int64)+plan["deviation"].(int64) {
 
- 				var sendList []interface{}
 
- 				sendStr := fmt.Sprintf("操作编号:%v\n牧场:%s\nTMR名称:%v\n描述:%v\n饲料名称:%v\n计划重量(kg):%v\n实际重量(kg):%v\n过程时间:%v",
 
- 					plan["projname"], plan["pasturename"], plan["tmrtname"], plan["name"], plan["fname"], plan["lweight"], plan["actualweightminus"], plan["processtime"])
 
- 				sendMap1 := make(map[string]interface{}, 0)
 
- 				sendMap1["value"] = "混料搅拌延时异常"
 
- 				sendMap1["color"] = "#173177"
 
- 				sendList = append(sendList, sendMap1)
 
- 				sendMap4 := make(map[string]interface{}, 0)
 
- 				sendMap4["value"] = sendStr
 
- 				sendMap4["color"] = "#173177"
 
- 				sendList = append(sendList, sendMap4)
 
- 				sendMap2 := make(map[string]interface{}, 0)
 
- 				sendMap2["value"] = plan["processtime"]
 
- 				sendMap2["color"] = "#173177"
 
- 				sendList = append(sendList, sendMap2)
 
- 				sendMap5 := make(map[string]interface{}, 0)
 
- 				sendMap5["value"] = "无备注"
 
- 				sendMap5["color"] = "#173177"
 
- 				sendList = append(sendList, sendMap5)
 
- 				wxPush(target, sendList, pastureId, serviceId)
 
- 			}
 
- 			_, err := tx2.SQL(` update downloadplandtl1_log set abnormalMixingDelay = 1 where id = ? `, data["id"]).Execute()
 
- 			if err != nil {
 
- 				logs.Error("abnormalMixingDelay-error-3:", err)
 
- 				return
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func endOfShift(target []string, pastureId string, serviceId int64) {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	now := time.Now().Format("2006-01-02")
 
- 	logList, err := tx.SQL(` select times from downloadedplan_log  where date = ? and classes = 0 group by times `, now).Query().List()
 
- 	if err != nil {
 
- 		logs.Error("endOfShift-error-1:", err)
 
- 		return
 
- 	}
 
- 	for _, item := range logList {
 
- 		exist, err := tx.SQL(` select id from downloadedplan  where mydate = ? and times = ? and iscompleted = 0  and enable = 1 `, now, item["times"]).Exist()
 
- 		if err != nil {
 
- 			logs.Error("endOfShift-error-2:", err)
 
- 			return
 
- 		}
 
- 		if !exist {
 
- 			hlList, err := tx.SQL(` select ( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
 
- 			sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
 
- 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 
- 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 
- 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
 
- 			round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0)  processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
 
- 			from downloadedplan d  
 
- 			join downloadplandtl1_exec  de on de.pid = d.id   
 
- 			where d.times = ? and d.mydate = ?  and lpplantype in(0,1)  group by d.times`, item["times"], now).Query().List()
 
- 			if err != nil {
 
- 				logs.Error("endOfShift-error-3:", err)
 
- 				return
 
- 			}
 
- 			slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
 
- 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 
- 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 
- 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
 
- 			round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
 
- 			from downloadedplan d  
 
- 			join downloadplandtl2  de on de.pid = d.id   
 
- 			where d.times = ? and d.mydate = ?  and lpplantype in(0,2)  group by d.times `, item["times"], now).Query().List()
 
- 			if err != nil {
 
- 				logs.Error("endOfShift-error-4:", err)
 
- 				return
 
- 			}
 
- 			data := make(map[string]interface{})
 
- 			for _, hl := range hlList {
 
- 				data["cltrains"] = hl["cltrains"]
 
- 				// data["hllweight"] = hl["lweight"]
 
- 				data["hlactualweightminus"] = hl["actualweightminus"]
 
- 				data["hlaccurate"] = hl["accurate"]
 
- 				data["hlcorrect"] = hl["correct"]
 
- 				data["hlcorrectcount"] = hl["correctcount"]
 
- 				// data["hlprocesstime"] = util.TimeTransformation(hl["processtime"].(int64))
 
- 				data["hlwcz"] = hl["wcz"]
 
- 			}
 
- 			for _, sl := range slList {
 
- 				// data["sllweight"] = sl["lweight"]
 
- 				data["slactualweightminus"] = sl["actualweightminus"]
 
- 				data["slaccurate"] = sl["accurate"]
 
- 				data["slcorrect"] = sl["correct"]
 
- 				data["slcorrectcount"] = sl["correctcount"]
 
- 				// data["slprocesstime"] = util.TimeTransformation(sl["processtime"].(int64))
 
- 				data["slwcz"] = sl["wcz"]
 
- 			}
 
- 			sendStr := fmt.Sprintf("班次:%v\n车次数:%v\n实际混料(kg):%v\n混料误差值(kg):%v\n混料准确率:%v\n混料正确数:%v\n混料正确率:%v\n实际撒料(kg):%v\n撒料误差值(kg):%v\n撒料准确率:%v\n撒料正确数:%v\n撒料正确率:%v",
 
- 				item["times"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
 
- 				data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
 
- 			var sendList []interface{}
 
- 			sendMap1 := make(map[string]interface{}, 0)
 
- 			sendMap1["value"] = "班次完成"
 
- 			sendMap1["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap1)
 
- 			sendMap4 := make(map[string]interface{}, 0)
 
- 			sendMap4["value"] = sendStr
 
- 			sendMap4["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap4)
 
- 			sendMap2 := make(map[string]interface{}, 0)
 
- 			// sendMap2["value"] = plan["processtime"]
 
- 			sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
 
- 			sendMap2["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap2)
 
- 			sendMap5 := make(map[string]interface{}, 0)
 
- 			sendMap5["value"] = "无备注"
 
- 			sendMap5["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap5)
 
- 			wxPush(target, sendList, pastureId, serviceId)
 
- 			_, err = tx.SQL(` update downloadedplan_log set classes = 1 where date = ? and times = ? `, now, item["times"]).Execute()
 
- 			if err != nil {
 
- 				logs.Error("endOfShift-error-5:", err)
 
- 				return
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func plansToComplete(target []string, pastureId string, serviceId int64) {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	now := time.Now()
 
- 	exist, err := tx.SQL(` select id from downloadedplan_log  where date = ? and dailyplan = 0 `, now).Exist()
 
- 	if err != nil {
 
- 		logs.Error("plansToComplete-error-1:", err)
 
- 		return
 
- 	}
 
- 	if exist {
 
- 		downloadedplanExist, err := tx.SQL(` select id from downloadedplan  where mydate = ?  and iscompleted = 0  and enable = 1 `, now).Exist()
 
- 		if err != nil {
 
- 			logs.Error("plansToComplete-error-2:", err)
 
- 			return
 
- 		}
 
- 		if !downloadedplanExist {
 
- 			hlList, err := tx.SQL(` select (select count(a.id) from (	select id from  downloadedplan where mydate = ? GROUP BY times) as a  ) as timescount ,( select count(1) from downloadedplan where times = d.times and mydate = d.mydate ) as cltrains,
 
- 			sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
 
- 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 
- 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 
- 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.feedallowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
 
- 			round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0)  processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
 
- 			from downloadedplan d
 
- 			join downloadplandtl1_exec  de on de.pid = d.id
 
- 			where  d.mydate = ?  and lpplantype in(0,1)  group by d.mydate`, now, now).Query().List()
 
- 			if err != nil {
 
- 				logs.Error("plansToComplete-error-3:", err)
 
- 				return
 
- 			}
 
- 			slList, err := tx.SQL(` select sum(de.lweight)lweight,sum(de.actualweightminus)actualweightminus  ,
 
- 			round(if(sum(de.lweight) < sum(de.actualweightminus),sum(de.lweight)/sum(de.actualweightminus) *100, sum(de.actualweightminus)/sum(de.lweight) *100),2)  as accurate,
 
- 			ROUND(IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0))/SUM(1),0)*100,2) correct,
 
- 			IFNULL(SUM(IF(ABS(de.actualweightminus-de.lweight)<=de.allowratio AND de.actualweightminus<>0,1,0)),0) correctcount,
 
- 			round( sum(UNIX_TIMESTAMP(concat("2022-01-01 ", de.processtime)) - UNIX_TIMESTAMP("2022-01-01 00:00:00") ),0) processtime ,abs(sum(de.actualweightminus)-sum(de.lweight)) as wcz
 
- 			from downloadedplan d
 
- 			join downloadplandtl2  de on de.pid = d.id
 
- 			where d.mydate = ?  and lpplantype in(0,2)  group by d.mydate `, now).Query().List()
 
- 			if err != nil {
 
- 				logs.Error("plansToComplete-error-4:", err)
 
- 				return
 
- 			}
 
- 			data := make(map[string]interface{})
 
- 			for _, hl := range hlList {
 
- 				data["timescount"] = hl["timescount"]
 
- 				data["cltrains"] = hl["cltrains"]
 
- 				data["hllweight"] = hl["lweight"]
 
- 				data["hlactualweightminus"] = hl["actualweightminus"]
 
- 				data["hlaccurate"] = hl["accurate"]
 
- 				data["hlcorrect"] = hl["correct"]
 
- 				data["hlcorrectcount"] = hl["correctcount"]
 
- 				data["hlwcz"] = hl["wcz"]
 
- 			}
 
- 			for _, sl := range slList {
 
- 				data["sllweight"] = sl["lweight"]
 
- 				data["slactualweightminus"] = sl["actualweightminus"]
 
- 				data["slaccurate"] = sl["accurate"]
 
- 				data["slcorrect"] = sl["correct"]
 
- 				data["slcorrectcount"] = sl["correctcount"]
 
- 				data["slwcz"] = sl["wcz"]
 
- 			}
 
- 			sendStr := fmt.Sprintf("班次数:%v\n车次数:\n实际混料(kg):%v\n混料误差值(kg):%v\n混料准确率:%v\n混料正确数:%v\n混料正确率:%v\n混料完成时间:%v\n实际撒料(kg):%v\n撒料误差值(kg):%v\n撒料准确率:%v\n撒料正确数:%v\n撒料正确率:%v",
 
- 				data["timescount"], data["cltrains"], data["hlactualweightminus"], data["hlwcz"], data["hlaccurate"], data["hlcorrect"], data["hlcorrectcount"],
 
- 				data["slactualweightminus"], data["slwcz"], data["slaccurate"], data["slcorrect"], data["slcorrectcount"])
 
- 			var sendList []interface{}
 
- 			sendMap1 := make(map[string]interface{}, 0)
 
- 			sendMap1["value"] = "每日计划完成"
 
- 			sendMap1["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap1)
 
- 			sendMap4 := make(map[string]interface{}, 0)
 
- 			sendMap4["value"] = sendStr
 
- 			sendMap4["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap4)
 
- 			sendMap2 := make(map[string]interface{}, 0)
 
- 			// sendMap2["value"] = plan["processtime"]
 
- 			sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
 
- 			sendMap2["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap2)
 
- 			sendMap5 := make(map[string]interface{}, 0)
 
- 			sendMap5["value"] = "无备注"
 
- 			sendMap5["color"] = "#173177"
 
- 			sendList = append(sendList, sendMap5)
 
- 			wxPush(target, sendList, pastureId, serviceId)
 
- 			_, err = tx.SQL(` update downloadedplan_log set dailyplan = 1 where date = ? `, now).Execute()
 
- 			if err != nil {
 
- 				logs.Error("plansToComplete-error-5:", err)
 
- 				return
 
- 			}
 
- 		}
 
- 	}
 
- }
 
- func AddFormulaIssued(c *gin.Context) {
 
- 	appG := app.Gin{C: c}
 
- 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 	tempval_ := make(map[string]interface{})
 
- 	tempCommon := make(map[string]interface{})
 
- 	tempval := make([]map[string]interface{}, 0)
 
- 	err := json.Unmarshal(dataByte, &tempval_)
 
- 	logging.Info("AddFormulaIssued ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
 
- 	if err != nil {
 
- 	} else {
 
- 		if v, ok := tempval_["data"].([]interface{}); ok {
 
- 			for _, Tvalue := range v {
 
- 				if v1, ok := Tvalue.(map[string]interface{}); ok {
 
- 					tempval = append(tempval, v1)
 
- 				}
 
- 			}
 
- 		}
 
- 		tx := restful.Engine.NewSession()
 
- 		err := tx.Begin()
 
- 		if err != nil {
 
- 			logging.Error("tx.Begin 事务启动失败__error:", err)
 
- 		}
 
- 		defer func() {
 
- 			switch {
 
- 			case err != nil:
 
- 				if tx != nil {
 
- 					tx.Rollback()
 
- 				}
 
- 			default:
 
- 				if tx != nil {
 
- 					err = tx.Commit()
 
- 				}
 
- 			}
 
- 			if tx != nil {
 
- 				tx.Close()
 
- 			}
 
- 		}()
 
- 		if err == nil {
 
- 			if tempv, exists := c.Get("jwt_username"); exists {
 
- 				tempCommon["jwt_username"] = tempv.(string)
 
- 			}
 
- 			for _, paramvalue := range tempval {
 
- 				if _, ok := paramvalue["resultname"]; !ok {
 
- 					paramvalue["resultname"] = paramvalue["name"]
 
- 				}
 
- 				_, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
 
- 				if err != nil {
 
- 					logging.Error("AddFormulaIssued error-1:", err)
 
- 					break
 
- 				}
 
- 			}
 
- 			if err == nil {
 
- 				var temid, jtpastureid, tcode, tname, ccname, fttype string
 
- 				for _, tem := range tempval {
 
- 					if tem["name"].(string) == "insertSpotList" {
 
- 						for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
 
- 							itemmap := item.(map[string]interface{})
 
- 							jtpastureid = itemmap["pastureid"].(string)
 
- 							temid = itemmap["id"].(string)
 
- 						}
 
- 					}
 
- 				}
 
- 				feedtempletList, err := tx.SQL(` select tname,tcode,id,ccname,fttype from feedtemplet where id = ? and pastureid = ?  `, temid, jtpastureid).Query().List()
 
- 				if err != nil {
 
- 					logs.Error("AddFormulaIssued-error-2:", err)
 
- 					return
 
- 				}
 
- 				for _, feedtemplet := range feedtempletList {
 
- 					tcode = feedtemplet["tcode"].(string)
 
- 					tname = feedtemplet["tname"].(string)
 
- 					ccname = feedtemplet["ccname"].(string)
 
- 					fttype = feedtemplet["fttype"].(string)
 
- 				}
 
- 				for _, tem := range tempval {
 
- 					if tem["name"].(string) == "insertSpotList2" {
 
- 						for _, item := range tem["resultmaps"].(map[string]interface{})["list"].([]interface{}) {
 
- 							itemmap := item.(map[string]interface{})
 
- 							dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, itemmap["id"], "formulaIssued").Query().List()
 
- 							if err != nil {
 
- 								logs.Error("AddFormulaIssued-error-3:", err)
 
- 								return
 
- 							}
 
- 							for _, data := range dataList {
 
- 								var openIdList []string
 
- 								if _, ok := data["user"]; ok {
 
- 									openIdList = strings.Split(data["user"].(string), ",")
 
- 								}
 
- 								var sendList []interface{}
 
- 								sendStr := fmt.Sprintf("配方名称:%v\n配方编码:%s\n牲畜类别:%v\n配方类型:%v",
 
- 									tname, tcode, ccname, fttype)
 
- 								sendMap1 := make(map[string]interface{}, 0)
 
- 								sendMap1["value"] = "混料准确率异常"
 
- 								sendMap1["color"] = "#173177"
 
- 								sendList = append(sendList, sendMap1)
 
- 								sendMap4 := make(map[string]interface{}, 0)
 
- 								sendMap4["value"] = sendStr
 
- 								sendMap4["color"] = "#173177"
 
- 								sendList = append(sendList, sendMap4)
 
- 								sendMap2 := make(map[string]interface{}, 0)
 
- 								sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
 
- 								sendMap2["color"] = "#173177"
 
- 								sendList = append(sendList, sendMap2)
 
- 								sendMap5 := make(map[string]interface{}, 0)
 
- 								sendMap5["value"] = "无备注"
 
- 								sendMap5["color"] = "#173177"
 
- 								sendList = append(sendList, sendMap5)
 
- 								wxPush(openIdList, sendList, itemmap["id"].(string), data["service_id"].(int64))
 
- 							}
 
- 						}
 
- 						break
 
- 					}
 
- 				}
 
- 				if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
 
- 					appG.Response(http.StatusOK, e.SUCCESS, tempval)
 
- 				} else {
 
- 					appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
 
- 				}
 
- 			} else {
 
- 				msg := geterrmsg(err.Error())
 
- 				appG.Response(http.StatusOK, e.ERROR, msg)
 
- 			}
 
- 		}
 
- 	}
 
- 	if err != nil {
 
- 		msg := geterrmsg(err.Error())
 
- 		appG.Response(http.StatusOK, e.ERROR, msg)
 
- 		appG.Response(http.StatusOK, 200, nil)
 
- 	}
 
- }
 
- func AddBigInventory(c *gin.Context) {
 
- 	appG := app.Gin{C: c}
 
- 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
 
- 	tempval_ := make(map[string]interface{})
 
- 	tempCommon := make(map[string]interface{})
 
- 	tempval := make([]map[string]interface{}, 0)
 
- 	err := json.Unmarshal(dataByte, &tempval_)
 
- 	logging.Info("AddBigInventory ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
 
- 	if err != nil {
 
- 	} else {
 
- 		if v, ok := tempval_["common"].(map[string]interface{}); ok {
 
- 			tempCommon = v
 
- 		}
 
- 		if v, ok := tempval_["data"].([]interface{}); ok {
 
- 			for _, Tvalue := range v {
 
- 				if v1, ok := Tvalue.(map[string]interface{}); ok {
 
- 					tempval = append(tempval, v1)
 
- 				}
 
- 			}
 
- 		}
 
- 		tx := restful.Engine.NewSession()
 
- 		err := tx.Begin()
 
- 		if err != nil {
 
- 			logging.Error("tx.Begin 事务启动失败__error:", err)
 
- 		}
 
- 		defer func() {
 
- 			switch {
 
- 			case err != nil:
 
- 				if tx != nil {
 
- 					tx.Rollback()
 
- 				}
 
- 			default:
 
- 				if tx != nil {
 
- 					err = tx.Commit()
 
- 				}
 
- 			}
 
- 			if tx != nil {
 
- 				tx.Close()
 
- 			}
 
- 		}()
 
- 		if err == nil {
 
- 			if tempv, exists := c.Get("jwt_username"); exists {
 
- 				tempCommon["jwt_username"] = tempv.(string)
 
- 			}
 
- 			for _, paramvalue := range tempval {
 
- 				if _, ok := paramvalue["resultname"]; !ok {
 
- 					paramvalue["resultname"] = paramvalue["name"]
 
- 				}
 
- 				_, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
 
- 				if err != nil {
 
- 					logging.Error("AddBigInventory error-1:", err)
 
- 					break
 
- 				}
 
- 			}
 
- 			if err == nil {
 
- 				var pastureid, date string
 
- 				for _, tem := range tempval {
 
- 					if tem["name"].(string) == "insertBigInventory" {
 
- 						parammaps := tem["parammaps"].(map[string]interface{})
 
- 						pastureid = parammaps["pastureid"].(string)
 
- 						date = parammaps["inventorydate"].(string)
 
- 					}
 
- 				}
 
- 				feedinventoryList, err := tx.SQL(`SELECT
 
- 				remark,DATE_FORMAT(inventorydate, '%Y-%m-%d') inventorydate,createuser,
 
- 				TRIM(f.id) id,
 
- 				TRIM(f.pastureid) pastureid,
 
- 				ifnull(round((select sum(theoryweight-factweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight>fd.factweight) ,2),0) lessWeight,
 
- 				ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<fd.factweight),2),0)  moreWeight ,
 
- 				ifnull(round((select sum(factweight-theoryweight) from feedinventorydetail fd where fd.pastureid and fd.invid = f.id and fd.theoryweight<>fd.factweight) ,2),0)  differWeight
 
- 				FROM
 
- 				  feedinventory f
 
- 				WHERE f.pastureid = ?  and f.inventorydate=? `, pastureid, date).Query().List()
 
- 				if err != nil {
 
- 					logs.Error("AddBigInventory-error-2:", err)
 
- 					return
 
- 				}
 
- 				dataList, err := tx.SQL(` select user,function,id,service_id from remind where pastureid = ? and function = ? `, pastureid, "formulaIssued").Query().List()
 
- 				if err != nil {
 
- 					logs.Error("AddBigInventory-error-3:", err)
 
- 					return
 
- 				}
 
- 				for _, data := range dataList {
 
- 					var openIdList []string
 
- 					if _, ok := data["user"]; ok {
 
- 						openIdList = strings.Split(data["user"].(string), ",")
 
- 					}
 
- 					var createuser, lessWeight, moreWeight, differWeight interface{}
 
- 					for _, f := range feedinventoryList {
 
- 						createuser = f["createuser"]
 
- 						lessWeight = f["lessWeight"]
 
- 						moreWeight = f["moreWeight"]
 
- 						differWeight = f["differWeight"]
 
- 					}
 
- 					var sendList []interface{}
 
- 					sendStr := fmt.Sprintf("盘点人:%v\n盘盈库存(kg):%v\n盘亏库存(kg):%v\n盈亏净值(kg):%v",
 
- 						createuser, moreWeight, lessWeight, differWeight)
 
- 					sendMap1 := make(map[string]interface{}, 0)
 
- 					sendMap1["value"] = "库存盘点"
 
- 					sendMap1["color"] = "#173177"
 
- 					sendList = append(sendList, sendMap1)
 
- 					sendMap4 := make(map[string]interface{}, 0)
 
- 					sendMap4["value"] = sendStr
 
- 					sendMap4["color"] = "#173177"
 
- 					sendList = append(sendList, sendMap4)
 
- 					sendMap2 := make(map[string]interface{}, 0)
 
- 					sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
 
- 					sendMap2["color"] = "#173177"
 
- 					sendList = append(sendList, sendMap2)
 
- 					sendMap5 := make(map[string]interface{}, 0)
 
- 					sendMap5["value"] = "无备注"
 
- 					sendMap5["color"] = "#173177"
 
- 					sendList = append(sendList, sendMap5)
 
- 					wxPush(openIdList, sendList, pastureid, data["service_id"].(int64))
 
- 				}
 
- 				if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
 
- 					appG.Response(http.StatusOK, e.SUCCESS, tempval)
 
- 				} else {
 
- 					appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
 
- 				}
 
- 			} else {
 
- 				msg := geterrmsg(err.Error())
 
- 				appG.Response(http.StatusOK, e.ERROR, msg)
 
- 			}
 
- 		}
 
- 	}
 
- 	if err != nil {
 
- 		msg := geterrmsg(err.Error())
 
- 		appG.Response(http.StatusOK, e.ERROR, msg)
 
- 	}
 
- }
 
- func inventoryWarning(target []string, pastureId string, serviceId int64) {
 
- 	tx := restful.Engine.NewSession()
 
- 	defer tx.Close()
 
- 	feedstorageList, err := tx.SQL(`
 
- 	SELECT
 
- 	(select fname  from feed where pastureid =fs.pastureid and id = fs.feedid ) feedname,
 
- 	fs.stockweight,round(fs.lweight,2) avgweight, if (fs.stockweight<=0,0, FLOOR(fs.stockweight/fs.lweight)) ldays,
 
- 	TRIM(fs.feedid) feedid,
 
- 	TRIM(fs.pastureid) pastureid,
 
- 	DATE_FORMAT((select max(date) from fswarnhis where pastureid = fs.pastureid and feedid = fs.feedid ), '%Y-%m-%d') lastdate
 
- 	FROM (SELECT  fs.pushstatus,
 
- 	fs.id,
 
- 	 fs.feedname,fs.stockweight,
 
- 	fs.feedid feedid,
 
- 	fs.pastureid pastureid,DATE_FORMAT(NOW(), '%Y-%m-%d') lastdate,
 
- 	(SELECT SUM(d.lweight)/7 lweight FROM downloadplandtl1 d WHERE d.pastureid = fs.pastureid
 
- 	AND date >= DATE_FORMAT(DATE_ADD(NOW(),INTERVAL -7 DAY), '%Y-%m-%d')
 
- 	AND date <DATE_FORMAT(NOW(), '%Y-%m-%d') AND d.fid = fs.feedid) lweight
 
- 	FROM feedstorage  fs) fs
 
- 	WHERE  fs.pastureid=? AND fs.stockweight< fs.lweight*(SELECT inforvalue FROM sysopt WHERE sysopt.pastureid = fs.pastureid
 
- 	 AND inforname = 'repertoryWarn')
 
- 	ORDER BY ldays ,stockweight `).Query().List()
 
- 	if err != nil {
 
- 		logs.Error("inventoryWarning-error-1:", err)
 
- 		return
 
- 	}
 
- 	for _, f := range feedstorageList {
 
- 		var sendList []interface{}
 
- 		sendStr := fmt.Sprintf("饲料名称:%v\n库存量(kg):%s\n近7天平均计划量:%v\n剩余使用天数:%v",
 
- 			f["feedname"], f["stockweight"], f["lweight"], f["ldays"])
 
- 		sendMap1 := make(map[string]interface{}, 0)
 
- 		sendMap1["value"] = "库存预警"
 
- 		sendMap1["color"] = "#173177"
 
- 		sendList = append(sendList, sendMap1)
 
- 		sendMap4 := make(map[string]interface{}, 0)
 
- 		sendMap4["value"] = sendStr
 
- 		sendMap4["color"] = "#173177"
 
- 		sendList = append(sendList, sendMap4)
 
- 		sendMap2 := make(map[string]interface{}, 0)
 
- 		sendMap2["value"] = time.Now().Format("2006-01-02 15:04:05")
 
- 		sendMap2["color"] = "#173177"
 
- 		sendList = append(sendList, sendMap2)
 
- 		sendMap5 := make(map[string]interface{}, 0)
 
- 		sendMap5["value"] = "无备注"
 
- 		sendMap5["color"] = "#173177"
 
- 		sendList = append(sendList, sendMap5)
 
- 		wxPush(target, sendList, pastureId, serviceId)
 
- 	}
 
- }
 
 
  |