package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.entity.dto.DeviceQueryDTO;
import com.haha.entity.dto.DoorOpenDTO;
import com.haha.entity.dto.BindReplenisherDTO;
import com.haha.entity.dto.TemperatureDTO;
import com.haha.entity.dto.VolumeDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Device;
import com.haha.entity.Replenisher;
import com.haha.service.DeviceService;
import com.haha.service.DoorRecordService;
import com.haha.service.LayerTemplateService;
import com.haha.service.ReplenisherService;
import com.haha.common.vo.DeviceStatisticsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 设备管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/devices")
@RequiredArgsConstructor
public class DeviceController {

    private final DeviceService deviceService;
    private final DoorRecordService doorRecordService;
    private final LayerTemplateService layerTemplateService;
    private final ReplenisherService replenisherService;

    /**
     * 分页查询设备列表
     * @param queryDTO 查询参数
     * @return 设备列表
     */
    @RequirePermission("device:read")
    @GetMapping("/list")
    public Result<PageResult<Device>> list(DeviceQueryDTO queryDTO) {
        queryDTO.validate();

        IPage<Device> devicePage = deviceService.getPage(
                queryDTO.getPage(),
                queryDTO.getPageSize(),
                queryDTO.getDeviceId(),
                queryDTO.getShopId(),
                queryDTO.getStatus()
        );

        return Result.success("查询成功", PageResult.of(devicePage));
    }

    /**
     * 获取设备详情
     * @param id 设备ID
     * @return 设备详情
     */
    @RequirePermission("device:read")
    @GetMapping("/{id}")
    public Result<Device> getById(@PathVariable Long id) {
        Device device = deviceService.getDetailById(id);
        if (device == null) {
            return Result.error(404, "设备不存在");
        }
        return Result.success("查询成功", device);
    }

    /**
     * 获取设备统计数据
     * @return 统计数据
     */
    @RequirePermission("device:read")
    @GetMapping("/statistics")
    public Result<DeviceStatisticsVO> getStatistics() {
        DeviceStatisticsVO statistics = deviceService.getStatistics();
        return Result.success("查询成功", statistics);
    }

    /**
     * 远程开门
     * @param id 设备ID
     * @param params 开门参数
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @Log(module = "设备管理", operation = OperationType.OTHER, summary = "远程开门")
    @PostMapping("/{id}/open")
    public Result<Void> openDoor(@PathVariable Long id, @RequestBody DoorOpenDTO dto) {
        boolean success = deviceService.openDoor(id, dto.getDoorIndex());
        return success ? Result.success("开门指令已发送", null) : Result.error(500, "开门失败");
    }

    /**
     * 设置温度
     * @param id 设备ID
     * @param params 温度参数
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @PutMapping("/{id}/temperature")
    public Result<Void> setTemperature(@PathVariable Long id, @RequestBody TemperatureDTO dto) {
        boolean success = deviceService.setTemperature(id, dto.getTemperature());
        return success ? Result.success("温度设置成功", null) : Result.error(500, "设置失败");
    }

    /**
     * 设置音量
     * @param id 设备 ID
     * @param params 音量参数
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @PutMapping("/{id}/volume")
    public Result<Void> setVolume(@PathVariable Long id, @RequestBody VolumeDTO dto) {
        boolean success = deviceService.setVolume(id, dto.getVolume());
        return success ? Result.success("音量设置成功", null) : Result.error(500, "设置失败");
    }

    /**
     * 查询设备的开关门记录
     * @param deviceId 设备 ID
     * @param page 页码
     * @param pageSize 每页数量
     * @return 开关门记录列表
     */
    @RequirePermission("device:read")
    @GetMapping("/{deviceId}/door-records")
    public Result<PageResult<com.haha.entity.DoorRecord>> getDoorRecords(
            @PathVariable String deviceId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        IPage<com.haha.entity.DoorRecord> recordPage = doorRecordService.getDeviceRecordsByPage(deviceId, page, pageSize);
        return Result.success("查询成功", PageResult.of(recordPage));
    }

    /**
     * 获取设备商品配置
     * @param deviceId 设备编号
     * @return 商品配置数据
     */
    @RequirePermission("device:read")
    @GetMapping("/{deviceId}/product-config")
    public Result<Map<String, Object>> getProductConfig(@PathVariable String deviceId) {
        Map<String, Object> config = layerTemplateService.getProductConfig(deviceId);
        return Result.success("查询成功", config);
    }

    /**
     * 保存设备商品配置
     * @param deviceId 设备编号
     * @param data 配置数据
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @Log(module = "设备管理", operation = OperationType.UPDATE, summary = "保存设备商品配置")
    @PostMapping("/{deviceId}/product-config")
    public Result<Void> saveProductConfig(@PathVariable String deviceId, @RequestBody Map<String, Object> data) {
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> floors = (List<Map<String, Object>>) data.get("floors");
        
        layerTemplateService.saveProductConfig(deviceId, floors);
        return Result.success("保存成功", null);
    }

    // ==================== 补货员管理 ====================

    /**
     * 获取设备绑定的补货员列表
     *
     * @param deviceId 设备SN号
     * @return 补货员列表
     */
    @RequirePermission("device:read")
    @GetMapping("/{deviceId}/replenishers")
    public Result<List<Replenisher>> getReplenishers(@PathVariable String deviceId) {
        List<Replenisher> replenishers = replenisherService.getReplenishersByDeviceId(deviceId);
        return Result.success("查询成功", replenishers);
    }

    /**
     * 绑定补货员到设备
     *
     * @param deviceId 设备SN号
     * @param dto      补货员ID
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @Log(module = "设备管理", operation = OperationType.UPDATE, summary = "绑定补货员到设备")
    @PostMapping("/{deviceId}/replenishers")
    public Result<Void> bindReplenisher(@PathVariable String deviceId, @RequestBody BindReplenisherDTO dto) {
        replenisherService.bindDevices(dto.getReplenisherId(), List.of(deviceId));
        return Result.success("绑定成功");
    }

    /**
     * 解绑设备的补货员
     *
     * @param deviceId      设备SN号
     * @param replenisherId 补货员ID
     * @return 操作结果
     */
    @RequirePermission("device:update")
    @Log(module = "设备管理", operation = OperationType.UPDATE, summary = "解绑设备补货员")
    @DeleteMapping("/{deviceId}/replenishers/{replenisherId}")
    public Result<Void> unbindReplenisher(@PathVariable String deviceId, @PathVariable Long replenisherId) {
        replenisherService.unbindDevice(replenisherId, deviceId);
        return Result.success("解绑成功");
    }

    /**
     * 查询设备详细状态（含门状态、锁状态、摄像头状态、网络状态）
     * @param deviceId 设备SN号
     * @return 设备详细状态
     */
    @RequirePermission("device:read")
    @GetMapping("/{deviceId}/detail-status")
    public Result<Map<String, Object>> getDetailStatus(@PathVariable String deviceId) {
        Map<String, Object> status = deviceService.getDeviceDetailStatus(deviceId);
        return Result.success("查询成功", status);
    }
}
