| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260 | 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/http/handle/yq"	"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,(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	}	//消息提醒	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()	} else if setting.ServerSetting.SyncStatus == 9 {		yq.YqCron()	}	// 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, ","))					} else if targetdata == "date" {						args = append(args, date)					}				}				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"]		// }		var barId string		barCount, err := tx.SQL(" select count(1) from bar where pastureid = ? and bcode = ? ", pastureid, barName).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, barName).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, barName).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)		}		insertSql := `insert into feedp(pastureid,barname,barid,softccount)VALUES(?,?,?,?)		ON DUPLICATE KEY UPDATE barname = ?  `		_, 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 08 * * *", 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		}	}}
 |