package com.ycwl.basic.integration.device.service;

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.device.client.DeviceV2Client;
import com.ycwl.basic.integration.device.dto.config.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceConfigIntegrationService {

    private final DeviceV2Client deviceConfigV2Client;
    private final IntegrationFallbackService fallbackService;
    
    private static final String SERVICE_NAME = "zt-device";

    public List<DeviceConfigV2DTO> getDeviceConfigs(Long deviceId) {
        CommonResponse<List<DeviceConfigV2DTO>> response = deviceConfigV2Client.getDeviceConfigs(deviceId);
        return handleResponse(response, "获取设备配置列表失败");
    }

    public List<DeviceConfigV2DTO> getDeviceConfigsByNo(String deviceNo) {
        log.debug("根据设备编号获取配置列表, deviceNo: {}", deviceNo);
        CommonResponse<List<DeviceConfigV2DTO>> response = deviceConfigV2Client.getDeviceConfigsByNo(deviceNo);
        return handleResponse(response, "根据设备编号获取配置列表失败");
    }

    public DeviceConfigV2DTO getDeviceConfigByKey(Long deviceId, String configKey) {
        CommonResponse<DeviceConfigV2DTO> response = deviceConfigV2Client.getDeviceConfigByKey(deviceId, configKey);
        return handleResponse(response, "根据键获取设备配置失败");
    }

    public DeviceConfigV2DTO createDeviceConfig(Long deviceId, CreateDeviceConfigRequest request) {
        log.debug("创建设备配置, deviceId: {}, configKey: {}", deviceId, request.getConfigKey());
        CommonResponse<DeviceConfigV2DTO> response = deviceConfigV2Client.createDeviceConfig(deviceId, request);
        return handleResponse(response, "创建设备配置失败");
    }

    public void updateDeviceConfig(Long deviceId, Long configId, UpdateDeviceConfigRequest request) {
        log.debug("更新设备配置, deviceId: {}, configId: {}", deviceId, configId);
        CommonResponse<String> response = deviceConfigV2Client.updateDeviceConfig(deviceId, configId, request);
        handleResponse(response, "更新设备配置失败");
    }

    public void deleteDeviceConfig(Long deviceId, Long configId) {
        log.debug("删除设备配置, deviceId: {}, configId: {}", deviceId, configId);
        CommonResponse<String> response = deviceConfigV2Client.deleteDeviceConfig(deviceId, configId);
        handleResponse(response, "删除设备配置失败");
    }

    /**
     * 批量更新设备配置
     */
    public BatchUpdateResponse batchUpdateDeviceConfig(Long deviceId, BatchDeviceConfigRequest request) {
        log.debug("批量更新设备配置, deviceId: {}, configs count: {}", deviceId, request.getConfigs().size());
        CommonResponse<BatchUpdateResponse> response = deviceConfigV2Client.batchUpdateDeviceConfig(deviceId, request);
        return handleResponse(response, "批量更新设备配置失败");
    }



    /**
     * 获取设备特定配置值
     */
    public String getDeviceConfigValue(Long deviceId, String configKey) {
        DeviceConfigV2DTO config = getDeviceConfigByKey(deviceId, configKey);
        return config != null ? config.getConfigValue() : null;
    }

    /**
     * 创建批量配置请求构建器
     */
    public BatchDeviceConfigRequestBuilder createBatchConfigBuilder() {
        return new BatchDeviceConfigRequestBuilder();
    }
    
    /**
     * 批量配置请求构建器
     */
    public static class BatchDeviceConfigRequestBuilder {
        private final BatchDeviceConfigRequest request = new BatchDeviceConfigRequest();
        
        public BatchDeviceConfigRequestBuilder() {
            request.setConfigs(new java.util.ArrayList<>());
        }
        
        /**
         * 添加配置项（有默认配置的情况，只需提供key和value）
         */
        public BatchDeviceConfigRequestBuilder addConfig(String configKey, String configValue) {
            BatchDeviceConfigRequest.BatchDeviceConfigItem item = new BatchDeviceConfigRequest.BatchDeviceConfigItem();
            item.setConfigKey(configKey);
            item.setConfigValue(configValue);
            request.getConfigs().add(item);
            return this;
        }
        
        /**
         * 添加配置项（完整参数，用于自定义配置）
         */
        public BatchDeviceConfigRequestBuilder addConfig(String configKey, String configValue, 
                                                        String configType, String description) {
            BatchDeviceConfigRequest.BatchDeviceConfigItem item = new BatchDeviceConfigRequest.BatchDeviceConfigItem();
            item.setConfigKey(configKey);
            item.setConfigValue(configValue);
            item.setConfigType(configType);
            item.setDescription(description);
            request.getConfigs().add(item);
            return this;
        }

        /**
         * 构建请求对象
         */
        public BatchDeviceConfigRequest build() {
            return request;
        }
    }

    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.isSuccess()) {
            String msg = response != null && response.getMessage() != null 
                        ? response.getMessage() 
                        : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, "zt-device");
        }
        return response.getData();
    }
}