package gate import ( "context" "encoding/json" "fmt" "git.getensh.com/common/gopkgs/database" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" "gorm.io/gorm" "property-device/errors" dbmodel "property-device/model" pb_v1 "property-device/pb/v1" "property-device/utils/gate_utils" "strings" "time" ) func checkGateBatchInParam(req *pb_v1.GateBatchInRequest) error { for _, v := range req.List { switch { case v.Manufactor == "": return status.Error(10003, "厂商不能为空") case gate_utils.GateProtocolNameMap[v.Protocol] == "": return status.Error(10003, "协议不能为空") case v.Sn == "": return status.Error(10003, "设备序列号不能为空") } } return nil } func gateBatchInHandle(db *gorm.DB, datas []*pb_v1.GateBatchInItem, now time.Time) error { array := make([]dbmodel.TGate, len(datas)) for i, req := range datas { array[i].DeviceName = req.DeviceName array[i].Sn = req.Sn array[i].Manufactor = req.Manufactor array[i].AuthKey = req.AuthKey array[i].GardenId = 0 array[i].OutUser = "" array[i].OutTime = 0 array[i].Status = 2 array[i].Enable = 1 array[i].Location = "" array[i].Protocol = req.Protocol array[i].Direction = 0 array[i].CreatedAt = now array[i].UpdatedAt = now array[i].QcodeSupport = gate_utils.GateProtocolFuntionMap[req.Protocol][0] array[i].PicSupport = gate_utils.GateProtocolFuntionMap[req.Protocol][1] array[i].CardSupport = gate_utils.GateProtocolFuntionMap[req.Protocol][2] } p := &dbmodel.TGate{} err := p.InsertMulti(db, &array) if err != nil { if strings.Contains(strings.ToLower(err.Error()), "duplicate") { return status.Error(10003, "设备id或设备序列号重复") } return errors.DataBaseError } return nil } func GateBatchIn(ctx context.Context, req *pb_v1.GateBatchInRequest) (reply *pb_v1.GateBatchInReply, err error) { reply = &pb_v1.GateBatchInReply{} // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err = fmt.Errorf("%+v", r) e := &status.Status{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { logger.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() err = checkGateBatchInParam(req) if err != nil { return nil, err } now := time.Now() length := len(req.List) gap := 50 db := database.DB().Begin() // 分批入库 for i := 0; i < length; i += gap { datas := req.List[i:length] if i+gap <= length { datas = req.List[i : i+gap] } if err = gateBatchInHandle(db, datas, now); err != nil { db.Rollback() return nil, err } } db.Commit() return reply, nil }