package uhf

import (
	"fmt"
	"wails-app/internal/dao"
	"wails-app/internal/global"
	"wails-app/internal/model/uhf/request"
	"wails-app/internal/model/uhf/response"

	"go.uber.org/zap"
)

type uhfService struct{}

var UHFService = new(uhfService)

// CreateReader 创建UHF读写器
func (s *uhfService) CreateReader(req request.UHFReaderCreate) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("device_code = ?", req.DeviceCode).First(&reader)
	if result.RowsAffected > 0 {
		return fmt.Errorf("设备编码已存在")
	}

	var channel dao.Channel
	global.GVA_DB.Model(&channel).Where("id = ?", req.ChannelId).First(&channel)

	var booth dao.Booth
	global.GVA_DB.Model(&booth).Where("id = ?", channel.BoothID).First(&booth)

	reader = dao.UHFReader{
		DeviceCode:   req.DeviceCode,
		DeviceName:   req.DeviceName,
		DeviceType:   req.DeviceType,
		ConnectType:  req.ConnectType,
		IPAddress:    req.IPAddress,
		Port:         req.Port,
		COMPort:      req.COMPort,
		BaudRate:     req.BaudRate,
		IsActive:     req.IsActive,
		Description:  req.Description,
		ParkingLotID: booth.ParkingLotID,
		ChannelID:    uint(req.ChannelId),
	}

	err := global.GVA_DB.Create(&reader).Error

	if req.IsActive {
		if err := StartDeviceHandler(&reader); err != nil {
			global.GVA_LOG.Error("启动设备失败", zap.String("code", reader.DeviceCode), zap.Error(err))
		}
	}

	return err
}

// UpdateReader 更新UHF读写器
func (s *uhfService) UpdateReader(req request.UHFReaderUpdate) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", req.ID).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	updateData := map[string]interface{}{
		"device_name":  req.DeviceName,
		"device_type":  req.DeviceType,
		"connect_type": req.ConnectType,
		"ip_address":   req.IPAddress,
		"port":         req.Port,
		"com_port":     req.COMPort,
		"baud_rate":    req.BaudRate,
		"is_active":    req.IsActive,
		"description":  req.Description,
		"channel_id":   req.ChannelId,
	}

	return global.GVA_DB.Model(&reader).Updates(updateData).Error
}

// ConnectedDevice 连接设备
func (s *uhfService) ConnectedDevice(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	return StartDeviceHandler(&reader)
}

// GetReaderByCode 根据设备编码获取设备
func (s *uhfService) GetReaderByCode(code string) (response.UHFReaderResponse, error) {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("device_code = ?", code).First(&reader)
	if result.RowsAffected == 0 {
		return response.UHFReaderResponse{}, fmt.Errorf("设备不存在")
	}

	return response.UHFReaderResponse{
		ID:           reader.ID,
		DeviceCode:   reader.DeviceCode,
		DeviceName:   reader.DeviceName,
		ConnectType:  reader.ConnectType,
		IPAddress:    reader.IPAddress,
		Port:         reader.Port,
		COMPort:      reader.COMPort,
		BaudRate:     reader.BaudRate,
		Status:       reader.Status,
		IsActive:     reader.IsActive,
		Description:  reader.Description,
		ParkingLotID: reader.ParkingLotID,
		CreatedAt:    reader.CreatedAt,
		UpdatedAt:    reader.UpdatedAt,
	}, nil
}

func (s *uhfService) QueryAllReaders() ([]dao.UHFReader, error) {
	var readers []dao.UHFReader
	err := global.GVA_DB.Find(&readers).Error
	if err != nil {
		return readers, err
	}
	return readers, nil
}

// ListReaders 分页查询设备列表
func (s *uhfService) ListReaders(req request.UHFReaderQuery) ([]dao.UHFReader, int64, error) {
	var readers []dao.UHFReader
	var total int64

	query := global.GVA_DB.Model(&dao.UHFReader{}).Preload("Channel").Preload("ParkingLot")

	if req.DeviceCode != "" {
		query = query.Where("device_code LIKE ?", "%"+req.DeviceCode+"%")
	}
	if req.DeviceName != "" {
		query = query.Where("device_name LIKE ?", "%"+req.DeviceName+"%")
	}
	if req.Status != "" {
		query = query.Where("status = ?", req.Status)
	}
	if req.ConnectType != "" {
		query = query.Where("connect_type = ?", req.ConnectType)
	}

	if req.ParkingLotID != 0 {
		query = query.Where("parking_lot_id = ?", req.ParkingLotID)
	}

	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	limit := req.PageSize
	offset := (req.Page - 1) * req.PageSize
	err = query.Limit(limit).Offset(offset).Order("created_at DESC").Find(&readers).Error
	if err != nil {
		return nil, 0, err
	}

	return readers, total, nil
}

// DeleteReader 删除设备
func (s *uhfService) DeleteReader(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	return global.GVA_DB.Delete(&reader).Error
}

// ConnectReader 连接设备
func (s *uhfService) ConnectReader(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	if !reader.IsActive {
		return fmt.Errorf("设备未启用")
	}

	err := global.GVA_DB.Model(&reader).Update("status", "online").Error
	if err != nil {
		return err
	}

	fmt.Printf("设备[%s]连接成功\n", reader.DeviceCode)
	return nil
}

// DisconnectReader 断开设备连接
func (s *uhfService) DisconnectReader(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	err := global.GVA_DB.Model(&reader).Update("status", "offline").Error
	if err != nil {
		return err
	}

	fmt.Printf("设备[%s]断开连接\n", reader.DeviceCode)
	return nil
}

// ReportTag 客户端上报标签数据
func (s *uhfService) ReportTag(deviceCode string, tag string) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("device_code = ?", deviceCode).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	fmt.Printf("📶 收到设备 %s 上报的标签: %s\n", deviceCode, tag)

	return nil
}

// SetReaderPower 设置功率（模拟实现）
func (s *uhfService) SetReaderPower(id uint, power int) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	if reader.Status != "online" {
		return fmt.Errorf("设备未连接")
	}

	fmt.Printf("设备[%s]功率设置为: %ddBm\n", reader.DeviceCode, power)
	return nil
}

// StartInventory 启动读卡（模拟实现）
func (s *uhfService) StartInventory(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	if reader.Status != "online" {
		return fmt.Errorf("设备未连接")
	}

	fmt.Printf("设备[%s]已启动读卡模式\n", reader.DeviceCode)
	return nil
}

// StopInventory 停止读卡（模拟实现）
func (s *uhfService) StopInventory(id uint) error {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return fmt.Errorf("设备不存在")
	}

	fmt.Printf("设备[%s]已停止读卡\n", reader.DeviceCode)
	return nil
}

// ReadTag 读取标签（模拟实现）
func (s *uhfService) ReadTag(id uint) (string, error) {
	var reader dao.UHFReader
	result := global.GVA_DB.Where("id = ?", id).First(&reader)
	if result.RowsAffected == 0 {
		return "", fmt.Errorf("设备不存在")
	}

	if reader.Status != "online" {
		return "", fmt.Errorf("设备未连接")
	}

	return "", nil
}
