import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart' as my_get;

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/style/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../../common/widgets/index.dart';

class MindMapHomePage extends StatefulWidget {
  const MindMapHomePage({Key? key}) : super(key: key);

  @override
  _MindMapHomePageState createState() => _MindMapHomePageState();
}

class _MindMapHomePageState extends State<MindMapHomePage>
    with SingleTickerProviderStateMixin {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
  final ScrollController _scrollController = ScrollController(); //listview的控制器
  TextEditingController? newFolderEditingController;
  AnimationController? animationController;
  Animation<double>? animation;
  final List<MindMap> _datas = [];
  final List<MindFolder> _trees = [];
  bool _isFirstLoading = true;
  String _folderName = 'mindmap_root_folder'.tr;
  String _folderId = 'root';
  String _lastPageId = O2.o2DefaultPageFirstKey;
  String _title = "app_name_mindMap".tr;

  @override
  void initState() {
    super.initState();
    _title = my_get.Get.parameters['displayName'] ?? "app_name_mindMap".tr;
    newFolderEditingController = TextEditingController();
    animationController = AnimationController(
        duration: const Duration(milliseconds: 300), vsync: this);
    animation = Tween<double>(begin: 64, end: 400).animate(animationController!)
      ..addListener(() {
        setState(() {});
      });
    _getFolderTree();
    _getData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
  }

  @override
  void dispose() {
    animationController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title: Text(_title)),
      body: _buildBody(),
      floatingActionButtonLocation: const MindMapFloatingActionButtonLocation(),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddMenu,
        tooltip: 'mindmap_create_btn_name'.tr,
        backgroundColor: Theme.of(context).primaryColor,
        child: const Icon(Icons.add, color: Colors.white),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _getFolderTree() async {
    _trees.clear();
    final list = await MindMapService.to.myFolderTree();
    if (list != null) {
      //查询到tree转化成list
      Map<String, dynamic> json = {};
      json['name'] = 'mindmap_root_folder'.tr;
      json['id'] = 'root';
      MindFolder root = MindFolder.fromJson(json);
      root.level = 1;
      _trees.add(root);
      _recursionTree(list, 2);
      // 刷新选中目录的名称
      for (var tree in _trees) {
        if (tree.id == _folderId) {
          _folderName = tree.name ?? 'mindmap_root_folder'.tr;
        }
      }
      setState(() {});
    }
  }

  void _recursionTree(List<MindFolder> children, int level) {
    if (children.isEmpty) {
      return;
    }
    for (var tree in children) {
      tree.level = level;
      _trees.add(tree);
      if (tree.children != null && tree.children!.isNotEmpty) {
        _recursionTree(tree.children!, level + 1);
      }
    }
  }

  void _getData() {
    _lastPageId = O2.o2DefaultPageFirstKey;
    _datas.clear();
    _fetchData();
  }

  void _getMore() {
    if (_datas.isNotEmpty) {
      _lastPageId = _datas.last.id ?? O2.o2DefaultPageFirstKey;
      _fetchData();
    } else {
      OLogger.d('没有更多数据了。。。。。。。。。。');
    }
  }

  void _fetchData() async {
    final list = await MindMapService.to.mindFilterByPage(_lastPageId, _folderId);
    if (list != null && list.isNotEmpty) {
      _datas.addAll(list);
    }
    setState(() {
      _isFirstLoading = false;
    });
    // .then((list) {
    //   if (list != null && list.isNotEmpty) {
    //     _datas.addAll(list);
    //   }
    //   setState(() {
    //     _isFirstLoading = false;
    //   });
    // }).catchError((error) {
    //   print(error);
    //   setState(() {
    //     _isFirstLoading = false;
    //   });
    //   _showErrorSnap('获取数据异常!');
    // });
  }

  void _changeFolder(int index) {
    _folderId = _trees[index].id!;
    _folderName = _trees[index].name!;
    _getData();
  }

  void _newOrEditFolder(String parentId, String? id) async {
    var folderName = newFolderEditingController?.text;
    if (folderName == null || folderName.trim().isEmpty) {
      _showErrorSnap('mindmap_msg_name_not_empty'.tr);
    } else {
      Loading.show();
      final d =
          await MindMapService.to.saveMindFolder(folderName, parentId, id: id);
      if (d != null) {
        Loading.dismiss();
        _getFolderTree();
      }
      // .then((id) {

      // }).catchError((error) {
      //   print(error);
      //   Loading.complete(context);
      //   _showErrorSnap(id == null ? '新建目录失败！' : '修改目录失败！');
      // });
    }
  }

  ///
  /// 删除目录
  /// 先判断是否有子目录，然后查询是否有文件 ，全都没有才能删除
  ///
  void _deleteFolderValidate(int index) async {
    MindFolder deleteFolder = _trees[index];
    bool hasSubFolder = true;
    if (index + 1 < _trees.length) {
      MindFolder next = _trees[index + 1];
      if (deleteFolder.level! < next.level!) {
        //是子目录
        _showErrorSnap('mindmap_msg_have_sub_folder'.tr);
      } else {
        hasSubFolder = false;
      }
    } else {
      hasSubFolder = false;
    }
    if (!hasSubFolder) {
      List<MindMap>? list = await MindMapService.to
          .mindFilterByPage(O2.o2DefaultPageFirstKey, deleteFolder.id!);
      if (list != null && list.isNotEmpty) {
        _showErrorSnap('mindmap_msg_have_map_in_folder'.tr);
      } else {
        O2UI.showConfirm(my_get.Get.context, 'mindmap_msg_confirm_delete_folder'.tr, okPressed: () {
          _deleteFolder(index);
        });
        // O2Dialogs.showConfirmDialog(message: '确定要删除这个目录？', context: context)
        //     .then((result) {
        //   if (result == O2DialogAction.positive) {
        //     _deleteFolder(index);
        //   }
        // });
      }
    }
  }

  void _deleteFolder(int index) async {
    MindFolder deleteFolder = _trees[index];
    bool result = await MindMapService.to.deleteMindFolder(deleteFolder.id!);
    if (result) {
      if (_folderId == deleteFolder.id) {
        _changeFolder(0);
      }
      setState(() {
        _trees.removeAt(index);
      });
    }
  }

  ///新建脑图
  void _newMindMap() async {
    var mindName = newFolderEditingController?.text;
    if (mindName == null || mindName.trim().isEmpty) {
      _showErrorSnap('mindmap_msg_map_name_not_empty'.tr);
    } else {
      Loading.show();
      Node node = Node(data: NodeData(text: mindName), children: []);
      Map<String, dynamic> dataJson = {};
      dataJson['root'] = node.toJson();
      dataJson['template'] = 'default';
      dataJson['theme'] = 'fresh-blue';
      MindMapData data = MindMapData.fromJson(dataJson);
      Map<String, dynamic> mindJson = {};
      mindJson['name'] = mindName;
      mindJson['folderId'] = _folderId;
      mindJson['fileVersion'] = 0;
      MindMap map = MindMap.fromJson(mindJson);
      final id = await MindMapService.to.saveMindMap(map, data);
      if (id != null && id.isNotEmpty) {
        Loading.dismiss();
        map.id = id;
        _datas.add(map);
        setState(() {});
        _gotoMindMapView(_datas.length - 1);
      }
      // .then((id) {
      //   if (id.isNotEmpty) {

      //   }
      // }).catchError((error) {
      //   print('新建脑图异常$error');
      //   Loading.complete(context);
      //   _showErrorSnap('新建脑图失败！');
      // });
    }
  }

  void _renameMindMap(MindMap map) async {
    newFolderEditingController?.text = map.name ?? '';
    final result = await O2UI.showCustomDialog(
        context,
        'mindmap_rename_map'.tr,
        TextField(
          controller: newFolderEditingController,
          autofocus: true,
          decoration:
             InputDecoration(labelText: 'mindmap_name_label'.tr, hintText: 'mindmap_msg_enter_map_name'.tr),
        ));
    if (result != null && result == O2DialogAction.positive) {
      _renameMindMap2Remote(map);
    }
    // O2Dialogs.showCustomDialog(
    //     context: context,
    //     title: '重命名脑图',
    //     content: TextField(
    //       controller: newFolderEditingController,
    //       autofocus: true,
    //       decoration:
    //       const InputDecoration(labelText: '名称', hintText: '请输入脑图名称'),
    //     )).then((action) {
    //   if (action == O2DialogAction.positive) {
    //     _renameMindMap2Remote(map);
    //   }
    // });
  }

  ///新建脑图
  void _renameMindMap2Remote(MindMap map) async {
    var mindName = newFolderEditingController?.text;
    if (mindName == null || mindName.trim().isEmpty) {
      _showErrorSnap('mindmap_msg_map_name_not_empty'.tr);
    } else {
      map.name = mindName;
      var allMindMapData =
          await MindMapService.to.mindMap(map.id!); //要重新get一下 不然content没有内容
      if (allMindMapData != null) {
        allMindMapData.name = mindName;
        final id = await MindMapService.to.renameMindMap(allMindMapData);
        if (id != null) {
          setState(() {
            OLogger.d('更新了脑图名称。。。。。。。。');
          });
        }
      }

      // MindMapService.to.renameMindMap(allMindMapData).then((id) {
      //   if (id.isNotEmpty) {
      //     setState(() {
      //       print('更新了脑图名称。。。。。。。。');
      //     });
      //   }
      // }).catchError((error) {
      //   print('更新脑图异常$error');
      //   _showErrorSnap('更新脑图失败！');
      // });
    }
  }

  void _deleteMindMap(MindMap map) {
    O2UI.showConfirm(context, 'mindmap_msg_confirm_delete_map'.trArgs([map.name??'']), okPressed: () {
      _deleteMindMap2Server(map);
    });

    // O2Dialogs.showConfirmDialog(
    //         message: '确定要删除这个脑图，名称：【${map.name}】？', context: context)
    //     .then((result) {
    //   if (result == O2DialogAction.positive) {
    //     MindMapService.to.deleteMindMap(map.id!).then((result) {
    //       if (!result) {
    //         print('删除失败');
    //       }
    //       _getData();
    //     }).catchError((error) {
    //       print('删除脑图出错，$error');
    //       _showErrorSnap('删除脑图出错！');
    //     });
    //   }
    // });
  }

  void _deleteMindMap2Server(MindMap map) async {
    final result = await MindMapService.to.deleteMindMap(map.id!);
    if (!result) {
      OLogger.d('删除失败');
    }
    _getData();
  }

  void _gotoMindMapView(int index) async {
    OLogger.d('点了第$index行。。。。。。。打开脑图编辑器');
    // await AppRouterManager.instance.router?.navigateTo(context, '/mindMap/${_datas[index].id}');
    await my_get.Get.toNamed(O2OARoutes.appMindMapView,
        arguments: {'mapId': _datas[index].id});
    OLogger.d('返回了。。。。刷新数据');
    _getData();
  }

  Widget _buildBody() {
    if (_isFirstLoading) {
      return const Center(child: CircularProgressIndicator());
    } else {
      return Column(
        children: <Widget>[
          Expanded(
            child: _datas.isNotEmpty ? _gridView() : _emptyDataView(),
          ),
          _bottomFolderBar()
        ],
      );
    }
  }

  //grid 列表
  Widget _gridView() {
    return Padding(
        padding: const EdgeInsets.all(5),
        child: GridView.builder(
            controller: _scrollController,
            itemCount: _datas.length,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, mainAxisSpacing: 5, crossAxisSpacing: 5),
            itemBuilder: _gridItemView));
  }

  Widget _gridItemView(BuildContext context, int index) {
    MindMap data = _datas[index];
    final url = O2ApiManager.instance.getFileURL(data.icon);
    return InkWell(
      child: GridTile(
        footer: Container(
          height: 40,
          decoration: BoxDecoration(
              border: Border.all(color: AppColor.dividerColor),
              color: Theme.of(context).scaffoldBackgroundColor),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(8, 0, 0, 0),
                  child: Text(data.name ?? '',
                      style: Theme.of(context).textTheme.bodyLarge),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.more_vert),
                onPressed: () => _showMindMapOperationMenu(data),
              )
            ],
          ),
        ),
        child: Container(
            height: 144,
            color: AppColor.o2Dark,
            child: Center(
              child: url.isEmpty
                  ? const AssetsImageView('unknow.png', width: 48, height: 48)
                  : FadeInImage.assetNetwork(
                      placeholder: 'assets/images/unknow.png', image: url),
            )),
      ),
      onTap: () {
        _gotoMindMapView(index);
      },
    );
  }

  // //列表
  // Widget _listView() {
  //   return ListView.separated(
  //       controller: _scrollController,
  //       itemBuilder: _itemView,
  //       separatorBuilder: _separatorView,
  //       itemCount: _datas.length);
  // }

  //列表项外框和点击事件
  // Widget _itemView(BuildContext context, int index) {
  //   return InkWell(
  //     child: _slideRow(index, _datas[index]),
  //     onTap: () {
  //       _gotoMindMapView(index);
  //     },
  //   );
  // }

  //列表项滑动控件
  // Widget _slideRow(int index, MindMap data) {
  //   return Slidable(
  //     // The end action pane is the one at the right or the bottom side.
  //     endActionPane: ActionPane(
  //       motion: const ScrollMotion(),
  //       children: [
  //         SlidableAction(
  //           onPressed: (_) {
  //             _deleteMindMap(_datas[index]);
  //           },
  //           backgroundColor: Colors.red,
  //           foregroundColor: Colors.white,
  //           icon: Icons.delete,
  //           label: '删除',
  //         ),
  //       ],
  //     ),
  //     child: _rowContentView(data),
  //   );
  // }

  //列表项内容
  // Widget _rowContentView(MindMap data) {
  //   final url = O2ApiManager.instance.getFileURL(data.icon);
  //   return ListTile(
  //     leading: Container(
  //       width: 48,
  //       height: 48,
  //       color: AppColor.o2Dark,
  //       child: url.isEmpty
  //           ? const AssetsImageView('unknow.png', width: 48, height: 48)
  //           : FadeInImage.assetNetwork(
  //               placeholder: 'assets/images/unknow.png',
  //               image: url,
  //               width: 48,
  //               height: 48,
  //             ),
  //     ),
  //     title: Text(data.name ?? ''),
  //     subtitle: Text('版本：${data.fileVersion}'),
  //     trailing: Text(_timeFormat(data.updateTime),
  //         style: Theme.of(context).textTheme.bodySmall),
  //   );
  // }

  ///
  /// @param time 2019-02-11 12:20:00
  // String _timeFormat(String? time) {
  //   if (time != null && time.isNotEmpty && time.length > 16) {
  //     var year = time.substring(0, 4);
  //     if (DateTime.now().year == int.parse(year)) {
  //       return time.substring(5, 16);
  //     } else {
  //       return time.substring(0, 16);
  //     }
  //   } else {
  //     return "";
  //   }
  // }

  //分割线
  // Widget _separatorView(BuildContext context, int index) {
  //   return const Divider(height: 1);
  // }

  // 没有数据的时候显示的文字
  Widget _emptyDataView() {
    return Center(
        child: Text('empty_data'.tr, style: Theme.of(context).textTheme.bodySmall));
  }

  // 底部 文件夹 栏
  Widget _bottomFolderBar() {
    var screenWidth = MediaQuery.of(context).size.width;
    return SizedBox(
        height: animation!.value,
        child: Stack(
          children: <Widget>[
            Positioned(
                left: 0,
                top: 0,
                width: screenWidth,
                height: 400,
                child: Column(
                  children: <Widget>[
                    _bottomFolderBarHeader(),
                    Expanded(
                      child: Container(
                        child: _bottomFolderListView(),
                      ),
                    )
                  ],
                ))
          ],
        ));
  }

  Widget _bottomFolderBarHeader() {
    return InkWell(
      onTap: () {
        if (animation!.value > 64) {
          animationController?.reverse();
        } else {
          animationController?.forward();
        }
      },
      child: Container(
        padding: const EdgeInsets.all(16),
        color: Theme.of(context).colorScheme.background,
        child: Row(
          children: <Widget>[
            const Icon(Icons.folder, size: 32),
            Expanded(
              child: Align(
                alignment: Alignment.center,
                child: Text(_folderName,
                    style: Theme.of(context).textTheme.bodyLarge),
              ),
            ),
            animation!.value > 64
                ? const Icon(Icons.arrow_drop_down, size: 32)
                : const Icon(Icons.arrow_drop_up, size: 32)
          ],
        ),
      ),
    );
  }

  Widget _bottomFolderListView() {
    return ListView.builder(
      itemBuilder: _folderItemView,
      itemCount: _trees.length,
    );
  }

  Widget _folderItemView(BuildContext context, int index) {
    final folder = _trees[index];
    return InkWell(
      onTap: () {
        _changeFolder(index);
        animationController?.reverse();
      },
      child: Slidable(
          endActionPane: ActionPane(
            motion: const ScrollMotion(),
            children: _folderSlideMenu(index),
          ),
          child: ListTile(
            contentPadding: EdgeInsets.only(left: 16.0 + ((folder.level ?? 0) * 8.0), right: 16),
            title: Text(folder.name ?? ''),
            selected: folder.id == _folderId,
          )),
    );
  }

  ///
  /// 目录列表横拉菜单
  ///
  List<Widget> _folderSlideMenu(int index) {
    if (index == 0) {
      return [];
    } else {
      return <Widget>[
        SlidableAction(
          onPressed: (_) {
            OLogger.d('删除目录。。。。。。。。');
            _deleteFolderValidate(index);
          },
          backgroundColor: Colors.red,
          foregroundColor: Colors.white,
          icon: Icons.delete,
          label: 'mindmap_delete_btn_name'.tr,
        ),
        SlidableAction(
          onPressed: (_) {
            OLogger.d('重命名目录。。。。。。。。');
            _showFolderDialog(_trees[index]);
          },
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white,
          icon: Icons.edit,
          label: 'mindmap_rename_btn_name'.tr,
        )
      ];
    }
  }

  ///
  /// 底部弹出菜单 选择 新建脑图 新建文件夹
  ///
  void _showAddMenu() {
    O2UI.showBottomSheetWithCancel(context, <Widget>[
      ListTile(
        onTap: () {
          OLogger.d('新建脑图。。。。。。。。');
          Navigator.of(context).pop();
          _showNewMindMap();
        },
        leading: const Icon(Icons.add_box),
        title: Text('mindmap_create_map'.tr, style: Theme.of(context).textTheme.bodyMedium),
      ),
      ListTile(
        onTap: () {
          Navigator.of(context).pop();
          _showFolderDialog(null);
        },
        leading: const Icon(Icons.create_new_folder),
        title: Text('mindmap_create_folder'.tr, style: Theme.of(context).textTheme.bodyMedium),
      )
    ]);
  }

  void _showMindMapOperationMenu(MindMap data) {
    OLogger.d('显示菜单。。。${data.name}');
    O2UI.showBottomSheetWithCancel(context, <Widget>[
      ListTile(
        onTap: () {
          Navigator.of(context).pop();
          _renameMindMap(data);
        },
        leading: const Icon(Icons.edit),
        title: Text('mindmap_rename_btn_name'.tr, style: Theme.of(context).textTheme.bodyMedium),
      ),
      ListTile(
        onTap: () {
          Navigator.of(context).pop();
          _deleteMindMap(data);
        },
        leading: const Icon(Icons.delete_forever),
        title: Text('mindmap_delete_btn_name'.tr, style: Theme.of(context).textTheme.bodyMedium),
      )
    ]);
  }

  void _showErrorSnap(String message) {
    // O2SnackBars.showSnackBar(_scaffoldKey, message);
    Loading.toast(message);
  }

  ///
  /// 新建目录
  ///
  void _showFolderDialog(MindFolder? old) async {
    String title;
    String parentId;
    String? id;
    if (old != null) {
      newFolderEditingController?.text = old.name ?? '';
      title = 'mindmap_rename_btn_name'.tr;
      parentId = old.parentId!;
      id = old.id!;
    } else {
      newFolderEditingController?.text = '';
      title = 'mindmap_msg_create_under_foler'.trArgs([_folderName]);
      parentId = _folderId;
      id = null;
    }
    var result = await O2UI.showCustomDialog(
        context,
        title,
        TextField(
          controller: newFolderEditingController,
          autofocus: true,
          decoration:
               InputDecoration(labelText: 'mindmap_name_label'.tr, hintText: 'mindmap_msg_enter_folder_name'.tr),
        ));
    if (result != null && result == O2DialogAction.positive) {
      _newOrEditFolder(parentId, id);
    }
    // O2Dialogs.showCustomDialog(
    //     context: context,
    //     title: title,
    //     content: TextField(
    //       controller: newFolderEditingController,
    //       autofocus: true,
    //       decoration:
    //           const InputDecoration(labelText: '名称', hintText: '请输入目录名称'),
    //     )).then((action) {
    //   if (action == O2DialogAction.positive) {
    //     _newOrEditFolder(parentId, id);
    //   }
    // });
  }

  ///
  /// 新建脑图Dialog
  ///
  void _showNewMindMap() async {
    newFolderEditingController?.text = '';
    var result = await O2UI.showCustomDialog(
        context,
        'mindmap_msg_create_map_under_foler'.trArgs([_folderName]),
        TextField(
          controller: newFolderEditingController,
          autofocus: true,
          decoration:
               InputDecoration(labelText: 'mindmap_map_name_label'.tr, hintText: 'mindmap_msg_enter_map_name'.tr),
        ));
    if (result != null && result == O2DialogAction.positive) {
      _newMindMap();
    }
    // O2Dialogs.showCustomDialog(
    //     context: context,
    //     title: '在【$_folderName】下新建脑图',
    //     content: TextField(
    //       controller: newFolderEditingController,
    //       autofocus: true,
    //       decoration:
    //           const InputDecoration(labelText: '脑图名称', hintText: '请输入脑图名称'),
    //     )).then((action) {
    //   if (action == O2DialogAction.positive) {
    //     _newMindMap();
    //   }
    // });
  }
}
