| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125 | package backendimport (	"bytes"	"context"	"errors"	"fmt"	"io"	"kpt-tmr-group/model"	"kpt-tmr-group/pkg/logger/zaplog"	"kpt-tmr-group/pkg/tool"	"kpt-tmr-group/pkg/xerr"	operationPb "kpt-tmr-group/proto/go/backend/operation"	"net/http"	"strconv"	"sync"	"go.uber.org/zap"	"github.com/xuri/excelize/v2"	"gorm.io/gorm")// CreateGroupPasture 创建集团牧场func (s *StoreEntry) CreateGroupPasture(ctx context.Context, req *operationPb.AddPastureRequest) error {	// 账号同步牧场端	groupPasture := model.NewGroupPasture(req)	if err := s.DB.Create(groupPasture).Error; err != nil {		return xerr.WithStack(err)	}	if err := s.PastureAccountDistribution(ctx, groupPasture); err != nil {		s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_delete", operationPb.IsShow_NO)		return xerr.WithStack(err)	} else {		s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_distribution", operationPb.IsShow_OK)	}	return nil}// PastureAccountDistribution 账号同步牧场端func (s *StoreEntry) PastureAccountDistribution(ctx context.Context, groupPasture *model.GroupPasture) error {	if groupPasture.Domain == "" {		return nil	}	body := &model.AccountDistribution{		Account:     groupPasture.Account,		UserName:    groupPasture.ManagerUser,		Password:    groupPasture.Password,		Phone:       groupPasture.ManagerPhone,		PastureId:   int32(groupPasture.Id),		PastureName: groupPasture.Name,		Address:     groupPasture.Address,	}	res := &model.PastureCommonResponse{}	if err := s.PastureHttpClient(ctx, model.PastureAccountDistributionURl, groupPasture.Id, body, res); err != nil {		zaplog.Error("AccountDistribution", zap.Any("url", model.PastureAccountDistributionURl), zap.Any("err", err), zap.Any("body", body), zap.Any("res", res))		return xerr.WithStack(err)	}	if res.Code != http.StatusOK {		if err := s.DB.Model(new(model.GroupPasture)).Where("id = ?", groupPasture.Id).Update("is_distribution", operationPb.IsShow_OK).Error; err != nil {			zaplog.Error("AccountDistribution-Update", zap.Any("url", model.PastureAccountDistributionURl), zap.Any("err", err), zap.Any("body", body), zap.Any("res", res))			return xerr.Customf("%s", res.Msg)		}	}	return nil}func (s *StoreEntry) FindGroupPastureListByIds(ctx context.Context, pastureIds []int32) ([]*model.GroupPasture, error) {	groupPastureList := make([]*model.GroupPasture, 0)	if err := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK).		Where("id IN ?", pastureIds).		Find(&groupPastureList).Error; err != nil {		return nil, xerr.WithStack(err)	}	return groupPastureList, nil}func (s *StoreEntry) GetGroupPastureListById(ctx context.Context, pastureId int64) (*model.GroupPasture, error) {	groupPasture := &model.GroupPasture{		Id: int64(pastureId),	}	if err := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK).		First(&groupPasture).Error; err != nil {		return nil, xerr.WithStack(err)	}	return groupPasture, nil}// EditGroupPasture 创建集团牧场func (s *StoreEntry) EditGroupPasture(ctx context.Context, req *operationPb.AddPastureRequest) error {	groupPasture := &model.GroupPasture{Id: int64(req.Id)}	if err := s.DB.First(groupPasture).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在!")		}		return xerr.WithStack(err)	}	updateData := &model.GroupPasture{		Name:         req.Name,		Account:      req.Account,		ManagerUser:  req.ManagerUser,		ManagerPhone: req.ManagerPhone,		Address:      req.Address,		Domain:       req.Domain,	}	if err := s.DB.Model(new(model.GroupPasture)).Omit("is_show", "password").		Where("id = ?", req.Id).		Updates(updateData).Error; err != nil {		return xerr.WithStack(err)	}	return nil}// SearchGroupPastureList 查询牧场列表func (s *StoreEntry) SearchGroupPastureList(ctx context.Context, req *operationPb.SearchPastureRequest) (*operationPb.SearchPastureResponse, error) {	groupPasture := make([]*model.GroupPasture, 0)	var count int64 = 0	pref := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK)	if req.Name != "" {		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))	}	if req.ManagerPhone != "" {		pref.Where("manager_phone like ?", fmt.Sprintf("%s%s%s", "%", req.ManagerPhone, "%"))	}	if req.ManagerUser != "" {		pref.Where("manager_user like ?", fmt.Sprintf("%s%s%s", "%", req.ManagerUser, "%"))	}	if req.StartTime > 0 && req.EndTime > 0 && req.EndTime >= req.StartTime {		pref.Where("created_at BETWEEN  ? AND ? ", req.StartTime, req.EndTime)	}	if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).		Find(&groupPasture).Error; err != nil {		return nil, xerr.WithStack(err)	}	return &operationPb.SearchPastureResponse{		Code: http.StatusOK,		Msg:  "ok",		Data: &operationPb.SearchPastureData{			Page:     req.Pagination.Page,			Total:    int32(count),			PageSize: req.Pagination.PageSize,			List:     model.GroupPastureSlice(groupPasture).ToPB(),		},	}, nil}// DataSyncGroupPastureList 用户数据下发的牧场func (s *StoreEntry) DataSyncGroupPastureList(ctx context.Context) ([]*model.GroupPasture, error) {	groupPastureList := make([]*model.GroupPasture, 0)	if err := s.DB.Model(new(model.GroupPasture)).Where("is_delete = ? ", operationPb.IsShow_OK).		Where("is_show = ?", operationPb.IsShow_OK).Where("domain != ''").		Where("is_distribution = ?", operationPb.IsShow_OK).		Find(&groupPastureList).Error; err != nil {		return nil, xerr.WithStack(err)	}	zaplog.Info("GroupPastureList", zap.Any("data", groupPastureList))	return groupPastureList, nil}func (s *StoreEntry) DeleteGroupPasture(ctx context.Context, pastureId int64) error {	groupPasture := &model.GroupPasture{		Id: pastureId,	}	if err := s.DB.First(groupPasture).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(groupPasture).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) ResetPasswordGroupPasture(ctx context.Context, pastureId int64) error {	groupPasture := &model.GroupPasture{		Id: pastureId,	}	if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(groupPasture).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(groupPasture).Update("password", tool.Md5String(model.InitManagerPassword)).Error; err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) IsShowGroupPasture(ctx context.Context, req *operationPb.IsShowGroupPasture) error {	groupPasture := &model.GroupPasture{		Id: int64(req.PastureId),	}	if err := s.DB.First(groupPasture).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(groupPasture).Where("is_delete = ?", operationPb.IsShow_OK).Update("is_show", req.IsShow).Error; err != nil {		return xerr.WithStack(err)	}	return nil}// AddCattleCategory 添加畜牧分类func (s *StoreEntry) AddCattleCategory(ctx context.Context, req *operationPb.AddCattleCategoryRequest) error {	cattleCategory := model.NewCattleCategory(req)	if err := s.DB.Create(cattleCategory).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(req.ParentId),			ParentName: req.ParentName,			Name:       req.Name,			Id:         int32(req.Id),			Number:     req.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(cattleCategory.Id),		}		if err = s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body); err != nil {			zaplog.Error("AddCattleCategory", zap.Any("CategoryDistribution", err))		}	}	return nil}// EditCattleCategory 编辑畜牧分类func (s *StoreEntry) EditCattleCategory(ctx context.Context, req *operationPb.AddCattleCategoryRequest) error {	cattleCategory := &model.CattleCategory{Id: int64(req.Id)}	if err := s.DB.First(cattleCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	updateData := &model.CattleCategory{		ParentName: req.ParentName,		Name:       req.Name,		Number:     req.Number,		ParentId:   req.ParentId,	}	if err := s.DB.Model(new(model.CattleCategory)).Omit("is_show", "is_delete").		Where("id = ?", req.Id).		Updates(updateData).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(req.ParentId),			ParentName: req.ParentName,			Name:       req.Name,			Id:         int32(req.Id),			Number:     req.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(req.Id),		}		if err = s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body); err != nil {			zaplog.Error("EditCattleCategory", zap.Any("CategoryDistribution", err))		}	}	return nil}// IsShowCattleCategory 是否启用func (s *StoreEntry) IsShowCattleCategory(ctx context.Context, req *operationPb.IsShowCattleCategory) error {	cattleCategory := &model.CattleCategory{Id: int64(req.CattleCategoryId)}	if err := s.DB.First(cattleCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(new(model.CattleCategory)).Where("id = ?", req.CattleCategoryId).Update("is_show", req.IsShow).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(cattleCategory.ParentId),			ParentName: cattleCategory.ParentName,			Name:       cattleCategory.Name,			Id:         req.CattleCategoryId,			Number:     cattleCategory.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(cattleCategory.Id),		}		if err = s.CategoryDistribution(ctx, model.CattleCategoryDistributionURl, body); err != nil {			zaplog.Error("IsShowCattleCategory", zap.Any("CategoryDistribution", err), zap.Any("body", body))		}	}	return nil}// DeleteCattleCategory 是否删除func (s *StoreEntry) DeleteCattleCategory(ctx context.Context, cattleCategoryId int64) error {	cattleCategory := &model.CattleCategory{Id: cattleCategoryId}	if err := s.DB.First(cattleCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(new(model.CattleCategory)).Where("id = ?", cattleCategoryId).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryDeleteRequest{			GroupId:  int32(cattleCategory.Id),			IsDelete: int32(operationPb.IsShow_OK),		}		if err = s.CategoryDelete(ctx, model.CattleCategoryDeleteURl, body); err != nil {			zaplog.Error("DeleteCattleCategory", zap.Any("CategoryDelete", err), zap.Any("body", body))		}	}	return nil}// SearchCattleCategoryList 牧畜分类类别列表func (s *StoreEntry) SearchCattleCategoryList(ctx context.Context, req *operationPb.SearchCattleCategoryRequest) (*operationPb.SearchCattleCategoryResponse, error) {	cattleCategory := make([]*model.CattleCategory, 0)	var count int64 = 0	pref := s.DB.Model(new(model.CattleCategory)).Where("is_delete = ?", operationPb.IsShow_OK)	if req.Name != "" {		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))	}	if req.ParentId > 0 {		pref.Where("parent_id = ?", req.ParentId)	}	if req.IsShow > 0 {		pref.Where("is_show = ?", req.IsShow)	}	if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).		Find(&cattleCategory).Debug().Error; err != nil {		return nil, xerr.WithStack(err)	}	return &operationPb.SearchCattleCategoryResponse{		Code: http.StatusOK,		Msg:  "ok",		Data: &operationPb.SearchCattleCategoryData{			Page:     req.Pagination.Page,			PageSize: req.Pagination.PageSize,			Total:    int32(count),			List:     model.CattleCategorySlice(cattleCategory).ToPB(),		},	}, nil}// AddForageCategory 添加饲料分类func (s *StoreEntry) AddForageCategory(ctx context.Context, req *operationPb.AddForageCategoryRequest) error {	forageCategory := model.NewForageCategory(req)	if err := s.DB.Create(forageCategory).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(req.ParentId),			ParentName: req.ParentName,			Name:       req.Name,			Id:         int32(req.Id),			Number:     req.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(forageCategory.Id),		}		if err = s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body); err != nil {			zaplog.Error("AddForageCategory", zap.Any("CategoryDistribution", err), zap.Any("body", body))		}	}	return nil}// EditForageCategory 编辑饲料分类func (s *StoreEntry) EditForageCategory(ctx context.Context, req *operationPb.AddForageCategoryRequest) error {	forageCategory := &model.ForageCategory{Id: int64(req.Id)}	if err := s.DB.First(forageCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	updateData := &model.ForageCategory{		ParentName: req.ParentName,		Name:       req.Name,		Number:     req.Number,		ParentId:   req.ParentId,	}	if err := s.DB.Model(new(model.ForageCategory)).Omit("is_show", "is_delete").		Where("id = ?", req.Id).		Updates(updateData).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(req.ParentId),			ParentName: req.ParentName,			Name:       req.Name,			Id:         int32(req.Id),			Number:     req.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(req.Id),		}		if err = s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body); err != nil {			zaplog.Error("EditForageCategory", zap.Any("CategoryDistribution", err), zap.Any("body", body))		}	}	return nil}// IsShowForageCategory 是否启用func (s *StoreEntry) IsShowForageCategory(ctx context.Context, req *operationPb.IsShowForageCategory) error {	forageCategory := &model.ForageCategory{Id: int64(req.ForageCategoryId)}	if err := s.DB.First(forageCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(new(model.ForageCategory)).Where("id = ?", req.ForageCategoryId).Update("is_show", req.IsShow).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryRequest{			ParentId:   int32(forageCategory.ParentId),			ParentName: forageCategory.ParentName,			Name:       forageCategory.Name,			Id:         req.ForageCategoryId,			Number:     forageCategory.Number,			IsShow:     int32(req.IsShow),			GroupId:    int32(forageCategory.Id),		}		if err = s.CategoryDistribution(ctx, model.ForageCategoryDistributionURl, body); err != nil {			zaplog.Error("IsShowForageCategory", zap.Any("CategoryDistribution", err), zap.Any("body", body))		}	}	return nil}// DeleteForageCategory 是否删除func (s *StoreEntry) DeleteForageCategory(ctx context.Context, forageCategoryId int64) error {	forageCategory := &model.ForageCategory{Id: forageCategoryId}	if err := s.DB.First(forageCategory).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(new(model.ForageCategory)).Where("id = ?", forageCategoryId).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {		return xerr.WithStack(err)	} else {		body := &model.CategoryDeleteRequest{			GroupId:  int32(forageCategory.Id),			IsDelete: int32(operationPb.IsShow_OK),		}		if err = s.CategoryDelete(ctx, model.CattleCategoryDeleteURl, body); err != nil {			zaplog.Error("DeleteForageCategory", zap.Any("CategoryDelete", err), zap.Any("body", body))		}	}	return nil}// SearchForageCategoryList 饲料分类类别列表func (s *StoreEntry) SearchForageCategoryList(ctx context.Context, req *operationPb.SearchForageCategoryRequest) (*operationPb.SearchForageCategoryResponse, error) {	forageCategory := make([]*model.ForageCategory, 0)	var count int64 = 0	pref := s.DB.Model(new(model.ForageCategory)).Where("is_delete = ?", operationPb.IsShow_OK)	if req.Name != "" {		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))	}	if req.ParentId > 0 {		pref.Where("parent_id = ?", req.ParentId)	}	if req.Number != "" {		pref.Where("number like ?", fmt.Sprintf("%s%s%s", "%", req.Number, "%"))	}	if req.IsShow > 0 {		pref.Where("is_show = ?", req.IsShow)	}	if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).		Find(&forageCategory).Debug().Error; err != nil {		return nil, xerr.WithStack(err)	}	return &operationPb.SearchForageCategoryResponse{		Code: http.StatusOK,		Msg:  "ok",		Data: &operationPb.SearchForageCategoryData{			Page:     req.Pagination.Page,			PageSize: req.Pagination.PageSize,			Total:    int32(count),			List:     model.ForageCategorySlice(forageCategory).ToPB(),		},	}, nil}// CategoryDistribution 饲料分类和畜牧分类下发func (s *StoreEntry) CategoryDistribution(ctx context.Context, url string, req *model.CategoryRequest) error {	groupList, err := s.DataSyncGroupPastureList(ctx)	if err != nil {		return xerr.WithStack(err)	}	wg := sync.WaitGroup{}	wg.Add(len(groupList))	for _, v := range groupList {		go func(data *model.GroupPasture) {			res := &model.PastureCommonResponse{}			req.PastureId = int32(data.Id)			if err = s.PastureHttpClient(ctx, url, int64(data.Id), req, res); err != nil {				zaplog.Error("CategoryDistribution",					zap.Any("url", url),					zap.Any("err", err),					zap.Any("body", req),					zap.Any("res", res),				)			}			if res.Code != http.StatusOK {				zaplog.Error("CategoryDistribution-http",					zap.Any("url", url),					zap.Any("body", req),					zap.Any("res", res),				)			}			wg.Done()		}(v)	}	wg.Wait()	return nil}// CategoryDelete 饲料分类和畜牧分类删除func (s *StoreEntry) CategoryDelete(ctx context.Context, url string, req *model.CategoryDeleteRequest) error {	groupList, err := s.DataSyncGroupPastureList(ctx)	if err != nil {		return xerr.WithStack(err)	}	wg := sync.WaitGroup{}	wg.Add(len(groupList))	for _, v := range groupList {		go func(data *model.GroupPasture) {			res := &model.PastureCommonResponse{}			req.PastureId = int32(data.Id)			if err = s.PastureHttpClient(ctx, url, int64(data.Id), req, res); err != nil {				zaplog.Error("CategoryDelete",					zap.Any("url", url),					zap.Any("err", err),					zap.Any("body", req),					zap.Any("res", res),				)			}			if res.Code != http.StatusOK {				zaplog.Error("CategoryDelete-http",					zap.Any("url", url),					zap.Any("body", req),					zap.Any("res", res),				)			}			wg.Done()		}(v)	}	wg.Wait()	return nil}// CreateForage 创建饲料func (s *StoreEntry) CreateForage(ctx context.Context, req *operationPb.AddForageRequest) error {	forage := model.NewForage(req)	if err := s.DB.Create(forage).Error; err != nil {		return xerr.WithStack(err)	}	return nil}// EditForage 编辑饲料func (s *StoreEntry) EditForage(ctx context.Context, req *operationPb.AddForageRequest) error {	forage := model.Forage{Id: int64(req.Id)}	if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).First(&forage).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	updateData := &model.Forage{		Name:               req.Name,		CategoryId:         int64(req.CategoryId),		CategoryName:       req.CategoryName,		MaterialType:       req.MaterialType,		UniqueEncode:       req.UniqueEncode,		ForageSourceId:     req.ForageSourceId,		PlanTypeId:         req.PlanTypeId,		SmallMaterialScale: req.SmallMaterialScale,		AllowError:         int64(req.AllowError),		PackageWeight:      int64(req.PackageWeight),		Price:              int64(req.Price),		JumpWeight:         int64(req.JumpWeight),		JumpDelay:          req.JumpDelay,		ConfirmStart:       req.ConfirmStart,		RelayLocations:     int64(req.RelayLocations),		Jmp:                req.Jmp,		Backup1:            req.Backup1,		Backup2:            req.Backup2,		Backup3:            req.Backup3,	}	if err := s.DB.Model(new(model.Forage)).Omit("is_show", "is_delete").Where("id = ?", req.Id).		Updates(updateData).Error; err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) SearchForageList(ctx context.Context, req *operationPb.SearchForageListRequest) (*operationPb.SearchForageListResponse, error) {	forage := make([]*model.Forage, 0)	var count int64 = 0	pref := s.DB.Model(new(model.Forage)).Where("is_delete = ?", operationPb.IsShow_OK)	if req.Name != "" {		pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))	}	if req.CategoryId > 0 {		pref.Where("category_id = ?", req.CategoryId)	}	if req.ForageSourceId > 0 {		pref.Where("forage_source_id = ?", req.ForageSourceId)	}	if req.IsShow > 0 {		pref.Where("is_show = ?", req.IsShow)	}	if req.AllowError > 0 {		pref.Where("allow_error = ?", req.AllowError)	}	if req.JumpWeight > 0 {		pref.Where("jump_weight = ?", req.JumpWeight)	}	if req.JumpDelay > 0 {		pref.Where("jump_delay = ?", req.JumpDelay)	}	if err := pref.Order("sort").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).		Find(&forage).Error; err != nil {		return nil, xerr.WithStack(err)	}	return &operationPb.SearchForageListResponse{		Code: http.StatusOK,		Msg:  "ok",		Data: &operationPb.SearchForageList{			Page:     req.Pagination.Page,			PageSize: req.Pagination.PageSize,			Total:    int32(count),			List:     model.ForageSlice(forage).ToPB(),		},	}, nil}func (s *StoreEntry) ForageListSort(ctx context.Context, req *operationPb.ForageListSortRequest) error {	for _, v := range req.List {		if err := s.DB.Model(new(model.Forage)).Select("sort").Where("id = ?", v.Id).Updates(map[string]interface{}{			"sort": v.Sort,		}).Error; err != nil {			zaplog.Error("ForageListSort", zap.Any("err", err), zap.Any("id", v.Id), zap.Any("sort", v.Sort))		}	}	return nil}func (s *StoreEntry) ForageEnumList(ctx context.Context) *operationPb.ForageEnumListResponse {	res := &operationPb.ForageEnumListResponse{		Code: http.StatusOK,		Msg:  "ok",		Data: &operationPb.ForageEnumList{			JumpDelaType:          make([]*operationPb.JumpDelaTypeEnum, 0),			ForageSource:          make([]*operationPb.ForageSourceEnum, 0),			ForagePlanType:        make([]*operationPb.ForagePlanTypeEnum, 0),			CattleParentCategory:  make([]*operationPb.CattleParentCategoryEnum, 0),			ForageParentCategory:  make([]*operationPb.ForageParentCategoryEnum, 0),			IsShow:                make([]*operationPb.IsShowEnum, 0),			FormulaType:           make([]*operationPb.FormulaTypeEnum, 0),			FormulaList:           make([]*operationPb.FormulaOptionEnum, 0),			ConfirmStart:          make([]*operationPb.IsShowEnum, 0),			FormulationEvaluation: make([]*operationPb.FormulaOptionEnum, 0),			UseMaterialsType:      make([]*operationPb.FormulaOptionEnum, 0),			UseMaterialsList:      make([]*operationPb.FormulaOptionEnum, 0),			PriceMaterialsType:    make([]*operationPb.FormulaOptionEnum, 0),		},	}	// 跳转延迟	res.Data.JumpDelaType = append(res.Data.JumpDelaType, &operationPb.JumpDelaTypeEnum{		Value: operationPb.JumpDelaType_INVALID,		Label: "禁用",	}, &operationPb.JumpDelaTypeEnum{		Value: operationPb.JumpDelaType_THREE,		Label: "3秒",	}, &operationPb.JumpDelaTypeEnum{		Value: operationPb.JumpDelaType_SIX,		Label: "6秒",	})	// 饲料来源	res.Data.ForageSource = append(res.Data.ForageSource, &operationPb.ForageSourceEnum{		Value: operationPb.ForageSource_SYSTEM_BUILT_IN,		Label: "系统内置",	}, &operationPb.ForageSourceEnum{		Value: operationPb.ForageSource_USER_DEFINED,		Label: "用户自定义",	})	// 计划类型	res.Data.ForagePlanType = append(res.Data.ForagePlanType,		&operationPb.ForagePlanTypeEnum{			Value: operationPb.ForagePlanType_INVALID,			Label: "无",		},		&operationPb.ForagePlanTypeEnum{			Value: operationPb.ForagePlanType_FORKLIFT,			Label: "铲车",		}, &operationPb.ForagePlanTypeEnum{			Value: operationPb.ForagePlanType_CONCENTRATE,			Label: "精料",		})	// 畜牧类别	res.Data.CattleParentCategory = append(res.Data.CattleParentCategory, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_LACTATION_CAW,		Label: "泌乳牛",	}, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_FATTEN_CAW,		Label: "育肥牛",	}, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_RESERVE_CAW,		Label: "后备牛",	}, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_DRY_CAW,		Label: "干奶牛",	}, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_PERINATAL_CAW,		Label: "围产牛",	}, &operationPb.CattleParentCategoryEnum{		Value: operationPb.CattleCategoryParent_OTHER_CAW,		Label: "其他",	})	// 饲料类别	res.Data.ForageParentCategory = append(res.Data.ForageParentCategory, &operationPb.ForageParentCategoryEnum{		Value: operationPb.ForageCategoryParent_ROUGHAGE,		Label: "粗料",	}, &operationPb.ForageParentCategoryEnum{		Value: operationPb.ForageCategoryParent_CONCENTRATE,		Label: "精料",	}, &operationPb.ForageParentCategoryEnum{		Value: operationPb.ForageCategoryParent_HALF_ROUGHAGE_HALF_CONCENTRATE,		Label: "粗料精料参半",	}, &operationPb.ForageParentCategoryEnum{		Value: operationPb.ForageCategoryParent_OTHER,		Label: "其他",	})	res.Data.IsShow = append(res.Data.IsShow, &operationPb.IsShowEnum{		Value: operationPb.IsShow_OK,		Label: "是",	}, &operationPb.IsShowEnum{		Value: operationPb.IsShow_NO,		Label: "否",	})	res.Data.FormulationEvaluation = append(res.Data.FormulationEvaluation, &operationPb.FormulaOptionEnum{		Value: 0,		Label: "按配方查询",	}, &operationPb.FormulaOptionEnum{		Value: 1,		Label: "按栏舍查询",	})	res.Data.FormulaType = append(res.Data.FormulaType, &operationPb.FormulaTypeEnum{		Value: operationPb.FormulaType_FEED_FORMULA,		Label: "饲喂配方",	}, &operationPb.FormulaTypeEnum{		Value: operationPb.FormulaType_PREMIXED_FORMULA,		Label: "预混配方",	}, &operationPb.FormulaTypeEnum{		Value: operationPb.FormulaType_SUPPLEMENTARY_FORMULA,		Label: "补料配方",	})	res.Data.ConfirmStart = append(res.Data.ConfirmStart, &operationPb.IsShowEnum{		Value: operationPb.IsShow_OK,		Label: "启用",	}, &operationPb.IsShowEnum{		Value: operationPb.IsShow_NO,		Label: "禁用",	})	res.Data.UseMaterialsList = append(res.Data.UseMaterialsList, &operationPb.FormulaOptionEnum{		Value: 1,		Label: "理论",	}, &operationPb.FormulaOptionEnum{		Value: 2,		Label: "实际",	})	res.Data.PriceMaterialsType = append(res.Data.PriceMaterialsType, &operationPb.FormulaOptionEnum{		Value: 1,		Label: "畜牧类别",	}, &operationPb.FormulaOptionEnum{		Value: 2,		Label: "栏舍名称",	}, &operationPb.FormulaOptionEnum{		Value: 3,		Label: "日期",	}, &operationPb.FormulaOptionEnum{		Value: 4,		Label: "TMR设备号",	})	res.Data.UseMaterialsType = append(res.Data.PriceMaterialsType, &operationPb.FormulaOptionEnum{		Value: 5,		Label: "TMR班次",	}, &operationPb.FormulaOptionEnum{		Value: 6,		Label: "车次",	})	res.Data.JumpType = append(res.Data.JumpType, &operationPb.FormulaOptionEnum{		Value: 0,		Label: "手动跳转",	}, &operationPb.FormulaOptionEnum{		Value: 1,		Label: "自动跳转",	})	res.Data.StatisticsType = append(res.Data.StatisticsType, &operationPb.FormulaOptionEnum{		Value: 7,		Label: "无分类",	}, &operationPb.FormulaOptionEnum{		Value: 0,		Label: "驾驶员",	}, &operationPb.FormulaOptionEnum{		Value: 1,		Label: "配方名称",	}, &operationPb.FormulaOptionEnum{		Value: 2,		Label: "栏舍名称",	}, &operationPb.FormulaOptionEnum{		Value: 3,		Label: "牧畜类别",	}, &operationPb.FormulaOptionEnum{		Value: 4,		Label: "车次",	}, &operationPb.FormulaOptionEnum{		Value: 5,		Label: "TMR名称",	}, &operationPb.FormulaOptionEnum{		Value: 6,		Label: "饲料",	})	res.Data.FormulaList = append(res.Data.FormulaList, &operationPb.FormulaOptionEnum{		Value: 0,		Label: "所有",	})	formulaList := make([]*model.FeedFormula, 0)	if err := s.DB.Where("is_delete = ?", operationPb.IsShow_OK).Find(&formulaList).Error; err != nil {		zaplog.Error("OptionFormula", zap.Any("Err", err))		return res	}	for _, v := range formulaList {		res.Data.FormulaList = append(res.Data.FormulaList, &operationPb.FormulaOptionEnum{			Value: int32(v.Id),			Label: v.Name,		})	}	return res}func (s *StoreEntry) DeleteForageList(ctx context.Context, ids []int64) error {	if len(ids) == 0 {		return xerr.Custom("参数错误")	}	if err := s.DB.Model(new(model.Forage)).Where("id IN ?", ids).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {		return xerr.WithStack(err)	}	return nil}func (s *StoreEntry) IsShowForage(ctx context.Context, req *operationPb.IsShowForage) error {	forage := &model.Forage{Id: int64(req.ForageId)}	if err := s.DB.First(forage).Error; err != nil {		if errors.Is(err, gorm.ErrRecordNotFound) {			return xerr.Custom("该数据不存在")		}		return xerr.WithStack(err)	}	if err := s.DB.Model(new(model.Forage)).Where("id = ?", req.ForageId).Update("is_show", req.IsShow).Error; err != nil {		return xerr.WithStack(err)	}	return nil}// ExcelImportForage 导入excelfunc (s *StoreEntry) ExcelImportForage(ctx context.Context, req io.Reader) error {	xlsx, err := excelize.OpenReader(req)	if err != nil {		return xerr.WithStack(err)	}	defer xlsx.Close()	rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))	if err != nil {		return xerr.WithStack(err)	}	if len(rows) > 10000 {		rows = rows[:10000]	}	forageList := make([]*model.Forage, 0)	for i, row := range rows {		if i == 0 {			continue		}		var (			forageSourceId                                int32			categoryId, price, jumpWeight, relayLocations int			allowError, packageWeight                     int			name, uniqueEncode, backup1, backup2, backup3 string		)		for k, v := range row {			if k == 0 {				name = v			}			if k == 2 {				uniqueEncode = v			}			if k == 3 {				forageSourceId = operationPb.ForageSource_Kind_value[v]			}			if k == 5 {				allowError, _ = strconv.Atoi(v)			}			if k == 6 {				packageWeight, _ = strconv.Atoi(v)			}			if k == 7 {				price, _ = strconv.Atoi(v)			}			if k == 8 {				jumpWeight, _ = strconv.Atoi(v)			}			if k == 11 {				relayLocations, _ = strconv.Atoi(v)			}			if k == 13 {				backup1 = v			}			if k == 14 {				backup2 = v			}			if k == 15 {				backup3 = v			}		}		forageItem := &model.Forage{			Name:               name,			CategoryId:         int64(categoryId),			MaterialType:       0,			UniqueEncode:       uniqueEncode,			ForageSourceId:     operationPb.ForageSource_Kind(forageSourceId),			PlanTypeId:         0,			SmallMaterialScale: "",			AllowError:         int64(allowError),			PackageWeight:      int64(packageWeight),			Price:              int64(price),			JumpWeight:         int64(jumpWeight),			JumpDelay:          0,			ConfirmStart:       0,			RelayLocations:     int64(relayLocations),			Jmp:                0,			Backup1:            backup1,			Backup2:            backup2,			Backup3:            backup3,			IsShow:             operationPb.IsShow_OK,			IsDelete:           operationPb.IsShow_OK,			DataSource:         operationPb.DataSource_EXCEL_IMPORT,		}		forageList = append(forageList, forageItem)	}	if len(forageList) > 0 {		if err = s.DB.Create(forageList).Error; err != nil {			return xerr.WithStack(err)		}	}	return nil}// ExcelExportForage 流式导出excelfunc (s *StoreEntry) ExcelExportForage(ctx context.Context, req *operationPb.SearchForageListRequest) (*bytes.Buffer, error) {	res, err := s.SearchForageList(ctx, req)	if err != nil {		return nil, xerr.WithStack(err)	}	if len(res.Data.List) <= 0 {		return nil, xerr.Custom("数据为空")	}	file := excelize.NewFile()	defer file.Close()	streamWriter, err := file.NewStreamWriter(model.DefaultSheetName)	if err != nil {		return nil, xerr.WithStack(err)	}	titles := []interface{}{"饲料名称", "饲料分类", "唯一编码", "饲料来源", "计划类型", "允许误差(kg)", "包装单位重量(kg)",		"单价", "跳转重量域(kg)", "跳转延迟", "确认开始", "继电器位置", "无上域", "备用字段01", "备用字段02", "备用字段03"}	if err = streamWriter.SetRow("A1", titles); err != nil {		return nil, xerr.WithStack(err)	}	for i, item := range res.Data.List {		cell, err := excelize.CoordinatesToCellName(1, i+2)		if err != nil {			zaplog.Error("excelize.CoordinatesToCellName", zap.Any("Err", err))			continue		}		row := make([]interface{}, 0)		row = append(row, item.Name, item.CategoryName, item.UniqueEncode, item.ForageSourceId, item.PlanTypeId,			item.AllowError, item.PackageWeight, float64(item.Price/100.00), item.JumpWeight, item.JumpDelay,			item.ConfirmStart, item.RelayLocations, item.Jmp, item.Backup1, item.Backup2, item.Backup3)		if err = streamWriter.SetRow(cell, row); err != nil {			return nil, xerr.WithStack(err)		}	}	if err = streamWriter.Flush(); err != nil {		return nil, xerr.WithStack(err)	}	return file.WriteToBuffer()}// ExcelTemplateForage 导出模板func (s *StoreEntry) ExcelTemplateForage(ctx context.Context) (*bytes.Buffer, error) {	file := excelize.NewFile()	defer file.Close()	streamWriter, err := file.NewStreamWriter("Sheet1")	if err != nil {		return nil, xerr.WithStack(err)	}	titles := []interface{}{"饲料名称", "饲料分类", "唯一编码", "饲料来源", "计划类型", "允许误差(kg)", "包装单位重量(kg)",		"单价", "跳转重量域(kg)", "跳转延迟", "确认开始", "继电器位置", "无上域", "备用字段01", "备用字段02", "备用字段03"}	if err = streamWriter.SetRow("A1", titles); err != nil {		return nil, xerr.WithStack(err)	}	if err = streamWriter.Flush(); err != nil {		return nil, xerr.WithStack(err)	}	return file.WriteToBuffer()}func (s *StoreEntry) SmallMaterial(ctx context.Context, req *operationPb.SmallMaterialRequest) (*model.PastureCommonResponse, error) {	body := &model.PastureCommonRequest{		Name:       req.ApiName,		ReturnType: "Map",		ParamMaps: &model.FormulaEstimateParams{			PastureId: fmt.Sprintf("%d", req.PastureId),			ImforName: req.InfoName,		},	}	response := &model.PastureCommonResponse{Data: &model.PastureCommonData{}}	if err := s.PastureHttpClient(ctx, model.UrlDataByName, int64(req.PastureId), body, response); err != nil {		return nil, xerr.WithStack(err)	}	return response, nil}
 |