/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 2022-07-14 18:16:06
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-08-01 16:17:33
 * @FilePath: \marking_app\lib\provider\user_provider.dart
 * @Description: APP上传文件状态
 */

import 'dart:io';

import 'package:dio/dio.dart';
// import 'package:minio/io.dart';
// import 'package:minio/minio.dart';
import 'package:marking_app/common/model/job/upload_file_interface_config.dart';
import 'package:marking_app/utils/index.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/common/upload_img_secret_key.dart';
import 'package:marking_app/utils/request/rest_client.dart';

// API

final uploadFileProvider = StateNotifierProvider<UploadFileProviderHandle, UploadImgSecretKey>(
    (ref) => UploadFileProviderHandle(UploadImgSecretKey()));

class UploadFileProviderHandle extends StateNotifier<UploadImgSecretKey> with CommonMixin {
  // Minio? _minio;
  UploadFileProviderHandle(UploadImgSecretKey progress) : super(progress);

  Future<void> initConfig() async {
    try {
      RestClient client = await getClient();
      BaseStructureResult<UploadImgSecretKey> res = await client.getImageUploadKey();
      if (res.success && res.data != null) {
        setVal(res.data!);
      }
    } catch (e) {}
  }

  void setVal(UploadImgSecretKey val) {
    // state = val;

    // if (![val.account, val.password, val.ip, val.endPoint, val.bucketName].contains(null)) {
    //   _minio ??= Minio(
    //     accessKey: val.account!,
    //     secretKey: val.password!,
    //     endPoint: val.ip!,
    //     port: val.endPoint,
    //   );
    // }
  }

  void clean() {
    state = UploadImgSecretKey();
  }

  // 安装规则上传图片
  /// addFileSuffix 文件后缀
  // Future<String> _getFileName(String imgUrl, String addFileSuffix) async {
  //   if (_minio == null) {
  //     await initConfig();
  //   }
  //   imgUrl.replaceAll(RegExp('https?:\\/\\/.+?\\/.+?\\/'), '');

  //   // List<String> imgUrlArr = imgUrl.split('${state.bucketName!}/');
  //   // String oneVal = imgUrlArr[1];
  //   String oneVal = imgUrl.replaceAll(RegExp('https?:\\/\\/.+?\\/.+?\\/'), '');
  //   String prefixUrl = oneVal.substring(0, oneVal.lastIndexOf('/') + 1);
  //   String suffixFileName = oneVal.substring(oneVal.lastIndexOf('/') + 1);
  //   List<String> suffixFileNameArr = suffixFileName.split('.');
  //   String prefix = suffixFileNameArr[0];
  //   if (prefix.contains('-cmt')) {
  //     prefix = prefix.split('-cmt')[0];
  //   }
  //   String suffix = suffixFileNameArr[1];
  //   return '$prefixUrl${'$prefix-cmt-$addFileSuffix.'}$suffix';
  // }

  Future<bool> _upload(String path, String myObjectPath) async {
    try {
      // await _minio!.fPutObject(state.bucketName!, myObjectPath, path);
      return true;
    } catch (e) {
      toPrint(val: '错误输出：....，$e');
      return false;
    }
  }

  Future<FileResult?> uploadFile(String path, String fileName, String addFileSuffix) async {
    // try {
    //   String newFileName = await _getFileName(fileName, addFileSuffix);
    //   FileResult fileModel = FileResult(myObject: newFileName);
    //   fileModel.path = path;
    //   bool uploadFlag = await _upload(path, fileModel.myObject);
    //   if (uploadFlag) {
    //     bool uploadFlag = await _upload(path, fileModel.myObject);
    //     // 上传图片成功
    //     fileModel.url = 'https://${state.ip}:${state.endPoint!}/${state.bucketName!}/${fileModel.myObject}';
    //     fileModel.success = true;
    //   }
    //   return fileModel;
    // } catch (e) {
    //   toPrint(val: '上传报错....，$e');
    //   return null;
    // }
  }

  Future<FileResult?> getUploadFileConfig(UploadFileInterfaceConfig uploadConfig, File fileData) async {
    Dio dio = Dio();
    try {
      late Response response;
      final bytes = await fileData.readAsBytes();

      if (uploadConfig.uploadMethod == "PUT") {
        response = await dio.put(uploadConfig.uploadUri!,
            data: Stream.fromIterable(bytes.map((e) => [e])),
            options: Options(headers: {
              Headers.contentLengthHeader: bytes.length, // Set the content-length.
              HttpHeaders.contentTypeHeader: 'image/png',
            }));
      } else if (uploadConfig.uploadMethod == "POST") {
        response = await dio.post(uploadConfig.uploadUri!,
            data: Stream.fromIterable(bytes.map((e) => [e])),
            options: Options(headers: {
              Headers.contentLengthHeader: bytes.length, // Set the content-length.
              HttpHeaders.contentTypeHeader: 'image/png',
            }));
      }
      print('文件上传成功：${response.data}');
      if ([200, 201, 204].contains(response.statusCode)) {
        return FileResult(myObject: '', success: true, url: uploadConfig.downloadUri);
      }
    } catch (e) {
      print('文件上传失败：$e');
    } finally {
      dio.close();
    }
  }

  /// 获取上传文件的URL
  Future<String?> getFileUrl(String myObject, {bool failedDelete = false}) async {
    // try {
    //   return await _minio!.presignedGetObject(state.bucketName!, myObject);
    // } catch (e) {
    //   // 获取url失败 删除图片
    //   if (failedDelete) removeFile(myObject);
    // }
  }

  // Future<bool> removeFile(String myObject) async {
  //   try {
  //     await _minio!.removeObject(state.bucketName!, myObject);
  //     return true;
  //   } catch (e) {
  //     return false;
  //   }
  // }
}
