package monitor

import (
	"server/dao/devices"
	"server/dao/system"
	"server/global"
	"server/model/monitor"
	"server/utils/logger"
	"strconv"
	"strings"
)

type MultiScreenService struct{}

func (s MultiScreenService) MultiScreenList(id uint) ([]monitor.Placement, error) {
	user := system.SysUser{}
	err := user.GetUser(id)
	if err != nil {
		logger.Logger.Error("获取用户失败")
		return nil, err
	}
	idsSplit := strings.Split(user.SixScreen, ",")

	var list []monitor.Placement
	for i, id := range idsSplit {
		idInt, _ := strconv.Atoi(id)
		placement := monitor.Placement{}
		placement.ID = idInt
		placement.Slot = i + 1
		if idInt != -1 {
			ca := devices.Camera{}
			camera, err := ca.GetCamera(idInt)
			if err != nil {
				logger.Logger.Error("获取摄像头信息失败")
				continue
			}
			placement.Code = camera.CameraCode
			placement.Name = camera.CameraName
			placement.StreamId = camera.StreamId
			devAddress := camera.GateWay.Intersect.Address + "--" + camera.ShuntDescribe + "(主路)"
			if camera.Shunt == 2 {
				devAddress = camera.GateWay.Intersect.Address + "--" + camera.ShuntDescribe + "(支路)"
			}
			placement.DeviceAddress = devAddress
			placement.Url = global.GVA_CONFIG.Webrtc.Path + camera.StreamId
		}
		list = append(list, placement)
	}
	return list, nil
}

func (s MultiScreenService) EditMultiScreen(userid uint, site int, cameraId int) error {
	user := system.SysUser{}
	err := user.GetUser(userid)
	if err != nil {
		logger.Logger.Error("获取用户失败")
		return err
	}
	idsSplit := strings.Split(user.SixScreen, ",")
	idStr := ""
	for i := range idsSplit {
		if i+1 == site {
			idsSplit[site-1] = strconv.Itoa(cameraId)
		}
		idStr += idsSplit[i]
		if i < (len(idsSplit) - 1) {
			idStr += ","
		}
	}
	sysUser := system.SysUser{
		GVA_MODEL: global.GVA_MODEL{
			ID: userid,
		},
		SixScreen: idStr,
	}
	err = sysUser.SetUserInfoById()
	if err != nil {
		logger.Logger.Error("EditMultiScreen()... 修改用户信息失败")
		return err
	}
	return err
}
