package bluetooth

import (
	"fmt"
	"mini_server/internal/dao"
	"mini_server/internal/server/help"
	"mini_server/internal/server/httpreply"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type CreateRequest struct {
	DeviceId   string `gorm:"unique;type varchar(64);not null;comment:'设备Id，唯一标识每个蓝牙设备'"`
	DeviceName string `gorm:"type varchar(64);comment:'蓝牙名称'"`
	DeviceType string `gorm:"type varchar(64);comment:'设备类型'"`
}

// 添加角色
func Create(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	var request CreateRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid json data,err:%v", err)
		return
	}

	userid, res := help.GetUserId(c)
	if !res {
		reply.Status = http.StatusInternalServerError
		reply.Message = "登录信息已失效"
		return
	}

	data := dao.Bluetooth{
		DeviceId:   request.DeviceId,
		DeviceName: request.DeviceName,
		DeviceType: request.DeviceType,
		UserId:     userid,
	}

	err := dao.AddBluetooth(&data)
	if err != nil {
		logrus.Errorf("dao.Bluetooth_Insert failed, err:%v", err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "添加蓝牙失败"
		return
	}
	reply.Data = data
}

func QueryAll(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	userid, res := help.GetUserId(c)
	if !res {
		reply.Status = http.StatusInternalServerError
		reply.Message = "登录信息已失效"
		return
	}
	data, err := dao.GetAllBluetooth(userid)
	if err != nil {
		reply.Status = http.StatusInternalServerError
		reply.Message = "蓝牙查询异常"
		return
	}
	reply.Data = data
}

func Delete(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	var request CreateRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid json data,err:%v", err)
		return
	}

	userid, res := help.GetUserId(c)
	if !res {
		reply.Status = http.StatusInternalServerError
		reply.Message = "登录信息已失效"
		return
	}

	err := dao.DeleteBluetooth(request.DeviceId, userid)
	if err != nil {
		logrus.Errorf("dao.Bluetooth_Delete failed, err:%v", err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "删除蓝牙失败"
		return
	}
	reply.Data = err
}
