| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300 | package apiimport (	"bytes"	"context"	"encoding/json"	"fmt"	"io/ioutil"	"log"	"net/http"	"os"	"reflect"	"strconv"	"strings"	"time"	"tmr-watch/conf/setting"	"tmr-watch/http/handle/gm"	"tmr-watch/http/handle/jpud"	"tmr-watch/http/handle/restful"	"tmr-watch/http/handle/sap"	"tmr-watch/http/handle/ymy"	"tmr-watch/pkg/app"	"tmr-watch/pkg/e"	"tmr-watch/pkg/logging"	// "../../routers/api/gm"	// "../../routers/api/sap"	// "../../routers/restful"	"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,(select werks from pasture where pastureid = column_default)  werks  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()	// 0 无同步 1 圣牧 2 现代牧业 3 新希望 4 乐源 5 光明ud 6 多语言京鹏ud 7 一牧云	if setting.ServerSetting.SyncStatus == 1 {		// 圣牧		manualUdData(pastureinfo)		InitMqttClient()	} else if setting.ServerSetting.SyncStatus == 2 {		xdmy := cron.New()		err = xdmy.AddFunc("0 05 7 * * *", func() {			// 现代牧业sap同步			sap.SyncMaterialOutbound()			sap.SyncSurplusOutbound()			sap.SyncLeftoverEntry()			// sap.SyncWasteuse()		})		xdmy.Start()		InitMqttClient()	} else if setting.ServerSetting.SyncStatus == 3 {		duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)		duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)		spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))		xxw := cron.New()		xxw.AddFunc(spec2, func() {			XxwFeedtemplet(pastureinfo.Pastureid)			xxwFeedpSync(pastureinfo.Pastureid)		})		xxw.Start()	} else if setting.ServerSetting.SyncStatus == 4 {		duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)		duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)		spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))		ly := cron.New()		ly.AddFunc(spec2, func() {			XxwFeedtemplet(pastureinfo.Pastureid)			xxwFeedpSync(pastureinfo.Pastureid)		})		ly.Start()	} else if setting.ServerSetting.SyncStatus == 5 {		gmud := cron.New()		err = gmud.AddFunc("0 05 7 * * *", func() {			gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)		})		gmud.Start()	} else if setting.ServerSetting.SyncStatus == 6 {		jp := cron.New()		err = jp.AddFunc("0 05 7 * * *", func() {			jpud.JPUDUdSync(pastureinfo.Pastureid, pastureinfo.Werks)		})		jp.Start()	} else if setting.ServerSetting.SyncStatus == 7 {		c := cron.New()		err = c.AddFunc("0 05 7 * * *", func() {			ymy.YmyCron(pastureinfo.Werks, pastureinfo.Pastureid)		})		c.Start()	} else if setting.ServerSetting.SyncStatus == 8 {		InitMqttClient()	}	// manualUdData(pastureinfo)	// //圣牧自动同步前天有进行中的任务	// manualUdData(pastureinfo)	// gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)	// jpud.UdBarSync(pastureinfo.Pastureid, pastureinfo.Werks)	// jpud.UdFeedSync(pastureinfo.Pastureid, pastureinfo.Werks)	// xdmy := cron.New()	// err = xdmy.AddFunc("0 05 7 * * *", func() {	// 	// 	// 	// 	//现代牧业sap同步	// sap.SyncMaterialOutbound()	// 	sap.SyncSurplusOutbound()	// 	sap.SyncLeftoverEntry()	// 	sap.SyncWasteuse()	// 	// 	// 	// 	// 光明ud同步	// 	// 	// 	fmt.Println(time.Now())	// 	// gm.GmUdSync(pastureinfo.Pastureid, pastureinfo.Werks)	// 	// jpud.JPUDUdSync(pastureinfo.Pastureid, pastureinfo.Werks)	// })	// xdmy.Start()	// InitMqttClient()	// yq.YqCron()	//新希望配方同步定时任务	// duetimecst4, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)	// duetimecst5, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)	// spec2 := fmt.Sprintf("@every %v", duetimecst4.Sub(duetimecst5))	// xxw := cron.New()	// xxw.AddFunc(spec2, func() {	// 	XxwFeedtemplet(pastureinfo.Pastureid)	// 	xxwFeedpSync(pastureinfo.Pastureid)	// 	// windows指定要删除文件的目录	// })	// xxw.Start()}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 不存在则Createfunc 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()		fmt.Println(feedcode, fname, fclassid)		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 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,softccount)VALUES(?,?,?,?)		// ON DUPLICATE KEY UPDATE softccount = ?  `		// _, err = tx.SQL(insertSql, pastureid, barName, barId, cowCount, cowCount).Execute()		fmt.Println(barCode)		_, err = tx.SQL(`update feedp fp set fp.softccount = ? where  (select bcode from bar where id = fp.barid ) = ? `, cowCount, barName).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	// }`	dataStr := `{		  "msg_type_id": 0,		  "pasture_id": %s,		  "service_id": %d,		  "sys_name": "tmrWatch",				  "miniprogram": {		    "appid": "wx9ab2b5b25701da0a",		    "pagepath": "pages/login/login"		  },		  "target": %s,		  "keys": [		    "thing5",		    "thing2",		    "thing16",		    "thing36",		    "thing45"		  ],		  "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)		return	}	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))	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 ,round(d1.actualweightminus,2)actualweightminus,				round(d1.lweight,2) 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					}					if _, ok := plandtl1["errorvalue"]; !ok {						continue					}					errorvalue, _ := strconv.ParseFloat(plandtl1["errorvalue"].(string), 64)					if _, ok := plandtl1["feedallowratio"]; ok {						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"] = fmt.Sprintf("%v%s", plandtl1["projname"], "混料准确率异常")							sendList = append(sendList, sendMap1)							sendMap2 := make(map[string]interface{}, 0)							sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])							sendList = append(sendList, sendMap2)							sendMap3 := make(map[string]interface{}, 0)							sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])							sendList = append(sendList, sendMap3)							sendMap4 := make(map[string]interface{}, 0)							sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])							sendList = append(sendList, sendMap4)							sendMap5 := make(map[string]interface{}, 0)							sendMap5["value"] = pastureName							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 ,round(d2.actualweightminus,2)actualweightminus,round(d2.lweight,2) 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 _, ok := plandtl1["allowratio"]; ok {						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)							sendMap1 := make(map[string]interface{}, 0)							sendMap1["value"] = fmt.Sprintf("%v%s", plandtl1["projname"], "撒料准确率异常")							sendList = append(sendList, sendMap1)							sendMap2 := make(map[string]interface{}, 0)							sendMap2["value"] = fmt.Sprintf("%v-%v", plandtl1["tmrtname"], plandtl1["fname"])							sendList = append(sendList, sendMap2)							sendMap3 := make(map[string]interface{}, 0)							sendMap3["value"] = fmt.Sprintf("计划%v,实际%v", plandtl1["lweight"], plandtl1["actualweightminus"])							sendList = append(sendList, sendMap3)							sendMap4 := make(map[string]interface{}, 0)							sendMap4["value"] = fmt.Sprintf("误差值%v,准确率%v", plandtl1["errorvalue"], plandtl1["accuracy"])							sendList = append(sendList, sendMap4)							sendMap5 := make(map[string]interface{}, 0)							sendMap5["value"] = pastureName							sendList = append(sendList, sendMap5)							wxPush(target, sendList, pastureId, serviceId)						}					}					if _, ok := plandtl1["id"]; ok {						if _, ok := data["id"]; ok {							fmt.Println(plandtl1["id"])							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,1)")		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					}					exist, err := tx.SQL(`select * from saplog where pastureId = ? and msgtype = ? and date_format(dataDate ,'%Y-%m-%d') = ?  `,						pastureinfo.Pastureid, item.Datatype, now).Exist()					if exist {						continue					}					tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)					values(?,?,?,?,?,now(),?,?,?)`, pastureinfo.Pastureid, string(databyte), "", "", "", item.Datatype, now, "https://wdc.unidairy.cn/copartner_uploads/")					var method string					UDPostPush1(fmt.Sprintf(item.Package, string(databyte), len(data)), method)				}				// }			}		}	})	c.Start()	c1 := cron.New()	c1.AddFunc("01 18 * * *", func() {		udFeedpSync(pastureinfo)	})	c1.Start()	c2 := cron.New()	c2.AddFunc("30 11 * * *", func() {		udFeedpSync(pastureinfo)	})	c2.Start()	c3 := cron.New()	c3.AddFunc("59 23 * * *", func() {		udFeedpSync(pastureinfo)		udFeedSync(pastureinfo)	})	c3.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  ifnull(de.deviation,0) deviation,round(de.lweight,2) 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,round(de.actualweightminus,2) 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 {			fmt.Println(plan["processtime"])			fmt.Println(fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]), local)			showTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %v", time.Now().Format("2006-01-02"), plan["processtime"]))			nowTime, _ := time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))			// showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %v", 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"] = fmt.Sprintf("%s%v", "混料搅拌延时异常", plan["projname"])				// sendMap1["color"] = "#173177"				sendList = append(sendList, sendMap1)				sendMap4 := make(map[string]interface{}, 0)				sendMap4["value"] = fmt.Sprintf("%v-%v", plan["tmrtname"], plan["fname"])				// sendMap4["color"] = "#173177"				sendList = append(sendList, sendMap4)				sendMap2 := make(map[string]interface{}, 0)				sendMap2["value"] = fmt.Sprintf("计划%v,实际%v", plan["lweight"], plan["actualweightminus"])				// sendMap2["color"] = "#173177"				sendList = append(sendList, sendMap2)				sendMap5 := make(map[string]interface{}, 0)				sendMap5["value"] = fmt.Sprintf("过程时间:%v", plan["processtime"])				// sendMap5["color"] = "#173177"				sendList = append(sendList, sendMap5)				sendMap3 := make(map[string]interface{}, 0)				sendMap3["value"] = plan["pasturename"]				// sendMap3["color"] = "#173177"				sendList = append(sendList, sendMap3)				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,			round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) 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 round(sum(de.lweight),2) lweight,round(sum(de.actualweightminus),2) 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)	}}func udFeedpSync(pastureinfo *udPastureInfo) error {	tx := restful.Engine.NewSession()	defer tx.Close()	downList := make([]*ScheduledDownInfo, 0)	down := tx.Table("scheduled_down")	down.Where("company = ? ", "ud")	down.Where("methods = ? ", "SyncFeedp")	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)})		}	}	return nil}func UdFeedpSync(c *gin.Context) {	appG := app.Gin{C: c}	dataByte, _ := ioutil.ReadAll(c.Request.Body)	fsion := gofasion.NewFasion(string(dataByte))	pastureId := fsion.Get("pastureId").ValueStr()	// 	pastureinfo := new(udPastureInfo)	// 	pastureinfo.Pastureid = pastureId	// 	udFeedpSync(pastureinfo)	pastureinfo := new(udPastureInfo)	pastureinfo.Pastureid = pastureId	err := udFeedpSync(pastureinfo)	if err != nil {		appG.Response(http.StatusOK, e.ERROR, err.Error())		return	}	appG.Response(http.StatusOK, e.SUCCESS, true)	// return}func udFeedSync(pastureinfo *udPastureInfo) error {	tx := restful.Engine.NewSession()	defer tx.Close()	downList := make([]*ScheduledDownInfo, 0)	down := tx.Table("scheduled_down")	down.Where("company = ? ", "ud")	down.Where("methods = ? ", "SyncFeed")	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)})		}	}	return nil}func XxwFeedtemplet(pastureId string) {	tx := restful.Engine.NewSession()	defer tx.Close()	count, _ := tx.SQL(`select count(1) from  notice where content = 'xxwFeedtemplet'  and status = 1 `).Count()	// fmt.Println(count)	// count = 1	// pastureId = "1725428057"	if count == 1 {		tx.Exec(` delete  from ftdetail_sync `)		tx.Exec(` INSERT INTO ftdetail_sync (	id,	pastureid,	ftid,	fid,	fname,	lweight,	fweight,	islockcount,	isfg,	sort,	feedgroup,	preftid,	autosecond,	autosecondname,	splitftpreid,	deviation,	is_show ) SELECTid,pastureid,ftid,fid,fname,lweight,fweight,islockcount,isfg,sort,feedgroup,preftid,ifnull(autosecond,0),autosecondname,splitftpreid,deviation,is_showFROM	ftdetail`)		ftList, err := tx.SQL(` SELECT    IFNULL(recipeId, '') AS recipeId,    IFNULL(fodderId, '') AS fodderId,	   sum(IFNULL(autoWeight, ''))  AS autoWeight,    IFNULL(fodderName, '') AS fodderName,	  IFNULL(orderNum, '') AS orderNum,    IFNULL(mergerFodderId, '') AS mergerFodderId,    IFNULL(mergerFodderName, '') AS mergerFodderNameFROM    xxw_feedtemplet  group by  recipeId,mergerFodderId`).QueryString()		if err != nil {			log.Println("XxwFeedtemplet-error-1: ", err)			return		}		dataList, err := tx.SQL(` SELECT    IFNULL(recipeId, '') AS recipeId,    IFNULL(fodderId, '') AS fodderId,    IFNULL(fodderName, '') AS fodderName,    IFNULL(autoWeight, '') AS autoWeight,    IFNULL(orderNum, '') AS orderNum,    IFNULL(mergerFodderId, '') AS mergerFodderId,    IFNULL(mergerFodderName, '') AS mergerFodderNameFROM    xxw_feedtemplet `).QueryString()		if err != nil {			log.Println("XxwFeedtemplet-error-1: ", err)			return		}		// for _, item := range ftList {		tx.Exec(` delete  from ftdetail where ftid in(select id from feedtemplet  where xxwTempletCode is not null ) `)		// }		for _, item := range ftList {			ids, err := setting.SnowIds.NextId()			if err != nil {				ids = time.Now().UnixNano()				logging.Info("create SnowIds err", err)			}			/*				if item["mergerFodderId"] == "" {					_, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,tname,fttypeid,fttype,xxwTempletCode)  "+						"values(?,?,(select id from cowclass where pastureid = ? limit 1),?,?,1,'饲喂配方',?) "+						" ON DUPLICATE KEY UPDATE owner ='丰顿下发' ", ids, pastureId, pastureId, item["recipeId"], item["recipeId"], item["recipeId"])					if err != nil {						log.Println("XxwFeedtemplet-error-2: ", err)						return					}				}			*/			// /*			if item["mergerFodderId"] == "" {				_, err = tx.Exec("insert into feedtemplet(id,pastureid,ccid,tcode,tname,fttypeid,fttype,xxwTempletCode)  "+					"values(?,?,(select id from cowclass where pastureid = ? limit 1),?,?,1,'饲喂配方',?) "+					" ON DUPLICATE KEY UPDATE owner ='丰顿下发' ", ids, pastureId, pastureId, item["recipeId"],					item["recipeId"], item["recipeId"])				if err != nil {					log.Println("XxwFeedtemplet-error-2: ", err)					return				}				_, err = tx.Exec(` update feedtemplet f set  tcode = (select if(left((select max(tcode) from					feedtemplet where pastureid = ?),8) = (select DATE_FORMAT(now(),"%Y%m%d")),					(select max(tcode)+1 from feedtemplet where pastureid = ?),					(select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))))					 where xxwTempletCode = ? and tcode is null  `, pastureId, pastureId, item["recipeId"])				if err != nil {					log.Println("XxwFeedtemplet-error-3: ", err)					return				}				// */			} else {				_, err = tx.Exec(`insert into feedtemplet(id,pastureid,ccid,tname,fttypeid,fttype,xxwTempletCode)						values(?,?,(select id from cowclass where pastureid = ? limit 1),?,2,'预混配方',?)						 ON DUPLICATE KEY UPDATE owner ='丰顿下发' `, ids, pastureId, pastureId,					item["mergerFodderName"]+item["recipeId"], item["mergerFodderId"])				if err != nil {					log.Println("XxwFeedtemplet-error-3: ", err)					return				}				_, err = tx.Exec(` update feedtemplet f set  tcode = (select if(left((select max(tcode) from					feedtemplet where pastureid = ?),8) = (select DATE_FORMAT(now(),"%Y%m%d")),					(select max(tcode)+1 from feedtemplet where pastureid = ?),					(select concat(DATE_FORMAT(now(),"%Y%m%d"),"001"))))					 where xxwTempletCode = ? and tcode is null  `, pastureId, pastureId, item["mergerFodderId"])				if err != nil {					log.Println("XxwFeedtemplet-error-3: ", err)					return				}				tx.Exec(` update feedtemplet f set  ccname = (select classname from cowclass  where id = f.ccid )					 where xxwTempletCode = ?  and tcode is null  `, item["mergerFodderId"])				ids, err := setting.SnowIds.NextId()				if err != nil {					ids = time.Now().UnixNano()					logging.Info("create SnowIds err", err)				}				_, err = tx.Exec(`insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,preftid,version)				 values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),					(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)   ,?,?,?,0,'',?,					(select id from feedtemplet where pastureid=? and xxwTempletCode =? limit 1),					(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) `,					ids, pastureId, pastureId, item["recipeId"], pastureId, item["mergerFodderId"], item["mergerFodderName"]+item["recipeId"], item["autoWeight"],					item["orderNum"], item["mergerFodderName"], pastureId, item["mergerFodderId"], pastureId, item["recipeId"])				if err != nil {					log.Println("XxwFeedtemplet-error-4: ", err)					return				}			}		}		for _, item := range dataList {			ids, err := setting.SnowIds.NextId()			if err != nil {				ids = time.Now().UnixNano()				logging.Info("create SnowIds err", err)			}			if item["mergerFodderId"] == "" {				_, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version)  "+					" values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+					" (select id from feed where pastureid=? and xxwFeedCode=? limit 1)   ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) ",					ids, pastureId, pastureId, item["recipeId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],					item["orderNum"], item["fodderName"], pastureId, item["recipeId"])				if err != nil {					log.Println(item)					log.Println("XxwFeedtemplet-error-5: ", err)					return				}			} else {				// /*				_, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version)  "+					" values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+					" (select id from feed where pastureid=? and xxwFeedCode=? limit 1)   ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1))   ON DUPLICATE KEY UPDATE pastureid = ?  ",					ids, pastureId, pastureId, item["mergerFodderId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],					item["orderNum"], item["fodderName"], pastureId, item["mergerFodderId"], pastureId)				if err != nil {					log.Println("XxwFeedtemplet-error-6: ", err)					return				}				// */				/*					_, err = tx.Exec("insert into ftdetail(id,pastureid,ftid,fid,fname,fweight,sort,autosecond,autosecondname,feedgroup,version)  "+						" values(?,?,(select id from feedtemplet where pastureid=? and xxwTempletCode=? limit 1),"+						" (select id from feed where pastureid=? and xxwFeedCode=? limit 1)   ,?,?,?,0,'',?,(select version from feedtemplet where pastureid=? and xxwTempletCode=? limit 1)) ",						ids, pastureId, pastureId, item["recipeId"], pastureId, item["fodderId"], item["fodderName"], item["autoWeight"],						item["orderNum"], item["mergerFodderName"], pastureId, item["recipeId"])					if err != nil {						log.Println("XxwFeedtemplet-error-7: ", err)						return					}				*/			}		}		tx.Exec(`update ftdetail f  set autosecond = (select autosecond from ftdetail_sync where ftid = f.ftid  and fid = f.fid ) ,		autosecondname = (select autosecondname from ftdetail_sync where ftid = f.ftid  and fid = f.fid ) `)		feedingList, err := tx.SQL(` SELECT    IFNULL(recipeId, '') AS recipeId	FROM    xxw_feedtemplet  group by  recipeId`).QueryString()		if err != nil {			log.Println("XxwFeedtemplet-error-1: ", err)			return		}		tx.Exec(` UPDATE notice SET status = 0 WHERE content = 'xxwFeedtemplet' `)		for _, feeding := range feedingList {			values1, _ := tx.SQL(`select b.bname barname,	ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,	ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 1 ),0) as '1' ,	ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 2		),0) as '2' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 3 		),0) as '3' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 4 		),0) as '4' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 5 		),0) as '5' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 6 		),0) as '6'   from feedp fp join bar b on b.id = fp.barid 		join feedtemplet  ft on ft.id = fp.ftid  where ft.xxwTempletCode = ? `, feeding["recipeId"]).QueryString()			fmt.Println(feeding["recipeId"])			FpdBatchEditGrfd(pastureId, values1)		}	}}func xxwFeedpSync(pastureId string) {	tx := restful.Engine.NewSession()	defer tx.Close()	count, _ := tx.SQL(`select count(1) from  notice where content = 'xxwBarCcount'  and status = 1 `).Count()	if count == 1 {		tx.Exec(` UPDATE notice SET status = 0 WHERE content = 'xxwBarCcount' `)		values1, err := tx.SQL(`select b.bname barname,	ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,	ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 1 ),0) as '1',	ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 2		),0) as '2' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 3		),0) as  '3' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 4		),0) as  '4' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 5		),0) as  '5' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 6		),0) as  '6'   from feedp fp join bar b on b.id = fp.barid		join feedtemplet  ft on ft.id = fp.ftid		where  b.pastureid = ?  and fp.ccount > 0 and fp.ftid >0  `, pastureId).QueryString()		fmt.Println(err)		FpdBatchEditGrfd(pastureId, values1)	}}func LYFDSync(c *gin.Context) {	appG := app.Gin{C: c}	dataByte, _ := ioutil.ReadAll(c.Request.Body)	fsion := gofasion.NewFasion(string(dataByte))	method := fsion.Get("method").ValueStr()	finalData := fsion.Get("finalDate").Array()	fmt.Println(method)	tx := restful.Engine.NewSession()	defer tx.Close()	pastureinfo := new(udPastureInfo)	err := tx.SQL(`select column_default  as pastureid,(select werks from pasture where pastureid = column_default)  werks  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	}	if method == "getPubBars" {		//牛舍,牛头数同步		getPubBars(finalData, tx, pastureinfo.Pastureid)	} else if method == "getMaterial" {		getMaterial(finalData, tx, pastureinfo.Pastureid)	} else if method == "getMaterialInfo" {		getMaterialInfo(finalData, tx, pastureinfo.Pastureid)	} else if method == "getTFeedRecipesKind" {		getTFeedRecipesKind(finalData, tx, pastureinfo.Pastureid)	}	appG.Response(http.StatusOK, e.SUCCESS, nil)}func getPubBars(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {	for _, f := range finalData {		barName := f.Get("barName").ValueStr()		barGroup := f.Get("barGroup").ValueStr()		ccount := f.Get("counts").ValueStr()		_, err := tx.Exec(`insert into bar(pastureid,bcode,bname,xxwBarCode)values(?,?,?,?)   ON DUPLICATE KEY UPDATE bname = ? `, pastureId, barGroup,			barName, barGroup, barName)		// INSERT INTO `tmrwatch5`.`feedp` (`pastureid`, `barname`, `barid`, `softccount`, `ccount`) VALUES (1, '1', 1, 0, 1)		fmt.Println(err)		_, err = tx.Exec(`insert into feedp(pastureid, barname, barid, softccount,ccount,xxwBarCode)			values(?,?,(select id from bar where bcode = ? and pastureId = ? ),?,?,?)   			ON DUPLICATE KEY UPDATE barname = ?,ccount = ? `, pastureId, barName,			barGroup, pastureId, 0,			ccount, barGroup, barName, ccount)		fmt.Println(err)		values1, err := tx.SQL(`select b.bname barname,	ifnull(ccount,0) ccount,ifnull(ratio,0) ratio,ftname,ptsfname,			ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 1 ),0) as '1',			ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 2				),0) as '2' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 3				),0) as  '3' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 4				),0) as  '4' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 5				),0) as  '5' ,ifnull((select tratio from fpdetail  where barid = fp.barid  and times = 6				),0) as  '6'   from feedp fp join bar b on b.id = fp.barid				join feedtemplet  ft on ft.id = fp.ftid				where  b.pastureid = ?  and fp.ccount > 0 and fp.ftid >0 and b.bcode = ?  `, pastureId, barGroup).QueryString()		fmt.Println(err)		if len(values1) != 0 {			FpdBatchEditGrfd(pastureId, values1)		}	}}func getMaterial(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {	for _, f := range finalData {		ids, err := setting.SnowIds.NextId()		if err != nil {			ids = time.Now().UnixNano()			logging.Info("create SnowIds err", err)		}		feedclassName := f.Get("feedclassName").ValueStr()		_, err = tx.SQL(`insert into feedclass(id,pastureid,fccode,fcname,bigfeedclassname,bigfeedclassid,sort,backup1)		vALUES(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from feedclass f  where f.pastureid =? ),?)  			ON DUPLICATE KEY UPDATE  backup1 = '丰顿' `,			ids, pastureId, f.Get("feedclassid").ValueStr(), feedclassName, feedclassName, ids, pastureId, "丰顿").Execute()		if err != nil {			logs.Error("getMaterial-error-1:", err)			return		}	}}func getMaterialInfo(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {	for _, f := range finalData {		feedclassid := f.Get("feedclassid").ValueStr()		_, err := tx.Exec(` insert into feed(pastureid,fclass,fclassid,feedcode,fname,allowratio,uprice,xxwFeedCode)		values(?,?,(select id from feedclass  where fcname = ? and pastureid = ? ),?,?,?,?,?) ON DUPLICATE KEY UPDATE  source = '丰顿'  `,			pastureId, f.Get("feedclassName").ValueStr(), f.Get("feedclassName").ValueStr(), pastureId,			feedclassid, f.Get("fodderName").ValueStr(), f.Get("autoWeight").ValueStr(),			f.Get("standardPrice").ValueStr(), feedclassid)		fmt.Println(err)	}}func getTFeedRecipesKind(finalData []*gofasion.Fasion, tx *xorm.Session, pastureId string) {	for _, f := range finalData {		ids, err := setting.SnowIds.NextId()		if err != nil {			ids = time.Now().UnixNano()			logging.Info("create SnowIds err", err)		}		recipeobjNAME := f.Get("recipeobjNAME").ValueStr()		_, err = tx.Exec(` insert into cowclass(id,pastureId,classcode,classname,parentid,parentname,sort)		values(?,?,?,?,?,?,(select ifnull(max(f.sort),0) +1 from cowclass f  where f.pastureid =? )  )  ON DUPLICATE KEY UPDATE classname = ?`,			ids, pastureId, recipeobjNAME, recipeobjNAME, ids,			recipeobjNAME, pastureId, recipeobjNAME)		if err != nil {			logs.Error(err)			return		}	}}
 |