import 'dart:io';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/utils/alert_util.dart';
import 'package:account_center/common/utils/bottom_dialog.dart';
import 'package:account_center/page/enterprise/join_or_new_enterprise_page/enterprise_proxy_person_page/clx_file_manage.dart';
import 'package:account_center/widget/permission_util.dart';
import 'package:flutter/material.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';

/// 从url中获取文件名
String getFileNameFromUrl(String url) {
  int lastIndex = url.lastIndexOf("/");
  if (lastIndex == -1) {
    return url;
  }
  return url.substring(lastIndex + 1);
}

/// 临时下载文件路径
Future<String> getTempDownloadPath(String url) async {
  var dirPath = await getTempDownloadDirPath();
  var tempName = getTempDownloadName(url);
  return "$dirPath/$tempName";
}

/// 临时下载文件夹路径
Future<String> getTempDownloadDirPath() async {
  return (await getApplicationDocumentsDirectory()).path;
}

/// 临时下载文件名
String getTempDownloadName(String url) {
  return "${url.hashCode.toString()}_${getFileNameFromUrl(url)}";
}

void downloadFile(
  String url, {
  ProgressCallback? onReceiveProgress,
}) {
  getTempDownloadPath(url).then(
    (path) {
      if (File(path).existsSync()) {
        _saveFile(path);
        return;
      } else {
        AlertUtil.showLoading();
        download(ossDomain + url, path, onReceiveProgress: onReceiveProgress)
            .then(
          (value) {
            AlertUtil.dismissLoading();
            if (!value) {
              Get.snackbar('提示', '下载失败');
              return;
            }
            _saveFile(path);
          },
        );
      }
    },
  );
}

/// 预览网络图片
void previewNetFile(String url) async {
  var tempPath = await getTempDownloadPath(url);
  if (File(tempPath).existsSync()) {
    previewLocalFile(tempPath);
    return;
  } else {
    /// 全路径
    bool isPath = url.startsWith('http');
    AlertUtil.showLoading();
    var success = await download(isPath ? url : ossDomain + url, tempPath,
        onReceiveProgress: null);
    AlertUtil.dismissLoading();
    if (success) {
      previewLocalFile(tempPath);
    } else {
      Get.snackbar('提示', '下载失败');
    }
  }
}

/// 本地文件预览
void previewLocalFile(String filePath) async {
  if (Platform.isAndroid) {
    BottomDialog.showBottomDialog([
      ButtonItem(
        title: '查看文件',
        onClick: () {
          OpenFilex.open(filePath);
        },
      ),
      ButtonItem(
        title: '保存本地',
        onClick: () {
          _saveFile(filePath);
        },
      )
    ]);
  } else if (Platform.isIOS) {
    _saveFile(filePath);
  }
}

void exportFile(
  String url,
  String filePath,
  Map<String, dynamic>? queryParameters,
) {
  AlertUtil.showLoading();
  export(
    url,
    filePath,
    queryParameters: queryParameters,
  ).then(
    (success) {
      AlertUtil.dismissLoading();
      if (!success) {
        Get.snackbar('提示', '下载失败');
        return;
      }
      _saveFile(filePath);
    },
  );
}

void _saveFile(String path) {
  PermissionUtil.checkStorePermission().then((bool) {
    if (bool != true) {
      return;
    }
    CLXFileManage.copyFileToPublic(path).then(
      (value) {
        Get.snackbar(
          '提示',
          '下载成功，请前往系统文件夹查看',
          backgroundColor: Colors.black.withAlpha(150),
          colorText: Colors.white,
        );
      },
    );
  });
}
