package com.ruoyi.web.app;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.device.service.DeviceIotService;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.LogBizType;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.map.GeoUtils;
import com.ruoyi.iot.constants.IotConstants;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/app/device/iot")
public class AppDeviceIotController extends BaseController {

    @Autowired
    private DeviceIotService deviceIotService;

    @Autowired
    private DeviceService deviceService;


    @ApiOperation("用户响铃寻车")
    @PutMapping("/ring")
    @Log(title = "用户响铃寻车", businessType = BusinessType.OTHER, bizIdName = "arg0", bizType = LogBizType.DEVICE)
    public AjaxResult ring(@RequestParam(required = false) Long id, 
        @RequestParam(required = false) String sn, 
        @RequestParam(required = false) BigDecimal lon, 
        @RequestParam(required = false) BigDecimal lat) {
        DeviceVO device = null;
        if (id != null) {
            device = deviceService.selectDeviceById(id);
        } else {
            device = deviceService.selectDeviceBySn(sn);
        }
        ServiceUtil.assertion(device == null, "当前车辆不存在，无法响铃寻车");

        if (device.getAreaRequiredRingRadius() != null && device.getAreaRequiredRingRadius()) {
            BigDecimal distance = GeoUtils.calculateDistance(device.getLatitude(), device.getLongitude(), lat, lon);
            ServiceUtil.assertion(MathUtils.biggerThan(distance, device.getAreaRingRadius()), 
            "您当前距离车辆%s米，无法响铃寻车。请距离车辆%s米以内再试", distance, device.getAreaRingRadius());
        }

        return toAjax(deviceIotService.play(device, IotConstants.PLAY_WARNING, "用户响铃寻车", true));
    }
}
