import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/device_control_bo.dart';
import 'package:smart_hotel_app/repositories/device_control_repository.dart';
import 'package:smart_hotel_app/services/device_control_service.dart';
import 'package:smart_hotel_app/views/home/device/cubit/device_state.dart';

class DeviceCubit extends Cubit<DeviceState> {
  final DeviceControlService _service;
  final int _deviceId;

  DeviceCubit({
    DeviceControlService? service,
    required int deviceId,
  })  : _service = service ??
            DeviceControlService(
              repository: DeviceControlRepository(),
            ),
        _deviceId = deviceId,
        super(const DeviceState()) {
    loadDetail();
  }

  Future<void> loadDetail() async {
    emit(const DeviceState(isLoading: true));
    try {
      final detail = await _service.getDetail(deviceId: _deviceId);
      emit(DeviceState(deviceInfo: _mapToDeviceInfo(detail)));
    } catch (e) {
      emit(DeviceState(error: e.toString()));
    }
  }

  DeviceInfo _mapToDeviceInfo(DeviceControlBO detail) {
    final basic = detail.deviceBasicInfo;
    final params = detail.realtimeParams;

    final status = basic.onlineStatus == '1' ? '在线' : '离线';

    final powerData = detail.trendChart.dataPoints
        .map((p) => p.power.toInt())
        .toList();
    final tempData = detail.trendChart.dataPoints
        .map((p) => p.temperature.toInt())
        .toList();
    final timeLabels = detail.trendChart.dataPoints
        .map((p) => p.time)
        .toList();

    return DeviceInfo(
      deviceName: basic.deviceName,
      deviceCode: basic.deviceCode,
      location: basic.deviceLocation,
      status: status,
      voltage: params.voltage,
      current: params.current,
      power: params.activePower,
      temperature: params.deviceTemperature,
      powerData: powerData,
      tempData: tempData,
      timeLabels: timeLabels,
      deviceTypeIcon: basic.deviceTypeIcon,
    );
  }

  Future<void> remotePowerOn() async {
    if (state.isPoweringOn) return;
    emit(state.copyWith(isPoweringOn: true));
    try {
      await _service.powerOn(deviceId: _deviceId);
      emit(state.copyWith(
        isPoweringOn: false,
        operationMessage: '远程送电成功',
      ));
    } catch (e) {
      emit(state.copyWith(
        isPoweringOn: false,
        operationMessage: '远程送电失败: $e',
      ));
    }
  }

  Future<void> remotePowerOff() async {
    if (state.isPoweringOff) return;
    emit(state.copyWith(isPoweringOff: true));
    try {
      await _service.powerOff(deviceId: _deviceId);
      emit(state.copyWith(
        isPoweringOff: false,
        operationMessage: '远程断电成功',
      ));
    } catch (e) {
      emit(state.copyWith(
        isPoweringOff: false,
        operationMessage: '远程断电失败: $e',
      ));
    }
  }

  void clearOperationMessage() {
    emit(state.copyWith(operationMessage: null));
  }

  void selectChartTab(int index) {
    emit(state.copyWith(selectedChartTabIndex: index));
  }
}