package rfidProgram import ( "crypto/md5" "encoding/hex" "fmt" "github.com/flipped-aurora/gin-vue-admin/server/global" "github.com/flipped-aurora/gin-vue-admin/server/model/common/response" "github.com/flipped-aurora/gin-vue-admin/server/model/rfidProgram" "github.com/flipped-aurora/gin-vue-admin/server/model/rfidProgram/request" "github.com/gin-gonic/gin" "strconv" "strings" "time" ) type RfidAppApi struct{} // CORS 中间件 func corsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "http://dev-rfid.7in6.com:23609") c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Token") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(200) return } c.Next() } } // 登录请求结构体 type LoginRequest struct { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"` } // 登录响应 type LoginResponse struct { UserInfo UserInfo `json:"user_info"` Token string `json:"token"` TokenExpireTime time.Time `json:"token_expire_time"` } // 用户信息响应 type UserInfo struct { ID int32 `json:"id"` Username string `json:"username"` Nickname string `json:"nickname"` Building string `json:"building"` Room string `json:"room"` Pen string `json:"pen"` } // 用户登录 func (rfidAppApi *RfidAppApi) Login(c *gin.Context) { var req LoginRequest if err := c.ShouldBindJSON(&req); err != nil { response.FailWithMessage("参数错误", c) return } // 计算密码 MD5 hash := md5.Sum([]byte(req.Password)) passwordHash := hex.EncodeToString(hash[:]) // 查询用户 var user rfidProgram.RfidUser result := global.GVA_DB.Where("username = ? AND password = ?", req.Username, passwordHash).First(&user) if result.Error != nil { response.FailWithMessage("用户名或密码错误", c) return } // 获取当前时间和今天结束时间 now := time.Now() todayEnd := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location()) // 判断 token 是否有效 var token string if user.Token != "" && user.TokenExpireTime.After(now) { token = user.Token } else { // 生成新 token token = generateToken(user.Username) // 更新用户 token user.Token = token user.TokenExpireTime = &todayEnd user.SysRq = &now global.GVA_DB.Save(&user) } // 构造返回数据 userInfo := UserInfo{ ID: *user.Id, Username: user.Username, Nickname: user.Nickname, Building: user.Building, Room: user.Room, Pen: user.Pen, } loginRes := LoginResponse{ UserInfo: userInfo, Token: token, TokenExpireTime: todayEnd, } response.OkWithDetailed(loginRes, "登录成功", c) } // 生成 token func generateToken(username string) string { timestamp := time.Now().Unix() uniquePart := fmt.Sprintf("%d%d", timestamp, time.Now().UnixNano()) data := fmt.Sprintf("%s%s%s", username, uniquePart, "randomSalt") hash := md5.Sum([]byte(data)) return hex.EncodeToString(hash[:]) } // 保存用户设置 func (rfidAppApi *RfidAppApi) PostUserSetup(c *gin.Context) { var req rfidProgram.RfidUserEditInfo if err := c.ShouldBindJSON(&req); err != nil { response.FailWithMessage("参数错误", c) return } // 更新用户信息 result := global.GVA_DB.Model(&rfidProgram.RfidUser{}).Where("id = ?", req.Id).Updates(map[string]interface{}{ "building": req.Building, "room": req.Room, "pen": req.Pen, }) if result.Error != nil { response.FailWithMessage("保存失败", c) return } response.OkWithMessage("保存成功", c) } // 获取用户信息 func (rfidAppApi *RfidAppApi) UserList(c *gin.Context) { userID := c.Query("userid") if userID == "" { response.FailWithMessage("用户ID不能为空", c) return } // 转换用户ID为整数 id, err := strconv.Atoi(userID) if err != nil { response.FailWithMessage("用户ID格式错误", c) return } var user rfidProgram.RfidUser result := global.GVA_DB.Select("nickname", "username", "id", "token", "token_expire_time", "building", "room", "pen"). Where("id = ?", id).First(&user) if result.Error != nil { response.FailWithMessage("用户不存在", c) return } response.OkWithMessage("获取用户数据信息", c) } // 获取栋舍编号 func (rfidAppApi *RfidAppApi) GetBuilding(c *gin.Context) { var buildings []rfidProgram.RfidBuilding result := global.GVA_DB.Find(&buildings) if result.Error != nil { response.FailWithMessage("获取栋舍编号失败", c) return } response.OkWithDetailed(buildings, "栋舍编号", c) } // 获取房间编号 func (rfidAppApi *RfidAppApi) GetRoom(c *gin.Context) { var rooms []rfidProgram.RfidRoom result := global.GVA_DB.Find(&rooms) if result.Error != nil { response.FailWithMessage("获取房间编号失败", c) return } response.OkWithDetailed(rooms, "栋舍编号", c) } // 获取栏位编号 func (rfidAppApi *RfidAppApi) GetPen(c *gin.Context) { var pens []rfidProgram.RfidPen result := global.GVA_DB.Find(&pens) if result.Error != nil { response.FailWithMessage("获取栏位编号失败", c) return } response.OkWithDetailed(pens, "栋舍编号", c) } // 提交 RFID 记录 func (rfidAppApi *RfidAppApi) PostListAdd(c *gin.Context) { var req request.RfidRecordRequest if err := c.ShouldBindJSON(&req); err != nil { response.FailWithMessage("参数错误", c) return } // 解析 RFID 数据 rfidPairs := strings.Split(req.Rfid, ",") if len(rfidPairs) == 0 { response.FailWithMessage("RFID数据不能为空", c) return } var validRecords []rfidProgram.RfidRecords now := time.Now() for _, pair := range rfidPairs { pair = strings.TrimSpace(pair) if pair == "" { continue } parts := strings.SplitN(pair, ":", 2) if len(parts) < 2 { continue } rfid := strings.TrimSpace(parts[0]) rfidType := strings.TrimSpace(parts[1]) record := rfidProgram.RfidRecords{ Username: req.Username, UserId: req.UserID, Rfid: rfid, RfidNum: len(rfidPairs), BuildingName: req.BuildingName, RoomName: req.RoomName, PenNo: req.PenNo, Model: req.DeviceModel, Version: req.DeviceVersion, Type: rfidType, SysRq: &now, } validRecords = append(validRecords, record) } if len(validRecords) == 0 { response.FailWithMessage("无有效RFID数据", c) return } // 批量插入记录 result := global.GVA_DB.Create(&validRecords) if result.Error != nil { response.FailWithMessage("插入异常", c) return } response.OkWithDetailed(map[string]interface{}{"count": result.RowsAffected}, "数据已提交成功", c) }