package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/device/model"
	"iot_manager_service/app/device/service"
	"iot_manager_service/app/middleware"
	service2 "iot_manager_service/app/multimedia/service"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
	"math"
	"net/http"
	"strconv"
)

// 信息屏基本信息管理对象
var InfoBoard = new(infoBoardCtl)

type infoBoardCtl struct{}

func (c *infoBoardCtl) Detail(ctx *gin.Context) {
	id, e := strconv.Atoi(ctx.Query("id"))
	if e != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(e.Error(), nil))
		return
	}

	device, err := service.InfoBoardService.Get(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, device))
}

func (c *infoBoardCtl) List(ctx *gin.Context) {
	searchValue := ctx.Query("searchValue")
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}
	devices, total, err := service.InfoBoardService.List(searchValue, current, size)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	pages := math.Ceil(float64(total) / float64(size))
	rsp := model.RsqInfoBoardList{
		Current: current,
		Size:    size,
		Total:   int(total),
		Pages:   int(pages),
		Records: devices,
	}

	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

func (c *infoBoardCtl) CreateOrUpdate(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)

	var req dao.InfoBoard
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	if req.ID > 0 {
		//更新 排程
		service.InfoBoardService.EdgeCmd(claims.TenantId, req.Sn, 6, req.ID)
	}
	err := service.InfoBoardService.CreateOrUpdate(claims.UserId, claims.TenantId, req)
	ctx.JSON(http.StatusOK, err)
}

func (c *infoBoardCtl) Remove(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)

	var req *model.ReqInfoBoardRemove
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.InfoBoardService.Remove(claims.UserId, claims.TenantId, req.IDs)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

func (c *infoBoardCtl) ImportExcel(ctx *gin.Context) {
}

func (c *infoBoardCtl) ExportExcel(ctx *gin.Context) {
}

func (c *infoBoardCtl) ExportTemplate(ctx *gin.Context) {
}

func (c *infoBoardCtl) SystemOperation(ctx *gin.Context) {
}

func (c *infoBoardCtl) Enable(ctx *gin.Context) {
	//TODO:未做
}

func (c *infoBoardCtl) ShowSetting(ctx *gin.Context) {
	id, e := strconv.Atoi(ctx.Query("id"))
	if e != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(e.Error(), nil))
		return
	}

	device, err := service.InfoBoardService.Get(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, device))
}

type edgeCmdReq struct {
	InfoSn    string `json:"infoSn"`
	Id        int    `json:"id"`
	Directive int    `json:"directive"`
	Condition string `json:"condition"`
}

// EdgeCmd 向边缘端发送cmd命令
func (c *infoBoardCtl) EdgeCmd(ctx *gin.Context) {
	var req *edgeCmdReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)
	if req.Directive == 101 {
		var req2 dao.InfoBoard
		req2.ID = req.Id
		req2.Condition = req.Condition
		service.InfoBoardService.CreateOrUpdate(claims.UserId, claims.TenantId, req2)
	}
	//更新排程
	if req.Directive == 4 {
		c.CronSyncLedPaying(req.Id)
	}
	service.InfoBoardService.EdgeCmd(claims.TenantId, req.InfoSn, req.Directive, req.Id)
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

// CronSyncBrightnessAndMusicvolume 同步亮度与音量
func (s *infoBoardCtl) CronSyncBrightnessAndMusicvolume() {
	board := dao.InfoBoard{}
	list, err := board.GetAllDevicesNotTenant()
	if err != nil {
		fmt.Printf("err = %v \n", err)
		return
	}
	for _, led := range list {
		_, retState := cache.GetDeviceState(led.Sn)
		// 只有设备在线 才能向边缘端下发命令
		if retState == "1" {
			service.InfoBoardService.EdgeCmd(led.TenantId, led.Sn, 101, led.ID)
		}
	}
}

// CronSyncLedPaying 同步播放当前节目
func (s *infoBoardCtl) CronSyncLedPaying(id int) {
	board := dao.InfoBoard{}
	if id > 0 {
		board.ID = id
	}
	list, err := board.GetAllDevicesNotTenant()
	if err != nil {
		fmt.Printf("CronSyncLedPaying err = %v \n", err)
		return
	}
	for _, led := range list {
		_, retState := cache.GetDeviceState(led.Sn)
		currPaying := cache.GetDeviceLedData(led.Sn)
		if retState == "1" && len(currPaying) != 0 {
			playing := currPaying["playing"].(string) //得到当前正播放的节目
			fmt.Printf("led信息屏设备Sn = %v 当前正在播放[%v]", led.Sn, playing)
			playJson := service2.PublishLibrariesService.LedPaying(led.ID, playing)
			if playJson != "" {
				service.InfoBoardService.EdgePushLedProgram(led.TenantId, led.Sn, playJson)
				fmt.Printf("需要更新\n")
			} else {
				//fmt.Printf("无需更新\n")
			}
		} else {
			//fmt.Printf("led设备不在线Sn = %v \n", led.Sn)
		}
	}
}
