package controller

import (
	"cold-delivery/app/admin/model"
	"cold-delivery/app/admin/service"
	"cold-delivery/app/admin/service/dto"
	"cold-delivery/common/actions"
	"cold-delivery/common/nats/nats_server"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gogs.baozhida.cn/zoie/OAuth-core/api"
	_ "gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
)

type DeviceController struct {
	api.Api
}

// GetDevicePage 获取没有被保温箱和传感器绑定的设备列表
// @Summary 获取没有被保温箱和传感器绑定的设备列表
// @Description 获取没有被保温箱和传感器绑定的设备列表
// @Tags 设备
// @Param name query string false "设备名称"
// @Param pageSize query int false "页条数"
// @Param page query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]nats_server.Device_R}} "{"code": 200, "data": [...]}"
// @Router /api/device [get]
// @Security Bearer
func (e DeviceController) GetDevicePage(c *gin.Context) {
	coolerBoxSvc := service.CoolerBox{}
	iceLockerSvc := service.IceLocker{}
	req := dto.DeviceGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&coolerBoxSvc.Service).
		MakeService(&iceLockerSvc.Service).
		Bind(&req, binding.Query).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	list := make([]nats_server.Device_R, 0)
	p := actions.GetPermissionFromContext(c)

	var coolerBoxCount int64
	coolerBoxList := make([]model.CoolerBox, 0)
	var iceLockerCount int64
	iceLockerList := make([]model.IceLocker, 0)

	coolerBoxReq := dto.CoolerBoxGetPageReq{}
	coolerBoxReq.PageSize = 9999
	err = coolerBoxSvc.GetPage(&coolerBoxReq, &coolerBoxList, &coolerBoxCount, p)

	iceLockerReq := dto.IceLockerGetPageReq{}
	iceLockerReq.PageSize = 9999
	err = iceLockerSvc.GetPage(&iceLockerReq, &iceLockerList, &iceLockerCount, p)

	var count int64
	company, err := model.GetCompanyById(p.DeptId)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	list, count, err = nats_server.Cold_ReadDevice_List(req.Name, company.ColdKey, req.GetPageIndex(), 9999)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	var bindMap = make(map[string]struct{})
	for _, box := range coolerBoxList {
		bindMap[box.Sn] = struct{}{}
	}
	for _, iceLocker := range iceLockerList {
		bindMap[iceLocker.Sn] = struct{}{}
	}

	list2 := make([]nats_server.Device_R, 0)
	for i := 0; i < len(list); i++ {
		if _, ok := bindMap[list[i].T_sn]; ok {
			count--
			continue
		}
		list2 = append(list2, list[i])
	}

	// Fixme 测试完成之后删除
	//for i := 0; i < 20; i++ {
	//	list2 = append(list2, nats_server.Device_R{
	//		T_devName: fmt.Sprintf("冷冻柜%03d", i),
	//		T_sn:      fmt.Sprintf("2024114956064%03d", i),
	//	})
	//	count++
	//}

	//if len(list2) == 0 {
	//	e.PageOK(list2, len(list2), req.GetPageIndex(), req.GetPageSize(), "查询成功")
	//}

	// 计算总页数
	totalPages := (len(list2) + req.GetPageSize() - 1) / req.GetPageSize()

	// 如果n超出范围，返回错误
	if req.GetPageIndex() > totalPages {
		req.Page = totalPages
	}
	// 计算当前页的数据
	start := (req.GetPageIndex() - 1) * req.GetPageSize()
	end := start + req.GetPageSize()
	if end > len(list2) {
		end = len(list2)
	}
	currentPage := list2[start:end]

	e.PageOK(currentPage, len(list2), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// GetDeviceSensorPage 获取传感器列表
// @Summary 获取传感器列表
// @Description 获取传感器列表
// @Tags 设备
// @Param sn query string true "sn"
// @Success 200 {object} response.Response{data=response.Page{list=[]nats_server.DeviceSensor_R}} "{"code": 200, "data": [...]}"
// @Router /api/device-sensor [get]
// @Security Bearer
func (e DeviceController) GetDeviceSensorPage(c *gin.Context) {
	s := service.Device{}
	req := dto.DeviceSensorGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list, count, err := s.GetDeviceSensorList(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.PageOK(list, int(count), 0, 0, "查询成功")

}

// GetDeviceSensorDataPage 获取传感器数据列表
// @Summary 获取传感器数据列表
// @Description 获取传感器数据列表
// @Tags 设备
// @Param sn query string true "sn"
// @Param t_ids query string true "传感器id列表"
// @Param startTime query string true "开始时间"
// @Param endTime query string true "结束时间"
// @Success 200 {object} response.Response{data=response.Page{list=[]nats_server.DeviceSensor_R}} "{"code": 200, "data": [...]}"
// @Router /api/device-sensor [get]
// @Security Bearer
func (e DeviceController) GetDeviceSensorDataPage(c *gin.Context) {
	s := service.Device{}
	req := dto.DeviceSensorGetDataReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list, count, err := s.GetData(&req, p)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.PageOK(list, int(count), 0, 0, "查询成功")

}
