package com.yfd.platform.modules.basedata.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.AlarmThreshold;
import com.yfd.platform.modules.basedata.service.IAlarmThresholdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tangwei
 * @since 2024-04-16
 */
@RestController
@RequestMapping("/basedata/alarm-threshold")
@Api(value = "AlarmThresholdController", tags = "告警阈值设置")
public class AlarmThresholdController {

    @Resource
    private IAlarmThresholdService alarmThresholdService;

    @ApiOperation("分页查看告警阈值")
    @GetMapping("/getAlgorithmModelPage")
    public ResponseResult getAlgorithmModelPage(Page<Map<String, Object>> page) {
        Page<Map<String, Object>> mapPage = alarmThresholdService.pageMaps(page);
        return ResponseResult.successData(mapPage);
    }

    @ApiOperation("根据点位ID查看告警阈值")
    @GetMapping("/getAlgorithmModelById")
    public ResponseResult getAlgorithmModelById(String id) {
        List<AlarmThreshold> list =
                alarmThresholdService.list(new LambdaQueryWrapper<AlarmThreshold>().eq(AlarmThreshold::getDeviceId,
                        id));
        if (list.size() <= 0) {
            return ResponseResult.successData(null);
        }
        AlarmThreshold alarmThreshold = list.get(0);
        Map<String, Object> m = new HashMap<>(BeanUtil.beanToMap(alarmThreshold));
        Map<String, String> thresholdInterval = alarmThresholdService.getThresholdInterval(id);
        m.putAll(thresholdInterval);
        return ResponseResult.successData(m);
    }

    @ApiOperation("设置告警阈值")
    @PostMapping("/setAlgorithmModel")
    public ResponseResult updateAlgorithmModel(@RequestBody String alarmThresholdList) {
        List<AlarmThreshold> alarmThresholds = JSONUtil.toList(alarmThresholdList, AlarmThreshold.class);
        if (alarmThresholds.size() <= 0) {
            return ResponseResult.error("数据为空");
        }
        Set<String> ids =
                alarmThresholds.stream().map(AlarmThreshold::getDeviceId).collect(Collectors.toSet());
        // 删除之前的阈值
        alarmThresholdService.remove(new LambdaQueryWrapper<AlarmThreshold>().in(AlarmThreshold::getDeviceId, ids));
        boolean ok = alarmThresholdService.saveOrUpdateBatch(alarmThresholds);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

}
