package admin

import (
	"encoding/json"
	"fmt"
	"server/dao"
	"server/model/common/request"
	"server/utils/logger"
	"server/utils/protocol"
	"strconv"
)

type TunnelService struct{}

func (ts *TunnelService) QueryAllTunnels() ([]dao.Tunnel, error) {
	return dao.QueryAllTunnels()
}

func (ts *TunnelService) QueryTunnelList(info request.TunnelSearch) ([]dao.Tunnel, int64, error) {
	limit := info.PageInfo.PageSize
	offset := info.PageInfo.PageSize * (info.PageInfo.Page - 1)
	return dao.QueryTunnelList(info.Name, info.RegionId, info.UserId, limit, offset)
}

func (ts *TunnelService) QueryNoRegionTunnels() ([]dao.Tunnel, error) {
	return dao.QueryNoRegionTunnels()
}

func (ts *TunnelService) CreateTunnel(tunnel dao.Tunnel) error {
	return tunnel.CreateTunnel()
}

func (ts *TunnelService) UpdateTunnel(tunnel dao.Tunnel) error {
	return tunnel.UpdateTunnel()
}

func (ts *TunnelService) UpdateTunnelLamp(info request.TunnelLamp) error {
	data1 := strconv.Itoa(1) + strconv.Itoa(info.LampValue1)
	data2 := strconv.Itoa(2) + strconv.Itoa(info.LampValue2)
	err := MqttService.Publish(MqttService.GetTopic(info.TunnelSn, protocol.TopicLampControl), []byte(data1))
	if err != nil {
		return fmt.Errorf("error updating: %v", err)
	}
	err = MqttService.Publish(MqttService.GetTopic(info.TunnelSn, protocol.TopicLampControl), []byte(data2))
	if err != nil {
		return fmt.Errorf("error updating: %v", err)
	}
	return dao.UpdateTunnelLamp(info.Id, info.LampValue1, info.LampValue2)
}

func (ts *TunnelService) UpdateTactics(sn string, tactics int) error {
	err := MqttService.Publish(MqttService.GetTopic(sn, protocol.TopicTunnelTactics), strconv.Itoa(tactics))
	if err != nil {
		return fmt.Errorf("error updating: %v", err)
	}
	return dao.UpdateTactics(sn, tactics)
}

func (ts *TunnelService) UpdateTunnelsRegion(tunnelIds []int, regionId int) error {
	return dao.UpdateTunnelsRegion(tunnelIds, regionId)
}

func (ts *TunnelService) UpdateTunnelTime(time dao.TunnelTime) error {
	// 使用json.Marshal函数将结构体转换为JSON字节切片
	jsonBytes, err := json.Marshal(time)
	if err != nil {
		logger.Get().Fatalf("Error marshalling to JSON: %v", err)
	}
	err = MqttService.Publish(MqttService.GetTopic(time.TunnelSn, protocol.TopicTunnelTiming), jsonBytes)
	if err != nil {
		return err
	}
	time.IsComplete = false
	return time.UpdateTunnelTime()
}

func (ts *TunnelService) TunnelTimeOk(sn string) error {
	return dao.TunnelTimeOk(sn)
}

func (ts *TunnelService) DeleteTunnel(id int) error {
	devices, err := dao.QueryDeviceByTunnelId(id)
	if err != nil {
		return err
	}
	if len(devices) > 0 {
		return fmt.Errorf("存在数据不能删除")
	}
	return dao.DeleteTunnel(id)
}
