import 'dart:io';

import 'package:account_center/api/api_config.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/utils/device_util.dart';
import 'package:account_center/common/utils/file_util.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

import 'enterprise_proxy_person_see_state.dart';

class EnterpriseProxyPersonSeeLogic extends GetxController {
  final EnterpriseProxyPersonSeeState state = EnterpriseProxyPersonSeeState();
  dynamic data;
  String get fileName => data?['confirmationFileName'] ?? '-';
  String get fileUrl => data?['agentConfirmation'] ?? '';
  @override
  void onInit() {
    super.onInit();
    data = Get.arguments;
    if (data != null) {
      state.agentName = data['agentName'];
      state.agentMobile = data['agentMobile'];
      state.agentCardNo = data['agentCardNo'];
      if (kDebugMode) {
        state.agentCardFrontImg = data['agentCardFrontImg'];
        state.agentCardBackImg = data['agentCardBackImg'];
        // state.agentCardFrontImg = '$devOssDomain${data['agentCardFrontImg']}';
        // state.agentCardBackImg = '$devOssDomain${data['agentCardBackImg']}';
      } else {
        state.agentCardFrontImg = data['agentCardFrontImg'];
        state.agentCardBackImg = data['agentCardBackImg'];
        // state.agentCardFrontImg = '$prodOssDomain${data['agentCardFrontImg']}';
        // state.agentCardBackImg = '$prodOssDomain${data['agentCardBackImg']}';
      }
    }
  }

  Future<void> requestStoragePermission() async {
    PermissionStatus status;
    var device = await getDeviceInfo();
    if (Platform.isAndroid &&
        (device.systemVersion.contains('14') ||
            device.systemVersion.contains('13'))) {
      // status = await Permission.manageExternalStorage.request();
      return;
    } else {
      status = await Permission.storage.request();
    }
    if (!status.isGranted) {
      ToastUtil.showToast('请开启文件存储权限！');
      throw Exception('用户未授予存储权限');
    }
  }

  void preView() async {
    if (fileUrl.isEmpty) return;
    await requestStoragePermission();
    var d = await getApplicationDocumentsDirectory();
    var savePath = d.path;
    savePath = '$savePath/com.clx/${path.basename(fileUrl)}';
    // print(savePath);
    File file = File(savePath);
    if (await file.exists()) {
      FileUtil.openFile(savePath);
      return;
    }
    bool isSuccess = await download(ossDomain + fileUrl, savePath);
    if (isSuccess) {
      FileUtil.openFile(savePath);
    } else {
      ToastUtil.showToast('文件下载失败');
    }
  }
}
