package com.kym.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.kym.common.R;
import com.kym.entity.DeviceConfig;
import com.kym.entity.WashDevice;
import com.kym.entity.awoara.OrderInfo;
import com.kym.entity.awoara.response.HardwareInfo;
import com.kym.entity.awoara.response.State;
import com.kym.service.DeviceHealthProbeService;
import com.kym.service.WashDeviceService;
import com.kym.service.awoara.AwoaraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 设备远程控制 API（调试用）
 *
 * @author skyline
 */
@Slf4j
@RestController
@RequestMapping("/washDevice/remote")
public class WashDeviceRemoteController {

    private final WashDeviceService washDeviceService;
    private final AwoaraService awoaraService;
    private final DeviceHealthProbeService deviceHealthProbeService;

    public WashDeviceRemoteController(WashDeviceService washDeviceService, AwoaraService awoaraService,
                                       DeviceHealthProbeService deviceHealthProbeService) {
        this.washDeviceService = washDeviceService;
        this.awoaraService = awoaraService;
        this.deviceHealthProbeService = deviceHealthProbeService;
    }

    /**
     * 查询设备实时状态
     */
    @SaCheckPermission("washDevice.list")
    @PostMapping("/queryState")
    R<?> queryState(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        State state = awoaraService.queryState(productKey, deviceName);
        return R.success(state);
    }

    /**
     * 查询设备上的订单信息
     */
    @SaCheckPermission("washDevice.list")
    @PostMapping("/queryOrder")
    R<?> queryOrder(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        String orderId = params.get("orderId");
        OrderInfo orderInfo = awoaraService.queryOrder(productKey, deviceName, orderId);
        return R.success(orderInfo);
    }

    /**
     * 查询硬件信息
     */
    @SaCheckPermission("washDevice.list")
    @PostMapping("/queryHardwareInfo")
    R<?> queryHardwareInfo(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        HardwareInfo info = awoaraService.queryHardwareInfo(productKey, deviceName);
        return R.success(info);
    }

    /**
     * 读取设备配置
     */
    @SaCheckPermission("washDevice.list")
    @PostMapping("/readConfig")
    R<?> readConfig(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        DeviceConfig config = awoaraService.readConfig(productKey, deviceName);
        return R.success(config);
    }

