package com.zsc.edu.gateway.modules.iot.device.controller;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.gateway.framework.message.sse.SseConfig;
import com.zsc.edu.gateway.framework.mybatisplus.DataPermission;
import com.zsc.edu.gateway.modules.iot.device.dto.BatchDeviceDto;
import com.zsc.edu.gateway.modules.iot.device.dto.DeviceDto;
import com.zsc.edu.gateway.modules.iot.device.dto.DeviceServeDto;
import com.zsc.edu.gateway.modules.iot.device.entity.Device;
import com.zsc.edu.gateway.modules.iot.device.query.DeviceQuery;
import com.zsc.edu.gateway.modules.iot.device.service.DeviceService;
import com.zsc.edu.gateway.modules.iot.device.vo.DeviceVo;
import com.zsc.edu.gateway.modules.iot.record.entity.RecordData;
import com.zsc.edu.gateway.modules.iot.record.service.RecordDataService;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * @author zhuang
 */
@AllArgsConstructor
@RestController
@RequestMapping("api/rest/device")
public class DeviceController {

    DeviceService service;

    RecordDataService recordService;
    @Resource
    private SseConfig sseConfig;

    /**
     * 创建设备
     */
    @PostMapping
    @PreAuthorize("hasAuthority('iot:device:create')")
    public Device create(@RequestBody DeviceDto deviceDto) {
        return service.create(deviceDto);
    }


    /**
     * 批量创建设备
     */
    @PostMapping("batch")
    @PreAuthorize("hasAuthority('iot:device:create')")
    public List<Device> batchCreate(@RequestBody BatchDeviceDto batchDeviceDto) {
        return service.batchCreate(batchDeviceDto);
    }


    /**
     * 更新设备
     */
    @PatchMapping("{id}")
    @PreAuthorize("hasAuthority('iot:device:update')")
    public Device update(@RequestBody DeviceDto deviceDto, @PathVariable("id") Long id) {
        return service.update(deviceDto, id);
    }


    /**
     * 分页查询设备
     */
    @DataPermission
    @GetMapping
    @PreAuthorize("hasAuthority('iot:device:query')")
    public IPage<Device> query(Page<Device> page, DeviceQuery query) {
        return service.query(page, query);
    }

    /**
     * 删除设备
     */
    @DeleteMapping("{id}")
    @PreAuthorize("hasAuthority('iot:device:delete')")
    public Boolean delete(@PathVariable("id") Long id) {
        return service.removeById(id);
    }

    /**
     * 设备
     * 查询详情
     */
    @GetMapping("{id}")
    @PreAuthorize("hasAuthority('iot:device:query')")
    public DeviceVo detail(@PathVariable("id") Long id) {
        return service.detail(id);
    }


    /**
     * 手动触发事件
     */
    @PostMapping("serve")
    @PreAuthorize("hasAuthority('iot:device:create')")
    public ResponseEntity<String> serve(@RequestBody DeviceServeDto dto) {
        if (service.serve(dto)) {
            return ResponseEntity.ok("服务执行成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("服务执行失败");
        }
    }

    /**
     * 查询设备上报记录
     */
    @GetMapping("record/data")
    @PreAuthorize("hasAuthority('iot:device:query')")
    @DataPermission
    public IPage<RecordData> recordData(Page<RecordData> page, String clientId) {
        return recordService.query(page, clientId);
    }
    /**
     * 获取设备信息
     */
    @GetMapping(value = "/sse/status", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PreAuthorize("hasAuthority('iot:device:query')")
    @DataPermission
    public SseEmitter status() {
        return sseConfig.sendSseEvents(service::status);
    }

    /**
     * 获取设备上报信息
     */
    @GetMapping(value = "/sse/record/status", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PreAuthorize("hasAuthority('iot:device:query')")
    @DataPermission
    public SseEmitter recordDataStatus() {
        return sseConfig.sendSseEvents(recordService::recordDataStatus);
    }

    /**
     * 获取告警信息
     */
    @GetMapping(value = "/sse/data/status", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PreAuthorize("hasAuthority('iot:device:query')")
    @DataPermission
    public SseEmitter dataWarning() {
        return sseConfig.sendSseEvents(recordService::dataWarning);
    }

    /**
     * 下发命令
     */
    @PostMapping("/send")
    public String send(Long deviceId, Integer qos, @RequestBody JSONObject paras) throws JSONException {
        return service.send(deviceId, qos, paras);
    }

}
