import 'dart:async';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';

/// fileType : "png、jpg等"
Future<String> uploadFileToOss(String filePath) async {
  if (getToken()?.isNotEmpty != true) {
    ToastUtil.showToast('请先设置token');
    debugPrint('请先调用AccountCenter.setToken');
    return '';
  }
  Completer<String> completer = Completer();
  var fileType = filePath.split('.').last;
  var result = await fetchAsync(
    Method.get,
    url: '/msl-document/common/oss/generateByExt',
    queryParameters: {
      'extension': fileType,
    },
  );
  if (result.isError) {
    completer.complete('');
    return completer.future;
  }
  var data = result.data;
  Client.init(
    stsUrl: ossDomain,
    ossEndpoint: "oss-cn-beijing.aliyuncs.com",
    bucketName: data?['bucketName'],
    authGetter: () => Auth(
      accessKey: data['onceAccessKeyId'],
      accessSecret: data['onceAccessKeySecret'],
      secureToken: data?['onceSecurityToken'],
      expire: '',
    ),
  );
  var timestamp = DateTime.now().millisecondsSinceEpoch.toString();
  var key = (data?['commonDir'] ?? '') + '/' + timestamp + '.' + fileType;

  final Response<dynamic> resp = await Client().putObjectFile(
    filePath,
    fileKey: key,
    option: PutRequestOption(
      onSendProgress: (count, total) {
        debugPrint("send: count = $count, and total = $total");
      },
      onReceiveProgress: (count, total) {
        debugPrint("receive: count = $count, and total = $total");
      },
      aclModel: AclMode.publicWrite,
      callback: null,
    ),
  );
  if (resp.statusCode == 200) {
    completer.complete('/' + key);
  } else {
    debugPrint("uploadErr: ${resp.statusMessage}");
    completer.complete('');
  }

  return completer.future;
}
