/*
 * @Author: XianKaiQun
 * @Date: 2020-07-06 22:55:37
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-08-17 10:44:35
 * @Description: 
 */
import 'dart:async';
import 'dart:io';
import 'dart:convert' as convert;
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:app_package/src/models/res.dart';
import 'package:app_package/src/utils/http.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart' as _Dio; // TOD:因dio依赖库与flutter自带http库 有类命名冲突

class GlobalApi {
  static const String HEIC_SUFFIX = '.HEIC';

  static Future<File?> compressImageFile(File file) async {
    var length = await file.length();

    /// 图片大于500kb则进行压缩, 压缩至500kb
    var quality = ((500 / (length / 1024)) * 100).floor();
    final temppath = await _getCachePathString(file.path);

    /// 图片大于500kb则进行压缩, 压缩至500kb
    XFile? result = await FlutterImageCompress.compressAndGetFile(
      file.path,
      temppath,
      quality: quality < 100 ? quality : 100,
    );
    return result == null ? null : File(result.path);
  }

  static Future<Uint8List> compressImageBytes(Uint8List file) async {
    var length = file.lengthInBytes;

    /// 图片大于500kb则进行压缩, 压缩至500kb

    var quality = ((500 / (length / 1024)) * 100).floor();

    var result = await FlutterImageCompress.compressWithList(
      file,
      quality: quality < 100 ? quality : 100,
    );
    return result;
  }

  /// 获取图片的缓存路径并创建
  static Future<String> _getCachePathString(String name) async {
    // 获取图片的名称
    String filePathFileName = md5.convert(convert.utf8.encode(name)).toString();
    String extensionName = name.split('/').last.split('.').last;

    // 生成、获取结果存储路径
    final tempDic = await getTemporaryDirectory();
    Directory directory = Directory(tempDic.path + '/CacheImage/');
    bool isFoldExist = await directory.exists();
    if (!isFoldExist) {
      await directory.create();
    }
    return directory.path + filePathFileName + '.$extensionName';
  }

  ///图片上传
  ///http://yapi.wisdomcity.com.cn/project/52/interface/api/1566
  static Future<ResModel<String>?> postUploadImage(File? file) async {
    if (file == null) {
      debugPrint('文件不能为空');
      return null;
    }
    File? result = await compressImageFile(file);

    final formData = _Dio.FormData.fromMap({
      "file": await _Dio.MultipartFile.fromFile(
        result!.path,
        filename: result.path.split('/').last,
      ),
    });
    final res = await HttpUtil.instance.post(
      '/file/images/upload',
      data: formData,
    );

    return ResModel<String>(
      json: res.data,
      to: (v) => v,
      from: (v) => v,
    );
  }

  /// 图片批量上传
  // static Future<ResModel<String>> postMultiUploadImage(List<File> file) async {
  //   if (file == null) {
  //     debugPrint('文件不能为空');
  //     return null;
  //   }

  // final formData = _Dio.FormData.fromMap({
  //   "file": await _Dio.MultipartFile.fromFile(
  //     file.path,
  //     filename: file.path.split('/').last,
  //   ),
  // });
  // final res = await HttpUtil.instance.post(
  //   '/images/batch/upload',
  //   data: formData,
  // );

  // return ResModel<String>(
  //   json: res.data,
  //   to: (v) => v,
  //   from: (v) => v,
  // );
  // }

  ///上传图片返回文件对象
  ///http://yapi.wisdomcity.com.cn/project/52/interface/api/1566
  static Future postUploadImageObject(File? file) async {
    if (file == null) {
      debugPrint('文件不能为空');
      return null;
    }
    File? result = await compressImageFile(file);
    final formData = _Dio.FormData.fromMap({
      "file": await _Dio.MultipartFile.fromFile(
        result!.path,
        filename: result.path.split('/').last,
      ),
    });
    final res = await HttpUtil.instance.post(
      '/file/images/upload',
      data: formData,
    );
    print('000000000000000000005555555555555555555555555');
    return {
      'id': res.data['data'],
      'name': file.path.split('/').last,
      'type': 'image/${file.path.split('.').last}',
      'path': '/9ad134a361f8d778file/images/${res.data['data']}'
    };
  }

