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

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.coldchain.core.alarm.enums.SensorAlarmType;
import vip.xiaonuo.coldchain.core.alarm.service.SensorAlarmService;
import vip.xiaonuo.coldchain.modular.monitorsearchhistory.entity.SearchHistory;
import vip.xiaonuo.coldchain.modular.monitorsearchhistory.param.SearchHistoryAddParam;
import vip.xiaonuo.coldchain.modular.monitorsearchhistory.param.SearchHistoryIdParam;
import vip.xiaonuo.coldchain.modular.monitorsearchhistory.service.SearchHistoryService;
import vip.xiaonuo.common.pojo.CommonResult;

import java.util.List;

/**
 * 搜索记录控制器
 *
 * @author 黄渊昊
 */
@Tag(name = "搜索记录控制器")
@RestController
@Validated
public class SearchHistoryController {
    @Resource
    private SearchHistoryService searchHistoryService;
    @Resource
    private SensorAlarmService sensorAlarmService;

    /**
     * 获取最新十条搜索记录
     */
    @Operation(summary = "获取最新十条搜索记录")
    @GetMapping("/coldchain/searchhistory/getSearchHistory")
    public CommonResult<List<SearchHistory>> getSearchHistory() {
        return CommonResult.data(searchHistoryService.getSearchHistory());
    }

    /**
     * 获取报警次数最多的十条记录
     */
    @Operation(summary = "获取报警次数最多的十条记录")
    @GetMapping("/coldchain/searchhistory/topWarning")
    public CommonResult<JSONObject> topWarning(@RequestParam(value = "month", required = false) String month) {
        JSONObject obj = new JSONObject()
                .fluentPut("warning", sensorAlarmService.topWarning(month, List.of(SensorAlarmType.DATA_ALARM.getDeviceCode(), SensorAlarmType.DATA_RESTORE_ALARM.getDeviceCode())))
                .fluentPut("abnormal", sensorAlarmService.topWarning(month, List.of(SensorAlarmType.SENSOR_OFF_LINE.getDeviceCode(), SensorAlarmType.SENSOR_ON_LINE.getDeviceCode())));
        return CommonResult.data(obj);
    }

    /**
     * 新增搜索记录
     */
    @Operation(summary = "新增搜索记录")
    @GetMapping("/coldchain/searchhistory/add")
    public CommonResult<String> add(@Validated SearchHistoryAddParam searchHistoryAddParam) {
        searchHistoryService.add(searchHistoryAddParam);
        return CommonResult.ok();
    }

    /**
     * 删除搜索记录
     */
    @Operation(summary = "删除搜索记录")
    @GetMapping("/coldchain/searchhistory/delete")
    public CommonResult<String> delete(SearchHistoryIdParam searchHistoryIdParam) {
        searchHistoryService.delete(searchHistoryIdParam);
        return CommonResult.ok();
    }
}