    /**
     * 写入设备配置
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/writeConfig")
    R<?> writeConfig(@RequestBody Map<String, Object> params) {
        String productKey = (String) params.get("productKey");
        String deviceName = (String) params.get("deviceName");
        @SuppressWarnings("unchecked")
        Map<String, Object> configMap = (Map<String, Object>) params.get("config");
        DeviceConfig config = new DeviceConfig();
        if (configMap.get("idleTimeout") != null) config.setIdleTimeout((Integer) configMap.get("idleTimeout"));
        if (configMap.get("operationTimeout") != null) config.setOperationTimeout((Integer) configMap.get("operationTimeout"));
        if (configMap.get("priceWater") != null) config.setPriceWater((Integer) configMap.get("priceWater"));
        if (configMap.get("priceFoam") != null) config.setPriceFoam((Integer) configMap.get("priceFoam"));
        if (configMap.get("priceCleaner") != null) config.setPriceCleaner((Integer) configMap.get("priceCleaner"));
        if (configMap.get("priceTap") != null) config.setPriceTap((Integer) configMap.get("priceTap"));
        if (configMap.get("priceUserExt") != null) config.setPriceUserExt((Integer) configMap.get("priceUserExt"));
        if (configMap.get("priceCoat") != null) config.setPriceCoat((Integer) configMap.get("priceCoat"));
        if (configMap.get("priceBlow") != null) config.setPriceBlow((Integer) configMap.get("priceBlow"));
        if (configMap.get("priceSpace") != null) config.setPriceSpace((Integer) configMap.get("priceSpace"));
        if (configMap.get("maintenanceMode") != null) config.setMaintenanceMode((Integer) configMap.get("maintenanceMode"));
        if (configMap.get("soundVolume") != null) config.setSoundVolume((Integer) configMap.get("soundVolume"));
        if (configMap.get("workMode") != null) config.setWorkMode((Integer) configMap.get("workMode"));
        if (configMap.get("screenType") != null) config.setScreenType((Integer) configMap.get("screenType"));
        if (configMap.get("videoSource") != null) config.setVideoSource((Integer) configMap.get("videoSource"));
        if (configMap.get("videoPlayDelay") != null) config.setVideoPlayDelay((Integer) configMap.get("videoPlayDelay"));
        if (configMap.get("workLightDelay") != null) config.setWorkLightDelay((Integer) configMap.get("workLightDelay"));
        if (configMap.get("billDelay") != null) config.setBillDelay((Integer) configMap.get("billDelay"));
        if (configMap.get("tapOnDelay") != null) config.setTapOnDelay((Integer) configMap.get("tapOnDelay"));
        if (configMap.get("noticeThresholdIdle") != null) config.setNoticeThresholdIdle((Integer) configMap.get("noticeThresholdIdle"));
        if (configMap.get("noticeThresholdOperation") != null) config.setNoticeThresholdOperation((Integer) configMap.get("noticeThresholdOperation"));
        if (configMap.get("quickOpenMoney") != null) config.setQuickOpenMoney((Integer) configMap.get("quickOpenMoney"));
        if (configMap.get("motorOnDelay") != null) config.setMotorOnDelay((Integer) configMap.get("motorOnDelay"));
        if (configMap.get("motorOffDelay") != null) config.setMotorOffDelay((Integer) configMap.get("motorOffDelay"));
        if (configMap.get("motorOnInterval") != null) config.setMotorOnInterval((Integer) configMap.get("motorOnInterval"));
        if (configMap.get("motorFlowOn") != null) config.setMotorFlowOn((Boolean) configMap.get("motorFlowOn"));
        if (configMap.get("motorFlowOff") != null) config.setMotorFlowOff((Boolean) configMap.get("motorFlowOff"));
        if (configMap.get("userMessage1") != null) config.setUserMessage1((String) configMap.get("userMessage1"));
        if (configMap.get("userMessage2") != null) config.setUserMessage2((String) configMap.get("userMessage2"));
        if (configMap.get("workTimePeriod1") != null) config.setWorkTimePeriod1((String) configMap.get("workTimePeriod1"));
        if (configMap.get("workTimePeriod2") != null) config.setWorkTimePeriod2((String) configMap.get("workTimePeriod2"));
        if (configMap.get("lightTimePeriod1") != null) config.setLightTimePeriod1((String) configMap.get("lightTimePeriod1"));
        if (configMap.get("lightTimePeriod2") != null) config.setLightTimePeriod2((String) configMap.get("lightTimePeriod2"));
        awoaraService.writeConfig(productKey, deviceName, config);
        return R.success();
    }

    /**
     * 重启设备
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/reboot")
    R<?> reboot(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        awoaraService.reboot(productKey, deviceName);
        return R.success();
    }

    /**
     * 在设备屏幕显示消息
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/showMsgbox")
    R<?> showMsgbox(@RequestBody Map<String, Object> params) {
        String productKey = (String) params.get("productKey");
        String deviceName = (String) params.get("deviceName");
        String title = (String) params.get("title");
        String content = (String) params.get("content");
        int seconds = params.get("seconds") != null ? (Integer) params.get("seconds") : 10;
        awoaraService.showMsgbox(productKey, deviceName, title, content, seconds);
        return R.success();
    }

    /**
     * 隐藏设备屏幕消息
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/hideMsgbox")
    R<?> hideMsgbox(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        awoaraService.hideMsgbox(productKey, deviceName);
        return R.success();
    }

    /**
     * 探测设备连通性，在线则自动恢复设备状态和故障记录
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/probeAndRecover")
    R<?> probeAndRecover(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        var device = washDeviceService.lambdaQuery()
                .eq(WashDevice::getProductKey, productKey)
                .eq(WashDevice::getDeviceName, deviceName)
                .one();
        if (device == null) {
            return R.failed(400, "设备不存在");
        }
        boolean recovered = deviceHealthProbeService.probeAndRecover(device);
        return recovered ? R.success("设备在线，已触发恢复") : R.failed(400, "设备离线，未能恢复");
    }

    /**
     * 强制关闭订单
     */
    @SaCheckPermission("washDevice.modify")
    @PostMapping("/forceCloseOrder")
    R<?> forceCloseOrder(@RequestBody Map<String, String> params) {
        String productKey = params.get("productKey");
        String deviceName = params.get("deviceName");
        awoaraService.forceCloseOrder(productKey, deviceName);
        return R.success();
    }
}
