package service

import (
	deviceDao "iot_manager_service/app/device/dao"
	"iot_manager_service/app/middleware"
	"iot_manager_service/app/security/model"
	"iot_manager_service/app/system/dao"
	"log"
	"strconv"
	"strings"
)

var MultiscreenService = new(multiscreenService)

type multiscreenService struct{}

func (s multiscreenService) List(claims *middleware.Claims) ([]model.Placement, error) {
	securitySixScreen := s.getSlot(claims.UserId)
	idsSplit := strings.Split(securitySixScreen, ",")
	var ids []string
	for _, id := range idsSplit {
		idInt, _ := strconv.Atoi(id)
		if idInt < 1 {
			continue
		}
		ids = append(ids, strconv.Itoa(idInt))
	}
	//devices := deviceDao.CameraDevice{}.GetDevicesByIds(strings.Join(ids, ","))
	//fmt.Printf("devices = %v", devices)
	var list []model.Placement
	for i, id := range idsSplit {
		idInt, _ := strconv.Atoi(id)
		placement := model.Placement{}
		placement.ID = idInt
		placement.Slot = i + 1
		if idInt != -1 {
			device := deviceDao.CameraDevice{ID: idInt}
			err := device.GetDevice()
			if err != nil {
				continue
			}
			placement.Name = device.DeviceName
			placement.Sn = device.DeviceSN
			placement.Url = device.MonitorAddress
		}
		list = append(list, placement)
	}
	//fmt.Printf("list = %v", list)
	return list, nil
}

// Save 保存 多屏监控位置
func (s multiscreenService) Save(claims *middleware.Claims, site, id int) error {
	securitySixScreen := s.getSlot(claims.UserId)
	idsSplit := strings.Split(securitySixScreen, ",")
	ids := ""
	for i := range idsSplit {
		if i == (site - 1) {
			idsSplit[i] = strconv.Itoa(id)
		}
		ids += idsSplit[i]
		if i < (len(idsSplit) - 1) {
			ids += ","
		}
	}
	user := &dao.User{ID: claims.UserId}
	user.SecuritySixScreen = ids
	err := user.Update()
	if err != nil {
		return err
	}
	return nil
}

func (s multiscreenService) getSlot(userId int64) string {
	user := &dao.User{ID: userId}
	err := user.GetUser()
	if err != nil {
		log.Fatalln(err)
		panic("用户取失败了")
	}
	ids := ""
	if user.SecuritySixScreen == "" {
		ids = "-1,-1,-1,-1,-1,-1"
	} else {
		ids = user.SecuritySixScreen
	}
	return ids
}
