import 'dart:convert';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:dio/dio.dart';
import 'package:dio/src/form_data.dart' as formdata;
import 'package:ef/ef.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:vbvs_app/common/color/ServiceConstant.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/model/api_response.dart';

part 'mhdevice_share_controller.g.dart';

@JsonSerializable()
class MHDeviceShareModel {
  String? account;
  int? type = 1;

  String? msg;
  int? show = 0;
  int? code = 0;
  int limit = AppConstants.limit;
  int offset = 0;
  bool isLoading = false;
  bool hasMore = true;

  // List<dynamic>? shareUser = [
  //   {"type": 1},
  //   {"type": 2}
  // ];
  List<dynamic>? shareUser = [];
  Map mainShare = {};

  MHDeviceShareModel();
  static MHDeviceShareModel fromJson(Map<String, dynamic> json) =>
      _$MHDeviceShareModelFromJson(json);
  Map<String, dynamic> toJson() => _$MHDeviceShareModelToJson(this);
}

class MHDeviceShareController extends GetControllerEx<MHDeviceShareModel> {
  MHDeviceShareController() {
    attr = GetModel(MHDeviceShareModel()).obs;
  }

  // RxString account = "".obs;
  // RxString msg = "".obs;
  // RxInt code = 0.obs;
  @override
  Future<void> onInit() async {
    super.onInit();
    await shareDeviceList(Get.arguments["mac"]);
  }

  Future<ApiResponse> shareDevice(String mac) async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
    EasyDartModule.logger.info("分享设备");
    DailyLogUtils.writeLog("分享设备");
    try {
      model.account = model.account!.trim();
      if (model.account == null || model.account!.isEmpty) {
        apiResponse.msg = "请输入手机号".tr;
        return apiResponse;
      }
      if (!MyUtils.isValidPhoneNumber(model.account!) &&
          !MyUtils.isValidEmail(model.account!)) {
        apiResponse.msg = '请输入正确的手机号/邮箱号'.tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_share;
      String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      var data = {"type": model.type, "userName": model.account, "mac": mac};
      var response =
          await EasyDartModule.dio.post(queryUrl, data: jsonEncode(data));
      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        if (res.code != HttpStatusCodes.ok) {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = apiResponse.msg;
          }
        } else {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = "操作成功".tr;
          }
        }
        if (res.code != HttpStatusCodes.ok) {
          model.msg = res.msg!;
        }
        model.code = res.code!;
        updateAll();
        return res;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      EasyDartModule.logger.info("分享设备失败：${e.toString()}");
      DailyLogUtils.writeLog("分享设备失败：${e.toString()}");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  shareDeviceList(String mac) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.device_share;
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}?mac=$mac";
    await requestWithLog(
      logTitle: '分享用户列表',
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) => {
        model.shareUser = res.data,
        updateAll(),
      },
    );
  }

  Future<ApiResponse> confirmShare(String shareCode) async {
    EasyDartModule.logger.info("确认消息分享");
    DailyLogUtils.writeLog("确认消息分享");
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      if (shareCode == null || shareCode.isEmpty) {
        apiResponse.msg = "请求失败".tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_share;
      String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      final data = {
        "code": shareCode,
      };
      var response =
          await EasyDartModule.dio.put(queryUrl, data: jsonEncode(data));
      if (response != null) {
        if (response.data['code'] != HttpStatusCodes.ok) {
          apiResponse.msg = response.data['msg'];
          apiResponse.code = response.data['code'];
          return apiResponse;
        }
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        MyUtils.formatResponse(res, "操作成功".tr, "操作失败".tr);
        return res;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      EasyDartModule.logger.info("确认消息分享失败->$e");
      DailyLogUtils.writeLog("确认消息分享失败->$e");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }
}
