package com.ruoyi.web.controller.device;

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.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.device.domain.entity.TsbDevice;
import com.ruoyi.device.domain.model.TsbUserDeviceBind;
import com.ruoyi.device.service.ITsbDeviceService;
import com.ruoyi.device.service.ITsbUserDeviceService;
import jakarta.servlet.http.HttpServletResponse;
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 java.util.List;

/**
 * 调试宝设备信息
 *
 * @author lwm
 */
@RestController
@RequestMapping("/tsb/device")
public class TsbDeviceController extends BaseController
{
    @Autowired
    private ITsbDeviceService tsbDeviceService;

    @Autowired
    private ITsbUserDeviceService tsbUserDeviceService;

    /**
     * 首页调试宝设备卡片（已登录/未登录分组由前端处理）
     */
    @GetMapping("/home/list")
    public AjaxResult homeList()
    {
        return success(tsbDeviceService.selectTsbDeviceHomeList(new TsbDevice()));
    }

    /**
     * 查询调试宝设备列表
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(TsbDevice query)
    {
        startPage();
        List<TsbDevice> list = tsbDeviceService.selectTsbDeviceList(query);
        return getDataTable(list);
    }

    /**
     * 导出调试宝设备列表
     */
    @Log(title = "调试宝设备", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('tsb:device:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, TsbDevice query)
    {
        List<TsbDevice> list = tsbDeviceService.selectTsbDeviceList(query);
        ExcelUtil<TsbDevice> util = new ExcelUtil<>(TsbDevice.class);
        util.exportExcel(response, list, "调试宝设备数据");
    }

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

    /**
     * 新增调试宝设备
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:add')")
    @Log(title = "调试宝设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TsbDevice device)
    {
        if (!tsbDeviceService.checkImeiUnique(device))
        {
            return error("新增调试宝设备失败，IMEI已存在");
        }
        else if (!tsbDeviceService.checkDeviceSnUnique(device))
        {
            return error("新增调试宝设备失败，设备SN码已存在");
        }
        device.setCreateBy(getUsername());
        return toAjax(tsbDeviceService.insertTsbDevice(device));
    }

    /**
     * 修改调试宝设备
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:edit')")
    @Log(title = "调试宝设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TsbDevice device)
    {
        if (!tsbDeviceService.checkImeiUnique(device))
        {
            return error("修改调试宝设备失败，IMEI已存在");
        }
        else if (!tsbDeviceService.checkDeviceSnUnique(device))
        {
            return error("修改调试宝设备失败，设备SN码已存在");
        }
        device.setUpdateBy(getUsername());
        return toAjax(tsbDeviceService.updateTsbDevice(device));
    }

    /**
     * 状态修改（列表开关）
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:edit')")
    @Log(title = "调试宝设备", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody TsbDevice device)
    {
        if (device.getDeviceId() == null)
        {
            return error("设备ID不能为空");
        }
        if (StringUtils.isEmpty(device.getStatus()))
        {
            return error("状态不能为空");
        }
        device.setUpdateBy(getUsername());
        return toAjax(tsbDeviceService.updateTsbDeviceStatus(device));
    }

    /**
     * 删除调试宝设备
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:remove')")
    @Log(title = "调试宝设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds)
    {
        return toAjax(tsbDeviceService.deleteTsbDeviceByIds(deviceIds));
    }

    /**
     * 强制删除调试宝设备（先解除用户与设备绑定，再逻辑删除设备）
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:remove')")
    @Log(title = "调试宝设备强制删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/force/{deviceIds}")
    public AjaxResult forceRemove(@PathVariable Long[] deviceIds)
    {
        return toAjax(tsbDeviceService.forceDeleteTsbDeviceByIds(deviceIds));
    }

    /**
     * 未绑定调试宝设备的用户（下拉框）
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:list')")
    @GetMapping("/unbindUsers")
    public AjaxResult unbindUsers()
    {
        return success(tsbUserDeviceService.selectUnbindUsers(new TsbUserDeviceBind()));
    }

    /**
     * 按设备ID查询当前绑定关系（无则 data 为 null）
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:list')")
    @GetMapping("/bindByDevice/{deviceId}")
    public AjaxResult bindByDevice(@PathVariable Long deviceId)
    {
        return success(tsbUserDeviceService.selectBindByDeviceId(deviceId));
    }

    /**
     * 用户绑定设备
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:edit')")
    @Log(title = "调试宝设备", businessType = BusinessType.GRANT)
    @PutMapping("/bindUserDevice")
    public AjaxResult bindUserDevice(Long userId, Long deviceId)
    {
        if (userId == null)
        {
            return error("用户ID不能为空");
        }
        if (deviceId == null)
        {
            return error("设备ID不能为空");
        }
        return toAjax(tsbUserDeviceService.insertUserDevice(userId, deviceId));
    }

    /**
     * 用户解绑设备
     */
    @PreAuthorize("@ss.hasPermi('tsb:device:edit')")
    @Log(title = "调试宝设备", businessType = BusinessType.GRANT)
    @PutMapping("/unbindUserDevice")
    public AjaxResult unbindUserDevice(Long userId, Long deviceId)
    {
        if (userId == null)
        {
            return error("用户ID不能为空");
        }
        if (deviceId == null)
        {
            return error("设备ID不能为空");
        }
        return toAjax(tsbUserDeviceService.deleteUserDevice(userId, deviceId));
    }
}
