 
import 'package:get/get.dart';

import '../index.dart';

///
/// o2云 服务
///
class CollectService  extends GetxService {
  
  static CollectService get to => Get.find();
 

  String baseUrl() {
    return O2.o2CloudAPIUrl;
  }
 
  ///
  ///发送短信验证码
  ///
  Future<CollectCodeData?> getCode(CollectCodeData data) async {
    try {
      ApiResponse response = await O2HttpClient.instance
        .post('${baseUrl()}jaxrs/code', data.toJson(), needToken: false);
      if (response.isSuccess()) {
        return CollectCodeData.fromJson(response.data);
      }
    } catch (err, stackTrace) {
      OLogger.e('获取短信验证码失败', err, stackTrace);
    }
    return null;
  }

  ///
  ///获取绑定服务器列表
  Future<List<O2CloudServer>?> getUnitList(String phone, String code) async {
    try {
       ApiResponse response = await O2HttpClient.instance.get('${baseUrl()}jaxrs/unit/list/account/$phone/code/$code', needToken: false);
      if (response.isSuccess()) {
        var list = response.data == null ? [] : response.data as List;
        return list.map((e) => O2CloudServer.fromJson(e) ).toList();
      }
    } catch  (err, stackTrace) {
      OLogger.e('获取绑定的单位列表失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 绑定设备
  /// 
  Future<IdData?> bindDevice(O2CloudBindData data) async {
    try {
      ApiResponse response = await O2HttpClient.instance
        .post('${baseUrl()}jaxrs/device/account/bind', data.toJson(), needToken: false);
      if (response.isSuccess()) {
        return IdData.fromJson(response.data);
      }
    } catch (err, stackTrace) {
      OLogger.e('绑定设备失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 解绑设备
  ///
  Future<IdData?> unBindDevice(String token) async {
    try {
      ApiResponse response = await O2HttpClient.instance.delete('${baseUrl()}jaxrs/device/name/$token/unbind', needToken: false);
      if (response.isSuccess()) {
        return IdData.fromJson(response.data);
      }
    } catch (err, stackTrace) {
      OLogger.e('解绑设备失败', err, stackTrace);
    }
    return null;
  }
}
