import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:dio/dio.dart' as dio;
import 'package:ef/ef.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:get_storage/get_storage.dart';
import 'package:img_picker/img_picker.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:vbvs_app/common/color/ServiceConstant.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/controller/device/body_device_controller.dart';
import 'package:vbvs_app/controller/home/home_controller.dart';
import 'package:vbvs_app/controller/login/login_controller.dart';
import 'package:vbvs_app/controller/message/message_controller.dart';
import 'package:vbvs_app/controller/time/countdown_controller.dart';
import 'package:vbvs_app/model/api_response.dart';
import 'package:vbvs_app/model/user_data.dart';

part 'user_info_controller.g.dart';

@JsonSerializable()
class UserInfoModel {
  int? message = 0; //消息数量

  UserModel? user; //用户信息
  String? token; //token值
  String? runSystem; //运行系统
  String? phoneVersion; //手机版本
  String? deviceId; //手机唯一
  String? deviceModel; //设备可见型号（如 "iPhone"，"iPad"）
  String? appVersion; //app版本信息

  @JsonKey(ignore: true)
  // Session? superbase_session;
  @JsonKey(ignore: true)
  // User? superbase_user;

  String? img_bucket = 'user';
  int? login = 0; //0未登录 1 登录

  int? deviceBindNum = 0; //绑定设备数量

  int? loginPhone = 0; //0 本机号码 1其他手机号

  // String? nickname; //修改昵称
  // String? avatar; //修改头像地址

  UserInfoModel();
  static UserInfoModel fromJson(Map<String, dynamic> json) =>
      _$UserInfoModelFromJson(json);
  Map<String, dynamic> toJson() => _$UserInfoModelToJson(this);
}

class UserInfoController extends GetControllerEx<UserInfoModel> {
  // 初始化实例
  UserInfoController() {
    attr = GetModel(UserInfoModel()).obs;
  }

  RxDouble textHalfWidth = 0.0.obs;
  List device_bind_status = [];
  int device_bind_flag = 0;//0。未初始化  1.已初始化

  Future<ApiResponse> uploadImg() async {
    EasyDartModule.logger.info("请求上传图片");
    DailyLogUtils.writeLog("请求上传图片");
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "我的.头像上传失败".tr);
      if (image != null) {
        int fileSize = await image.length(); // 获取图片大小，单位为字节
        if (fileSize > 1048576 * 5) {
          apiResponse.msg = "我的.头像限制".tr;
          return apiResponse;
        }
        String serviceAddress = ServiceConstant.service_address;
        String serviceName = ServiceConstant.server_service;
        String serviceApi = ServiceConstant.upload_file;
        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 formData = dio.FormData.fromMap({
          "type": 1,
          "file": await dio.MultipartFile.fromFile(
            image.path, // 确保 image 是 File 类型
            filename: image.path.split('/').last,
          ),
        });
        var response = await EasyDartModule.dio.post(queryUrl, data: formData);
        if (response != null) {
          var responseData = response.data is String
              ? jsonDecode(response.data)
              : response.data;
          ApiResponse res =
              ApiResponse.fromJson(responseData, (object) => object);
          MyUtils.formatResponse(apiResponse, "我的.上传成功".tr, "我的.头像上传失败".tr);
          model.user!.tmpHead = res.data['path'];
          updateAll();
          return res;
        } else {
          return ApiResponse(code: -1, msg: "服务器.失败".tr);
        }
      } else {
        apiResponse.msg = "我的.未选择图片".tr;
        return apiResponse;
      }
    } catch (e) {
      EasyDartModule.logger.error("上传图片失败->$e");
      DailyLogUtils.writeError("上传图片失败->$e");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  //更新用户信息
  Future<ApiResponse> updateData() async {
    EasyDartModule.logger.info("更新用户资料");
    DailyLogUtils.writeLog("更新用户资料");
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "保存失败".tr);
      UserModel user = model.user!;
      if (user.tmpNickName == null || user.tmpNickName!.isEmpty) {
        apiResponse.msg = "昵称为空".tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.user_info;
      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 = {
        "nickName": user.tmpNickName,
        if (user.tmpHead != null && user.tmpHead!.isNotEmpty)
          "avatar": user.tmpHead,
      };

      var response =
          await EasyDartModule.dio.put(queryUrl, data: jsonEncode(data));
      if (apiResponse != null) {
        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);
    }
  }

  //查询用户信息
  Future<ApiResponse> getUserInfo() async {
    EasyDartModule.logger.info("查询用户资料");
    DailyLogUtils.writeLog("查询用户资料");
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "我的.查询失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.user_info;
      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 response = await EasyDartModule.dio.get(queryUrl);
      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        MyUtils.formatResponse(apiResponse, "我的.保存成功".tr, "我的.保存失败".tr);
        if (res.code == HttpStatusCodes.ok) {
          UserInfoController userInfoController = Get.find();
          userInfoController.model.user = UserModel.fromJson(res.data);
          final box = GetStorage();
          box.write('user', userInfoController.model.user!.toJson()); // 存储用户信息
          userInfoController.updateAll();
        }
        return apiResponse;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      EasyDartModule.logger.info("更新用户资料失败->$e");
      DailyLogUtils.writeLog("更新用户资料失败->$e");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  ApiResponse logOut() {
    ApiResponse apiResponse = ApiResponse(code: 1, msg: "设置页.退出成功".tr);
    EasyDartModule.logger.info("退出登录");
    DailyLogUtils.writeLog("退出登录");
    model.login = 0;
    EasyDartModule.dio.token = null;
    final box = GetStorage();
    box.remove("user");
    box.remove("token");
    BodyDeviceController bodyDeviceController = Get.find();
    bodyDeviceController.bindDeviceNum.value = 0;
    HomeController homeController = Get.find();
    homeController.sleepNum.value = 0;
    LoginController loginController = Get.find();
    loginController.model.register_agree = null;
    bodyDeviceController.sleepReportData.value = {};
    MessageController messageController = Get.find();
    messageController.model.body_message_read = 0;
    messageController.model.system_message_read = 0;
    CountdownController countdownController = Get.find();
    countdownController.countdown.value = 0;
    return apiResponse;
  }
}
