package model import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation" "gitee.com/xuyiping_admin/pkg/logger/zaplog" "gitee.com/xuyiping_admin/pkg/tool" "gitee.com/xuyiping_admin/pkg/xerr" "go.uber.org/zap" ) const ( InitManagerPassword = "123456" UrlDataByName = "authdata/GetDataByName" UrlReportForm = "authdata/GetReportform" UrlSummary = "authdata/summary" UrlProcess = "authdata/processAnalysist" UrlFeedTemplateHistory = "authdata/feedtemplet/history" UrlBarnHistory = "authdata/feedp/history" UrlSpillageAllHistory = "authdata/spillageall/history" ) const ( FeedFormulaDistributeUrl = "pasture/feed_formula/distribute" FeedFormulaCancelDistributeUrl = "pasture/feed_formula/cancel/distribute" FeedFormulaIsModifyUrl = "pasture/feed_formula/is_modify" FeedFormulaAsyncUrl = "pasture/feed_formula/async" FeedFormulaDetailListAsyncUrl = "pasture/feed_formula/detail_list" FeedAsyncUrl = "pasture/feed/async" DashboardAccuracyUrl = "pasture/dashboard/accuracy_data" DashboardExecTimeUrl = "pasture/dashboard/process_analysis" DashboardSprinkleFeedTimeUrl = "pasture/dashboard/sprinkle_statistics" PastureAccountDistributionURl = "pasture/account/distribute" ForageCategoryDistributionURl = "pasture/forage_category/distribute" CattleCategoryDistributionURl = "pasture/cattle_category/distribute" CattleCategoryDeleteURl = "pasture/cattle_category/delete" ForageCategoryDeleteURl = "pasture/cattle_category/delete" FeedUsageURl = "pasture/feed/usage" FeedFormulaVersionUpdateUrl = "pasture/feed_formula/version" ) var ( UrlChart = map[string]string{ "mr": "authdata/chart/feedEffMR", // 饲喂效率-效率统计 mr 泌乳牛干物质采食量 "sl": "authdata/chart/feedEffSL", // 饲喂效率-效率统计 sl 牛栏剩料率 "hl": "authdata/chart/feedEffHL", // 饲喂效率-效率统计 hl 混料时间统计 "zh": "authdata/chart/feedEffZH", // 饲喂效率-效率统计 zh 转化率 "cbft": "authdata/chart/feedEffCBFT", // 饲喂效率-效率统计 cbft 成本分析 "jh": "authdata/chart/accuracyAllJH", // 准确性分析-汇总统计-计划统计 "ft": "authdata/chart/accuracyAllFT", // 准确性分析-汇总统计-配方准确率 "nq": "authdata/chart/accuracyAllNQ", // 准确性分析-汇总统计-牛群准确率 "cc": "authdata/chart/accuracyAllCC", // 准确性分析-汇总统计-车辆准确率(重量) "allhl": "authdata/chart/accuracyAllHL", // 准确性分析-汇总统计-混料统计 "qx": "authdata/chart/accuracyAllQX", // 准确性分析-汇总统计-混料计划取消次数 "ls": "authdata/chart/accuracyAllLS", // 准确性分析-汇总统计-栏舍撒料时间统计 } ) type GroupPasture struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` PastureId int64 `json:"pasture_id"` Account string `json:"account,omitempty"` Password string `json:"password"` ManagerUser string `json:"manager_user"` ManagerPhone string `json:"manager_phone"` Domain string `json:"domain"` Extranet string `json:"extranet"` Intranet string `json:"intranet"` IsShow operationPb.IsShow_Kind `json:"is_show,omitempty"` IsDelete operationPb.IsShow_Kind `json:"is_delete,omitempty"` IsDistribution operationPb.IsShow_Kind `json:"is_distribution"` Address string `json:"address"` CreatedAt int64 `json:"created_at,omitempty"` UpdatedAt int64 `json:"updated_at,omitempty"` } func (g *GroupPasture) TableName() string { return "group_pasture" } // GetPastureId 获取牧场id func (g *GroupPasture) GetPastureId() int64 { if g.PastureId > 0 { return g.PastureId } return g.Id } type PastureTokenRequest struct { UserName string `json:"username"` Password string `json:"password"` } type PastureTokenResponse struct { Code int32 `json:"code"` Msg string `json:"msg"` Data *PastureTokenData `json:"data"` } type PastureTokenData struct { Token string `json:"token"` } func NewGroupPasture(req *operationPb.AddPastureRequest) *GroupPasture { groupPasture := &GroupPasture{ Name: req.Name, PastureId: int64(req.PastureId), Account: req.Account, Password: tool.Md5String(InitManagerPassword), ManagerUser: req.ManagerUser, ManagerPhone: req.ManagerPhone, IsShow: operationPb.IsShow_OK, IsDelete: operationPb.IsShow_OK, Address: req.Address, Domain: req.Domain, IsDistribution: operationPb.IsShow_NO, } return groupPasture } type PastureClient struct { Token string `json:"token"` Detail *GroupPasture `json:"detail"` authClient *http.Client } func NewPastureClient(g *GroupPasture) *PastureClient { return &PastureClient{ Detail: g, authClient: &http.Client{ Timeout: time.Duration(5) * time.Second, }, } } func (p *PastureClient) doRequest(req *http.Request) ([]byte, error) { resp, err := p.authClient.Do(req) if err != nil { zaplog.Error("PastureClient", zap.Any("authClient.Do", err)) return nil, xerr.WithStack(err) } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { zaplog.Error("PastureClient", zap.Any("ioutil.ReadAll", err)) return nil, xerr.WithStack(err) } if resp.StatusCode != http.StatusOK { if len(b) > 0 { return nil, xerr.Customf("err:%v,body:%s", err, string(b)) } else { return nil, xerr.Customf("err:%v", err) } } return b, nil } func (p *PastureClient) DoGet(url string) ([]byte, error) { // 获取token if err := p.GetToken(); err != nil { zaplog.Error("PastureClient", zap.Any("DoGet GetToken Err", err), zap.Any("detail", p.Detail)) return nil, xerr.WithStack(err) } req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { zaplog.Error("PastureClient", zap.Any("DoGet", err)) return nil, err } req.Header.Add("Accept", "application/json") req.Header.Add("token", p.Token) req.Header.Add("Content-Type", "application/json") req.Header.Add("pasture_id", fmt.Sprintf("%d", p.Detail.PastureId)) return p.doRequest(req) } func (p *PastureClient) DoPost(url string, body interface{}) ([]byte, error) { b, err := json.Marshal(body) if err != nil { zaplog.Error("PastureClient", zap.Any("DoPost-Marshal", err)) return nil, xerr.WithStack(err) } // 获取token if !strings.Contains(url, PastureAccountDistributionURl) { if err = p.GetToken(); err != nil { zaplog.Error("PastureClient", zap.Any("DoPost GetToken Err", err), zap.Any("detail", p.Detail)) return nil, xerr.WithStack(err) } } req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b)) if err != nil { zaplog.Error("PastureClient", zap.Any("NewRequest", err)) return nil, xerr.WithStack(err) } req.Header.Add("Accept", "application/json") req.Header.Add("token", p.Token) req.Header.Add("Content-Type", "application/json") req.Header.Add("pasture_id", fmt.Sprintf("%d", p.Detail.PastureId)) return p.doRequest(req) } func (p *PastureClient) GetToken() error { url := fmt.Sprintf("%s/%s", p.Detail.Domain, "auth") body := &PastureTokenRequest{ UserName: p.Detail.Account, Password: p.Detail.Password, } b, err := json.Marshal(body) if err != nil { return xerr.WithStack(err) } req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b)) if err != nil { zaplog.Error("PastureClient", zap.Any("GetToken", err)) return xerr.WithStack(err) } req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/json") result, err := p.doRequest(req) if err != nil { zaplog.Error("PastureClient", zap.Any("GetToken-doRequest", err)) return xerr.WithStack(err) } response := &PastureTokenResponse{} if err = json.Unmarshal(result, response); err != nil { zaplog.Error("PastureClient", zap.String("GetToken", string(result))) return xerr.WithStack(err) } if response.Code != http.StatusOK || response.Data == nil || response.Data.Token == "" { zaplog.Error("PastureClient", zap.Any("response", response)) return xerr.Customf("获取牧场端token失败 Err:%s", err) } p.Token = response.Data.Token return nil } type GroupPastureSlice []*GroupPasture func (g GroupPastureSlice) ToPB() []*operationPb.AddPastureRequest { res := make([]*operationPb.AddPastureRequest, len(g)) for i, v := range g { res[i] = &operationPb.AddPastureRequest{ Id: int32(v.Id), Name: v.Name, Account: v.Account, ManagerUser: v.ManagerUser, ManagerPhone: v.ManagerPhone, Address: v.Address, Domain: v.Domain, IsShow: v.IsShow, CreatedAt: int32(v.CreatedAt), CreatedAtFormat: time.Unix(v.CreatedAt, 0).Format(LayoutTime), PastureId: int32(v.PastureId), } } return res } func (g *GroupPasture) ToPb() *operationPb.AddPastureRequest { return &operationPb.AddPastureRequest{ Id: int32(g.Id), Name: g.Name, ManagerUser: g.ManagerUser, ManagerPhone: g.ManagerPhone, Address: g.Address, IsShow: g.IsShow, CreatedAt: int32(g.CreatedAt), } }