  static Future<UploadImgModel?> postUploadImageObject2(File? file) async {
    if (file == null) {
      debugPrint('文件不能为空');
      return null;
    }
    File? result = await compressImageFile(file);
    final formData = _Dio.FormData.fromMap({
      "file": await _Dio.MultipartFile.fromFile(
        result!.path,
        filename: result.path.split('/').last,
      ),
    });
    final res = await HttpUtil.instance.post(
      '/file/images/upload',
      data: formData,
    );
    return UploadImgModel(
      id: res.data['data'],
      name: file.path.split('/').last,
      type: 'image/${file.path.split('.').last}',
      path: '/9ad134a361f8d778file/images/${res.data['data']}',
    );
  }

  ///图片上传
  ///http://yapi.wisdomcity.com.cn/project/52/interface/api/1566
  static Future<ResModel<String>?> postUploadImageFormByte(
      Uint8List? bytes) async {
    if (bytes == null) {
      debugPrint('文件不能为空');
      return null;
    }
    Uint8List result = await compressImageBytes(bytes);
    final formData = _Dio.FormData.fromMap({
      "file": _Dio.MultipartFile.fromBytes(
        result,
        filename: 'uploadFileName',
      ),
    });
    final res = await HttpUtil.instance.post(
      '/file/images/upload',
      data: formData,
    );

    return ResModel<String>(
      json: res.data,
      to: (v) => v,
      from: (v) => v,
    );
  }

  static Future<ResModel<String>?> uploadImageUsingMultipartFile(
      ByteData? byteData, String filename) async {
    if (byteData == null) {
      debugPrint('文件数据不能为空');
      return null;
    }
    List<int> imageData = byteData.buffer.asUint8List();

    var uploadFileName = filename;

    //处理苹果的HEIC格式图片文件名称
    if (filename.toUpperCase().endsWith(HEIC_SUFFIX)) {
      uploadFileName = uploadFileName.replaceRange(
          uploadFileName.length - HEIC_SUFFIX.length,
          uploadFileName.length,
          '.jpg');
      debugPrint('uploadFileName :$uploadFileName');
    }

    _Dio.MultipartFile multipartFile = _Dio.MultipartFile.fromBytes(
      imageData,
      filename: uploadFileName,
    );
    _Dio.FormData formData = _Dio.FormData.fromMap({
      "file": multipartFile,
    });
    var res = await HttpUtil.instance.post(
      '/file/images/upload',
      data: formData,
    );

    return ResModel<String>(
      json: res.data,
      to: (v) => v,
      from: (v) => v,
    );
  }

  /// 获取逆编码地理位置 (2024.07.05 去除高德)
  // static Future<Map<String, dynamic>?> wisGetLocationName(parameters) async {
  //   var res = await HttpUtil.instance.get(
  //       'https://restapi.amap.com/v3/geocode/regeo?key=09b98b5ab6138d96a3ff36bc1b0b9c6c&$parameters');

  //   _Dio.Response<dynamic> resp = res;

  //   Map regeocodes = resp.data['regeocode'];

  //   return regeocodes as FutureOr<Map<String, dynamic>?>;
  // }

  static Future<ResModel<String>> getCommunityMeterChargeMode(data) async {
    var res = await HttpUtil.instance.get(
      '/app/admin/intelligent/config/getChargingModeByCommunityId',
      queryParameters: data,
    );
    return ResModel<String>(
      json: res.data,
      to: (v) => v,
      from: (v) => v,
    );
  }
}

class UploadImgModel {
  late String id;
  late String type;
  late String name;
  late String path;

  UploadImgModel({
    required this.id,
    required this.type,
    required this.name,
    required this.path,
  });

  UploadImgModel.fromJson(json) {
    Map<String, dynamic> map = Map.from(json ?? {});

    id = map['id'];
    type = map['type'];
    name = map['name'];
    path = map['path'];
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = Map<String, dynamic>();

    json['id'] = this.id;
    json['type'] = this.type;
    json['name'] = this.name;
    json['path'] = this.path;

    return json;
  }
}
