import 'dart:convert';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:ef/ef.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.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/repair_status.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/common/util/myDialog/my_dialog_controller.dart';
import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/controller/mh_controller/device_list_controller.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/model/api_response.dart';
import 'package:vbvs_app/model/user_data.dart';

part 'apply_repair_controller.g.dart';

@JsonSerializable()
class ApplyRepairModel {
  int? id; //报修id
  String? apply_name; //申请人名称
  String? tel; //手机号

  String? desc; //问题描述
  DateTime? create_time; //创建时间

  int? device_type; //类型 床，床垫 不能为空
  String? device_category; //型号 不能为空
  String? device_id; //序列号 设备id 不能为空

  String? device_name; //名称  可为空

  List<String>? issue_img = []; //图片
  int? imagesLImit = 3; //图片限制上传数量
  String? img_bucket = 'mianhuatang_repair';

  String? status; //维修状态

  String? select_device;
  // String? select_type;
  // List<String>? device_list = ['床垫/BY-H/智能床垫', '床垫/BY-A/智能床垫', '床垫/BY-C/智能床垫'];
  List<dynamic>? device_list = [];
  int? score;
  DateTime? score_time; //创建时间

  int? messageType = 1; //消息类型
  int? repairId; //消息类型

  ApplyRepairModel();
  static ApplyRepairModel fromJson(Map<String, dynamic> json) =>
      _$ApplyRepairModelFromJson(json);
  Map<String, dynamic> toJson() => _$ApplyRepairModelToJson(this);
}

class ApplyRepairController extends GetControllerEx<ApplyRepairModel> {
  // RepairRepository repairRepository = RepairRepository();
  ApplyRepairController() {
    attr = GetModel(ApplyRepairModel()).obs;
  }

  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": 2,
          "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);
          model.issue_img!.add(res.data['path']);
          updateAll();
          MyUtils.formatResponse(res, "我的.上传成功".tr, "我的.头像上传失败".tr);
          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<String> submitRepair(BuildContext context) async {
  //   //tmp
  //   // return '';
  //   String message = '';
  //   final MyDialogController myDialogController =
  //       Get.find<MyDialogController>();
  //   if (model.device_type == null || model.device_type!.isEmpty) {
  //     message = '请选择设备类型！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (model.device_category == null || model.device_category!.isEmpty) {
  //     message = '请输入设备型号！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (model.device_id == null || model.device_id!.isEmpty) {
  //     message = '请输入设备序列号id！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (model.apply_name == null || model.apply_name!.isEmpty) {
  //     message = '请输入姓名！';
  //     showToast(message);
  //     return message;
  //   }
  //   RegExp nameRegExp = RegExp(r'^[\u4e00-\u9fa5]{2,4}$');

  //   if (!nameRegExp.hasMatch(model.apply_name!)) {
  //     message = '姓名必须为2到4个汉字！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (model.tel == null || model.tel!.isEmpty) {
  //     message = '请输入手机号！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (!MyUtils.isValidPhoneNumber(model.tel!)) {
  //     message = '无效的手机号！';
  //     showToast(message);
  //     return message;
  //   }

  //   if (model.desc == null || model.desc!.isEmpty) {
  //     message = '请输入问题描述！';
  //     showToast(message);
  //     return message;
  //   }
  //   if (model.issue_img == null || model.issue_img!.isEmpty) {
  //     message = '请至少上传一张问题图片！';
  //     showToast(message);
  //     return message;
  //   }
  //   model.status = RepairStatus.pending;
  //   // await repairRepository.saveRepair(model);
  //   String type = "repair_submit_${model.device_id}";
  //   String serviceAddress = ServiceConstant.service_address;
  //   String serviceName = ServiceConstant.server_service;
  //   String serviceApi = ServiceConstant.submit_repair;
  //   String queryUrl = "$serviceAddress$serviceName$serviceApi?type=$type";

  //   // 组织请求数据
  //   final UserInfoController userInfoController =
  //       Get.find<UserInfoController>();
  //   UserModel user = userInfoController.model.user!;

  //   Map<String, dynamic> data = {
  //     'apply_name': model.apply_name,
  //     'desc': model.desc,
  //     'device_type': model.device_type,
  //     'issue_img': model.issue_img,
  //     'tel': model.tel,
  //     'uid': user.uid,
  //     'device_category': model.device_category,
  //     'device_id': model.device_id,
  //     'device_name': model.device_name,
  //     'status': model.status,
  //   };

  //   // 发起插入请求（这里相当于之前的 saveRepair）
  //   requestWithLog(
  //     logTitle: "提交报修",
  //     method: MyHttpMethod.post,
  //     queryUrl: queryUrl,
  //     data: data,
  //     onSuccess: (res) {
  //       if (res.data is List && res.data.isNotEmpty) {
  //         final inserted = res.data[0];
  //         model.id = inserted['id'];
  //         model.create_time = DateTime.tryParse(inserted['create_time']);
  //         // TextSelectionOverlay
  //         // // saveRepairHistor
  //         // saveRepairHistory(
  //         //   RepairProcessModel()
  //         //     ..status = model.status
  //         //     ..record_id = inserted['id'],
  //         // );
  //         showToast("提交成功！");
  //       } else {
  //         showToast("提交失败：未返回数据！");
  //       }
  //     },
  //     onFailure: (res) {
  //       showToast("提交失败！");
  //     },
  //   );

  //   return message;
  // }

  Future<void> getDeviceList() async {
    // UserModel loginUser = userInfoController.model.user!;
    DeviceListController deviceListController = Get.find();
    await deviceListController.getDeviceList();
    var aa = deviceListController.model.deviceList;
    ApplyRepairController applyRepairController = Get.find();
    applyRepairController.model.device_list = aa;
  }

}
