package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/device/dao"
	"iot_manager_service/app/device/edge_service"
	"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/common"
	"math"
	"net/http"
	"strconv"
)

// IP广播基本信息管理对象
var IpBroadcast = new(ipBroadcastCtl)

type ipBroadcastCtl struct{}

func (c *ipBroadcastCtl) 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.IpBroadcastService.Get(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, device))
}

func (c *ipBroadcastCtl) 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.IpBroadcastService.List(searchValue, current, size)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	pages := math.Ceil(float64(total) / float64(size))
	rsp := model.RsqIpBroadcastList{
		Current: current,
		Size:    size,
		Total:   int(total),
		Pages:   int(pages),
	}
	for _, device := range devices {

		rsp.Records = append(rsp.Records, device)
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

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

	var req dao.IpBroadcast
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.IpBroadcastService.CreateOrUpdate(claims.UserId, claims.TenantId, req)
	ctx.JSON(http.StatusOK, err)
}

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

	var req *model.ReqIpBroadcastRemove
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.IpBroadcastService.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 *ipBroadcastCtl) ImportExcel(ctx *gin.Context) {
}

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

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

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

	var req dao.IpBroadcast
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	if req.SoundVolume <= 1 {
		req.SoundVolume = 1
	}
	err2 := edge_service.IpCastControlService{}.SetVol(req.CastSn, req.SoundVolume)
	if err2 != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err2.Error(), nil))
		return
	}
	err := service.IpBroadcastService.CreateOrUpdate(claims.UserId, claims.TenantId, req)
	ctx.JSON(http.StatusOK, err)
}

type settingIpCastReq struct {
	ID        int `json:"id"`
	Directive int `json:"directive"`
}

func (c *ipBroadcastCtl) SettingIpCast(ctx *gin.Context) {
	var req settingIpCastReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	if req.Directive == 1 {
		err := edge_service.IpCastControlService{}.SetStop()
		if err != nil {
			ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
			return
		}
	}
	if req.Directive == 2 {
		c.CronSyncIpCastPaying(req.ID)
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
}

// 同步播放ip音柱节目
func (c *ipBroadcastCtl) CronSyncIpCastPaying(id int) {
	board := dao.IpBroadcast{}
	if id > 0 {
		board.ID = id
	}
	list, err := board.GetAllDevicesNotTenant()
	if err != nil {
		fmt.Printf("CronSyncIPCastPaying err = %v \n", err)
		return
	}
	for _, IPCast := range list {
		device, _ := service.IpBroadcastService.Get(IPCast.ID)
		//fmt.Printf("device = %v \n", device)
		if device.PlayState == "空闲" {
			playJson, ptype := service2.PublishLibrariesService.IPCastPaying(IPCast.ID)
			if playJson != "" {
				fmt.Printf("需要更新 \n")
				err := edge_service.IpCastControlService{}.PushPlay(playJson, ptype)
				if err != nil {
					fmt.Printf("err = %v \n", err)
					return
				}
			} else {
				//fmt.Printf("无需更新\n")
			}
		}
	}
}
