import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/room_bo.dart';
import 'package:smart_hotel_app/repositories/room_repository.dart';
import 'package:smart_hotel_app/services/room_service.dart';
import 'package:smart_hotel_app/utils/deal_utils.dart';
import 'package:smart_hotel_app/views/service/room/cubit/service_room_state.dart';

class ServiceRoomCubit extends Cubit<ServiceRoomState> {
  final RoomService _service;
  final int _roomId;

  ServiceRoomCubit({
    RoomService? service,
    required int roomId,
    String roomNumber = '',
  })  : _service = service ??
            RoomService(repository: RoomRepository()),
        _roomId = roomId,
        super(ServiceRoomState(roomId: roomId, roomNumber: roomNumber)) {
    loadDetail();
  }

  /// 客房详情接口
  Future<void> loadDetail({bool isLoading = true}) async {
    emit(state.copyWith(isLoading: isLoading, error: null));
    try {
      final detail = await _service.getRoomDetail(roomId: _roomId);
      emit(_mapDetailToState(detail));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 数据处理
  ServiceRoomState _mapDetailToState(RoomDetailBO detail) {
    final basic = detail.roomBasicInfo;
    final statusTags = _buildStatusTags(
      occupancyStatus: basic.occupancyStatus,
      powerSupplyStatus: basic.powerSupplyStatus,
      wifiOnlineStatus: basic.wifiOnlineStatus,
    );

    // 房间设备状态
    final roomDevices = detail.deviceStatusList
        .where((d) => !d.deviceName.contains('分控'))
        .map((d) {
      return RoomDevice(
        name: d.deviceName,
        icon: DealUtils.deviceIcon(d.deviceTypeIcon),
        isOn: d.powerStatus == '1' || d.powerStatus == 'on',
        statusText: _buildDeviceStatusText(d),
      );
    }).toList();

    // 从 deviceStatusList 建立 deviceId → deviceTypeIcon 的映射
    final iconMap = <int, String>{};
    for (final d in detail.deviceStatusList) {
      iconMap[d.deviceId] = d.deviceTypeIcon;
    }

    // 分设备控制
    final subDeviceControls = detail.deviceControl.subDeviceControls
        .where((c) => !c.deviceName.contains('分控'))
        .map((c) {
      return ControlDevice(
        deviceId: c.deviceId,
        name: c.deviceName,
        icon: DealUtils.deviceIcon(iconMap[c.deviceId] ?? ''),
        isOn: c.powerOn,
        detailText: c.currentParamDisplay.isNotEmpty ? c.currentParamDisplay : null,
        deviceTypeName: c.deviceTypeName,
      );
    }).toList();

    return state.copyWith(
      isLoading: false,
      roomNumber: basic.roomNumber,
      roomStatus: _mapOccupancyStatus(basic.occupancyStatus),
      statusTags: statusTags,
      roomDevices: roomDevices,
      mainPowerOn: detail.deviceControl.roomPowerControl.powerOn,
      controlDevices: subDeviceControls,
    );
  }

  List<RoomStatusTag> _buildStatusTags({
    required String occupancyStatus,
    required bool powerSupplyStatus,
    required String wifiOnlineStatus,
  }) {
    final tags = <RoomStatusTag>[];
    if (occupancyStatus == '1') {
      tags.add(RoomStatusTag.hasPerson);
    }
    if (powerSupplyStatus) {
      tags.add(RoomStatusTag.powerOn);
    }
    if (wifiOnlineStatus == '1' || wifiOnlineStatus == 'online') {
      tags.add(RoomStatusTag.wifiNormal);
    }
    return tags;
  }

  String _buildDeviceStatusText(DeviceStatusBO d) {
    if (d.powerStatusText.isNotEmpty) {
      return d.powerStatusText;
    }
    if (d.runStatusText.isNotEmpty) {
      return d.runStatusText;
    }
    if (d.deviceParams != null) {
      final p = d.deviceParams!;
      final parts = <String>[];
      if (p.temperature.isNotEmpty) parts.add('${p.temperature}°C');
      if (p.mode.isNotEmpty) parts.add(p.mode);
      return parts.join('·');
    }
    return '';
  }

  String _mapOccupancyStatus(String status) {
    switch (status) {
      case '1':
        return '入住中';
      case '0':
      default:
        return '空闲';
    }
  }

  /// 房间总电源开关
  Future<void> toggleMainPower(bool value) async {
    if (state.isPoweringOn || state.isPoweringOff) return;
    emit(state.copyWith(
      isPoweringOn: value,
      isPoweringOff: !value,
    ));
    try {
      if (value) {
        await _service.powerOn(roomId: _roomId);
      } else {
        await _service.powerOff(roomId: _roomId);
      }
      emit(state.copyWith(
        isPoweringOn: false,
        isPoweringOff: false,
        mainPowerOn: value,
      ));
      await loadDetail(isLoading: false);
    } catch (e) {
      emit(state.copyWith(
        isPoweringOn: false,
        isPoweringOff: false,
      ));
      rethrow;
    }
  }

  /// 分设备电源开关
  Future<void> toggleControlDevice(int index, bool value) async {
    final devices = state.controlDevices;
    if (index < 0 || index >= devices.length) return;
    final device = devices[index];

    // 乐观更新 UI
    final oldDevices = devices;
    final updatedDevices = List<ControlDevice>.from(devices);
    updatedDevices[index] = ControlDevice(
      deviceId: device.deviceId,
      name: device.name,
      icon: device.icon,
      isOn: value,
      detailText: device.detailText,
      deviceTypeName: device.deviceTypeName,
    );
    emit(state.copyWith(controlDevices: updatedDevices));

    try {
      if (value) {
        await _service.powerSingleOn(deviceId: device.deviceId);
      } else {
        await _service.powerSingleOff(deviceId: device.deviceId);
      }
      await loadDetail(isLoading: false);
    } catch (e) {
      // 失败回滚
      emit(state.copyWith(controlDevices: oldDevices));
      rethrow;
    }
  }

}
