package com.ruoyi.web.bst;

import com.ruoyi.bst.booth.service.BoothValidator;
import com.ruoyi.bst.device.domain.Device;
import com.ruoyi.bst.device.domain.DeviceQuery;
import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.device.service.DeviceConverter;
import com.ruoyi.bst.device.service.DeviceIotService;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.device.service.DeviceValidator;
import com.ruoyi.bst.store.service.StoreValidator;
import com.ruoyi.bst.storeStaff.domain.enums.StoreStaffPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.ValidGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.iot.constants.IotConstants;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 设备Controller
 *
 * @author ruoyi
 * @date 2025-04-23
 */
@RestController
@RequestMapping("/bst/device")
public class DeviceController extends BaseController
{
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceConverter deviceConverter;
    @Autowired
    private DeviceIotService deviceIotService;
    @Autowired
    private BoothValidator boothValidator;
    @Autowired
    private DeviceValidator deviceValidator;
    @Autowired
    private StoreValidator storeValidator;

    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('bst:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceQuery query)
    {
        startPage();
        startOrderBy();
        query.setDeleted(false);
        query.setScope(true);
        query.addStorePermission(StoreStaffPermission.DEVICE_VIEW.getCode());
        List<DeviceVO> list = deviceService.selectDeviceList(query);
        deviceIotService.pullDeviceInfoList(list, IotConstants.ONLINE_TYPE_COMMAND);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('bst:device:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceQuery query)
    {
        List<DeviceVO> list = deviceService.selectDeviceList(query);
        ExcelUtil<DeviceVO> util = new ExcelUtil<DeviceVO>(DeviceVO.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('bst:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
    {
        return success(deviceService.selectDeviceByDeviceId(deviceId));
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('bst:device:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.Create.class) Device device)
    {
        deviceConverter.toPoByCreate(device);
        return toAjax(deviceService.insertDevice(device));
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('bst:device:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class)Device device)
    {
        if (device.getBoothId() != null){
            if (!boothValidator.canEdit(device.getBoothId())){
                return AjaxResult.error("您无权限修改该卡座信息");
            }
        }

        deviceConverter.toPoByUpdate(device);
        return toAjax(deviceService.updateDevice(device));
    }

    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('bst:device:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deviceService.deleteDeviceByDeviceIds(ids));
    }

    /**
     * 逻辑删除设备
     */
    @PreAuthorize("@ss.hasPermi('bst:device:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/logic/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(deviceService.logicDel(ids));
    }

    @PreAuthorize("@ss.hasPermi('bst:device:bindMch')")
    @Log(title = "设备绑定商户", businessType = BusinessType.OTHER)
    @PutMapping("/bindMch")
    public AjaxResult bindMch(@RequestBody Device device, @RequestParam Long mchId) {
        if (device.getDeviceId() == null && device.getDeviceNo() == null) {
            return error("设备ID和SN不能同时为空");
        }
        // 绑定设备
        if (device.getDeviceId() != null) {
            return AjaxResult.success("操作成功", deviceService.bindMchById(device.getDeviceId(), mchId));
        } else {
            return AjaxResult.success("操作成功", deviceService.bindMchBySn(device.getDeviceNo(), mchId));
        }
    }

    @ApiOperation("解除设备绑定商户")
    @PreAuthorize("@ss.hasPermi('bst:device:unbind')")
    @Log(title = "设备", businessType = BusinessType.OTHER)
    @DeleteMapping("/{deviceId}/unbind")
    public AjaxResult unbind(@PathVariable @ApiParam("设备id") Long deviceId) {
        return toAjax(deviceService.unbind(deviceId));
    }

    @PreAuthorize("@ss.hasPermi('bst:device:setTime')")
    @Log(title = "设置设备开启时长", businessType = BusinessType.OTHER)
    @PutMapping("/setTime/{deviceId}")
    public AjaxResult setTime(@PathVariable @ApiParam("设备id") Long deviceId,
                              @ApiParam("时长") @RequestParam Long duration) {
        return toAjax(deviceService.setTimeDb(deviceId, duration));
    }

    @PreAuthorize("@ss.hasPermi('bst:device:changeStore')")
    @Log(title = "设备更改投放店铺", businessType = BusinessType.OTHER)
    @PutMapping("/changeStore")
    public AjaxResult changeStore(@RequestBody Device device) {
        if (device.getStoreId() == null) {
            return AjaxResult.error("店铺ID不能为空");
        }
        if (device.getDeviceId() == null) {
            return AjaxResult.error("设备ID不能为空");
        }
        // 设备权限校验
        if (!deviceValidator.canOperate(device.getDeviceId())){
            return AjaxResult.error("您无权限操作当前设备");
        }
        // 店铺权限校验
        if (!storeValidator.canEdit(device.getStoreId())){
            return AjaxResult.error("您无权限操作当前店铺");
        }
        return AjaxResult.success(deviceService.updateDeviceStore(device));
    }


}
