import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/utils/index.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import '../Image_slider_viewer/index.dart';
import '../cloud_disk_helpler.dart';
import '../folder_picker/index.dart';
import 'index.dart';

class EnterpriseFileListController extends GetxController {
  EnterpriseFileListController();

  final state = EnterpriseFileListState();
  int folderLevel = 0; // 组织层级
  final _renameController = TextEditingController();
  final _eventBus = EventBus();
  final _eventId = 'clouddisk';
  /// 队列处理进度通知
  final _queueController = StreamController<dynamic>();

  /// 图片查看器使用
   final List<FileInfo> imageList = [];

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
      _queueController.stream.listen((event) { 
      refreshData(showLoading: false);
    });
    _eventBus.on(EventBus.clouddiskFileUploadedMsg, _eventId, (f){
      _queueController.add(f);
    });
    _initBreadcrumb();
    initAnimElement();
    super.onReady();
  }
  
  @override
  void onClose() {
    _eventBus.off(EventBus.clouddiskFileUploadedMsg, _eventId);
     _queueController.close();
    super.onClose();
  }


  /// 初始化或动画结束后执行
  initAnimElement() {
    state.visibleAnimIcon = false;
    final context = Get.context;
    if (context == null) {
      return;
    }
    final size = MediaQuery.of(context).size;
    state.animRight = size.width / 2;
    state.animTop = size.height / 2;
    state.animWidth = 64;
  }
  ///  开始执行上传文件丢进去的动画
  _startUploadAnim() {
    state.visibleAnimIcon = true;
    state.animRight = 0;
    state.animTop = 0;
    state.animWidth = 0;
  }

  /// 初始化面包屑导航
  _initBreadcrumb() {
    final map = Get.arguments;
    if (map == null || map["topId"] == null || map["topName"] == null) {
      OLogger.e('参数不正确！');
      Get.back();
      return;
    }
    final topId = map["topId"] as String;
    final topName = map["topName"] as String;
    if (map["canCreate"] != null) {
      state.canCreate = map["canCreate"] as bool;
    }
    folderLevel = 0;
    state.title = topName;
    state.breadcrumbBeans.clear();
    state.breadcrumbBeans
        .add(FolderBreadcrumbBean(topName, topId, folderLevel));
    refreshData();
  }

  /// 点击面包屑导航
  void clickBreadcrumb(FolderBreadcrumbBean bean) {
    final list = state.breadcrumbBeans.toList();
    final last = list.last;
    if (bean.folderId != last.folderId) {
      var clickIndex = 0;
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (item.folderId == bean.folderId) {
          clickIndex = i;
        }
      }
      final newList = clickIndex == 0 ? [list[0]] : list.sublist(0, clickIndex);
      state.breadcrumbBeans.clear();
      state.breadcrumbBeans.addAll(newList);
      refreshData();
    }
  }

  /// 刷新数据
  void refreshData({bool showLoading = true}) async {
    final lastBreadcrumb = state.breadcrumbBeans.last;
    // 获取列表数据
    var folderId = lastBreadcrumb.folderId;
    folderLevel = lastBreadcrumb.level;
    _loadListByParent(folderId, showLoading: showLoading);
  }

  /// 点击列表对象
  void onItemClick(CloudDiskItem item) {
    if (item.isFolder) {
      FolderBreadcrumbBean bean = FolderBreadcrumbBean(
          item.folder?.name ?? '', item.folder?.id ?? '', folderLevel + 1);
      state.breadcrumbBeans.add(bean);
      refreshData();
    } else {
      final file = item.file;
      if (file != null ) {
        if (file.fileNamePlusExtension().isImageFileName == true) {
          ImageSliderViewerPage.openViewer(imageList, currentFileId: file.id); // 图片查看器
        } else {
          CloudDiskHelper().downloadAndOpenFile(file, isV3: true); // 其他文件打开
        }
      }
    }
  }

  /// 选中某一个 Item
  void onItemCheckedChange(CloudDiskItem item, bool? checked) {
    if (checked == true) {
      state.cloudDiskItemCheckedList.add(item);
    } else if (checked == false) {
      state.cloudDiskItemCheckedList.removeWhere((element) {
        if (element.isFolder && item.isFolder) {
          return element.folder?.id == item.folder?.id;
        } else if (!element.isFolder && !item.isFolder) {
          return element.file?.id == item.file?.id;
        }
        return false;
      });
    }
  }

  /// 查询数据
  void _loadListByParent(String parentId, {bool showLoading = true}) async {
    if (showLoading) { Loading.show(); }
    state.cloudDiskItemCheckedList.clear();
    List<CloudDiskItem> items = [];
    var listFolder =
        await FileAssembleService.to.listFolderByParentV3(parentId);
    if (listFolder != null) {
      for (var element in listFolder) {
        var item = CloudDiskItem.folder(element);
        items.add(item);
      }
    }
    var listFile = await FileAssembleService.to.listFileByFolderIdV3(parentId);
    if (listFile != null) {
      for (var element in listFile) {
        var item = CloudDiskItem.file(element);
        items.add(item);
      }
    }
    state.cloudDiskItemList..clear()..addAll(items);
    // 数据过滤 把图片对象放入 imageList
    imageList..clear()..addAll(
      state.cloudDiskItemList.where((p0) => !p0.isFolder && p0.file?.fileNamePlusExtension().isImageFileName == true).map((e) {
        FileInfo info = e.file!;
        info.isV3 = true;
        return info;
      }).toList());
    if (showLoading) { Loading.dismiss(); }
  }

  /// 创建文件夹
  createFolder() async {
    final context = Get.context;
    if (context == null) {
      return;
    }
    var folderId = state.breadcrumbBeans.last.folderId;
    if (folderId == O2.o2DefaultUnitParentId) {
      folderId = '';
    }
    _renameController.text = "";
    var result = await O2UI.showCustomDialog(
        context,
        'cloud_disk_action_create_folder'.tr,
        TextField(
          controller: _renameController,
          maxLines: 1,
          keyboardType: TextInputType.text,
          textInputAction: TextInputAction.done,
        ));
    if (result == O2DialogAction.positive) {
      final filename = _renameController.text;
      if (filename.isEmpty) {
        Loading.showError('cloud_disk_create_folder_not_empty_name'.tr);
        return;
      }
      final post = FolderPost(name: filename, superior: folderId);
      await FileAssembleService.to.createFolderV3(post);
      refreshData();
    }
  }

  /// 上传文件
  uploadFile() async {
    var folderId = state.breadcrumbBeans.last.folderId;
    if (folderId == O2.o2DefaultUnitParentId) {
      folderId = O2.o2DefaultPageFirstKey;
    }
    O2Utils.pickerFileOrImage((paths) {
      _uploadFileBegin(paths, folderId);
    }, allowMultiple: true);
  }
  Future<void> _uploadFileBegin(List<String?> paths, String folderId) async {
    if (paths.isEmpty) {
      return;
    }
    for (var element in paths) {
      if (element?.isNotEmpty == true) {
        CloudDiskHelper().uploadFile(File(element!), folderId, true);
      }
    }
    _startUploadAnim();
  }
  openUploadPage() {
    Get.toNamed(O2OARoutes.appCloudDiskUploadList);
  }


  /// 重命名
  rename() async {
    if (state.cloudDiskItemCheckedList.isEmpty) {
      return;
    }
    final context = Get.context;
    if (context == null) {
      return;
    }
    final item = state.cloudDiskItemCheckedList.first;
    _renameController.text = item.displayName;

    var result = await O2UI.showCustomDialog(
        context,
        'cloud_disk_buttons_rename'.tr,
        TextField(
          controller: _renameController,
          maxLines: 1,
          keyboardType: TextInputType.text,
          textInputAction: TextInputAction.done,
        ));
    if (result == O2DialogAction.positive) {
      final filename = _renameController.text;
      if (filename.isEmpty) {
        Loading.showError('cloud_disk_rename_not_empty'.tr);
        return;
      }
      _renameItem(item, filename);
    }
  }

  _renameItem(CloudDiskItem item, String newName) async {
    if (item.isFolder) {
      var folder = item.folder;
      if (folder == null || folder.id == null) {
        return;
      }
      final result =
          await FileAssembleService.to.renameFolderV3(folder.id!, newName);
      if (result != null) {
        refreshData();
      }
    } else {
      var file = item.file;
      if (file == null || file.id == null) {
        return;
      }
      final result =
          await FileAssembleService.to.renameFileV3(file.id!, newName);
      if (result != null) {
        refreshData();
      }
    }
  }

  delete() {
    final context = Get.context;
    if (context == null) {
      return;
    }
    if (state.cloudDiskItemCheckedList.isEmpty) {
      return;
    }
    O2UI.showConfirm(context, 'cloud_disk_delete_confirm'.tr, okPressed: () {
      _deleteItems();
    });
  }

  _deleteItems() async {
    for (var item in state.cloudDiskItemCheckedList) {
      if (item.isFolder) {
        final id = item.folder?.id ?? '';
        if (id.isNotEmpty) {
          await FileAssembleService.to.deleteFolderV3(id);
        }
      } else {
        final id = item.file?.id ?? '';
        if (id.isNotEmpty) {
          await FileAssembleService.to.deleteFileV3(id);
        }
      }
    }
    refreshData();
  }

  /// 移动文件
  move() async {
    if (state.cloudDiskItemCheckedList.isEmpty) {
      return;
    }
    final lastBreadcrumb = state.breadcrumbBeans.first;

    /// 选择企业网盘的目录
    final folder = await FolderPickerPage.openV3(
        lastBreadcrumb.folderId, lastBreadcrumb.displayName);
    if (folder != null && folder is FolderInfo) {
      for (var item in state.cloudDiskItemCheckedList) {
        if (item.isFolder) {
          final id = item.folder?.id ?? '';
          if (id.isNotEmpty) {
            await FileAssembleService.to.moveFolderV3(id, folder.id!);
          }
        } else {
          final id = item.file?.id ?? '';
          if (id.isNotEmpty) {
            await FileAssembleService.to.moveFileV3(id, folder.id!, folder.name!);
          }
        }
      }
      refreshData();
    }
  }

  /// 企业网盘的文件或目录保存到自己的个人网盘
  saveToPan() async {
    if (state.cloudDiskItemCheckedList.isEmpty) {
      return;
    }
    List<String> folderList = [];
    List<String> fileList = [];
    for (var item in state.cloudDiskItemCheckedList) {
      if (item.isFolder) {
        final id = item.folder?.id ?? '';
        if (id.isNotEmpty) {
          folderList.add(id);
        }
      } else {
        final id = item.file?.id ?? '';
        if (id.isNotEmpty) {
          fileList.add(id);
        }
      }
    }

    /// 选择个人网盘的目录
    final folder = await FolderPickerPage.open();
    if (folder != null && folder is FolderInfo) {
      ZoneFileSaveToPerson post =
          ZoneFileSaveToPerson(attIdList: fileList, folderIdList: folderList);
      await FileAssembleService.to.saveToPersonV3(folder.id!, post);
      refreshData();
    }
  }
}
