package vip.xiaonuo.coldchain.modular.app.controller;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.coldchain.modular.app.param.*;
import vip.xiaonuo.coldchain.modular.app.service.AppDeviceService;
import vip.xiaonuo.coldchain.modular.app.service.MessageService;
import vip.xiaonuo.common.pojo.CommonResult;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Tag(name = "APP移动端控制器")
@RestController
@RequestMapping("/coldchain/api/app")
@Validated
public class AppController {
    @Autowired
    private AppDeviceService appDeviceService;
    @Autowired
    private MessageService messageService;


    @GetMapping("/device-status")
    @Operation(summary = "设备总缆")
    public CommonResult<DeviceStatus> getDeviceStatus(String keyword,String roomId) {
        DeviceStatus deviceStatus = appDeviceService.getDeviceStatus(keyword,roomId);
        return CommonResult.data(deviceStatus);
    }

    @Operation(summary = "分页设备")
    @GetMapping("/device/page")
    public CommonResult<Page<AppDevice>> devicePage(AppDevicePageParam appDevicePageParam) {
        return CommonResult.data(appDeviceService.pageDevices(appDevicePageParam));
    }

    @Operation(summary = "分页设备关键字查询")
    @GetMapping("/device/search/page")
    @Deprecated
    public CommonResult<Page<AppDevice>> deviceSearchPage(AppDevicePageParam appDevicePageParam) {
        // 关键字为空，调用原来的接口
        if (StrUtil.isBlank(appDevicePageParam.getSearchKey())) {
            return devicePage(appDevicePageParam);
        }
        return CommonResult.data(appDeviceService.pageSearchDevices(appDevicePageParam));
    }

    /**
     * 添加设备接口
     *
     * @param device 设备对象
     * @return ResponseEntity
     */
    @PostMapping("/device/add")
    @Operation(summary = "添加采集器")
    public ResponseEntity<String> addDevice(@RequestBody @Valid AppDeviceAddParam device) {
        // 设备对象校验通过后，调用业务逻辑服务层进行保存操作
        boolean isSuccess = appDeviceService.addDevice(device);
        // 添加设备完成一样要获取设备默认参数
        if (isSuccess) {
            return ResponseEntity.ok("设备添加成功");
        } else {
            return ResponseEntity.status(500).body("设备添加失败");
        }
    }

    // 查询设备数据接口（POST）
    @PostMapping("/device/view")
    @Operation(summary = "查询采集设备数据")
    public CommonResult<SensorEchartDataResult> queryDeviceData(@RequestBody @Valid AppDeviceQueryParams appDeviceQueryParams) {
        return CommonResult.data(appDeviceService.queryDataByDeviceIdAndRoads(appDeviceQueryParams));
    }

    @PostMapping("/device/indicators")
    @Operation(summary = "查询采集设备数据")
    public CommonResult<SensorIndicator> indicators(@RequestBody @Valid AppIndicatorQueryParams appDeviceQueryParams) {
        SensorIndicator sensorIndicator = appDeviceService.indicators(appDeviceQueryParams);
        return CommonResult.data(sensorIndicator);
    }


    @PostMapping("/device/alarm")
    @Operation(summary = "更新设备预警")
    public CommonResult<Boolean> deviceAlarm(@RequestBody @Valid AppDeviceAlarmParam appDeviceAlarmParam) {
        Boolean alarm = appDeviceService.updateDeviceAlarm(appDeviceAlarmParam);
        return CommonResult.result(alarm, alarm);
    }

    @PostMapping("/device/update")
    @Operation(summary = "更新设备点位信息")
    public CommonResult<Boolean> deviceUpdate(@RequestBody @Valid AppDeviceUpdateParam appDeviceAlarmParam) {
        Boolean alarm = appDeviceService.updateDeviceInfo(appDeviceAlarmParam);
        return CommonResult.result(alarm, alarm);
    }

    // 下载设备数据接口（POST）
    @PostMapping("/device/download/{deviceCode}")
    @Operation(summary = "下载采集器设备数据接口")
    public ResponseEntity<InputStreamResource> downloadDeviceData(@RequestBody AppDeviceQueryParams appDeviceQueryParams, @PathVariable(value = "deviceCode", required = true) String deviceCode) throws IOException {
        return null;
    }

    @GetMapping("/message/unread/count")
    @Operation(summary = "获取未读消息统计")
    public Map<String, Long> getUnreadMessagesCount() {
        return messageService.getUnreadMessagesCount();
    }

    @GetMapping("/message/page")
    public CommonResult<Page<Message>> getMessages(MessagePageParam messagePageParam) {
        Page<Message> rlt = messageService.getMessages(messagePageParam);
        return CommonResult.data(rlt);
    }


    @PostMapping("/message/mark-read")
    @Operation(summary = "批量设置消息为已读")
    public void markMessagesAsRead(@RequestBody List<Long> messageIds) {
        messageService.markMessagesAsRead(messageIds);
    }
}