import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_simple_treeview/flutter_simple_treeview.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/user/user_device/controller.dart';
import 'package:flyinsono/pages/user/user_device/widgets/tree_node_widget.dart';
import 'package:get/get.dart' hide Node;

///分享设备页面
class ShareTerminalPage extends FStatefulWidget implements FPage {
  ShareTerminalPage({this.pageName = 'ShareTerminalPage', Key? key})
      : super(key: key);
  @override
  final String pageName;
  @override
  FState<ShareTerminalPage> createState() => _ShareTerminalState();
}

class _ShareTerminalState extends FState<ShareTerminalPage> {
  ///设备Controller
  final controller = Get.find<DeviceController>();

  ///树形视图Controller
  TreeController treeController = TreeController();

  //所有已选中部门节点的集合，用于判断节点是否需要展开
  final _deps = <String>[];
  List<TreeNode> _nodes = [];
  Timer? _debounce;
  @override
  void initState() {
    _initTree(true);
    super.initState();
  }

  @override
  void dispose() {
    controller.textEditingController.text = '';
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    final selectedCount = controller.state.selectedUsers.length; //已选中的人数

    final width = 350.0;
    final height = 550.0;
    return FSimpleDialog(
      backgroundColor: Colors.white,
      title: FText(
        i18nBook.user.shareDevice.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      bottomButton: _buildShareTerminalBottomButton(),
      children: [
        FRow(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            FColumn(
              children: [
                FContainer(
                  width: 350,
                  child: FSearchInput(
                    businessParent: this.widget,
                    hintText: i18nBook.common.search.t,
                    onChanged: (value) {
                      if (_debounce?.isActive ?? false) _debounce?.cancel();
                      _debounce = Timer(Duration(milliseconds: 300), () async {
                        await controller.orgDeviceController.initOrgUsers(
                            keyword: controller.textEditingController.text);
                        _nodes.clear();
                        _initTree(true);
                        setState(() {});
                      });
                    },
                    serchOnPressed: () async {
                      await controller.orgDeviceController.initOrgUsers(
                          keyword: controller.textEditingController.text);
                      _nodes.clear();
                      _initTree(true);
                      setState(() {});
                    },
                    controller: controller.textEditingController,
                  ),
                ),
                FContainer(
                  alignment: Alignment.topCenter,
                  margin: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                  width: width,
                  height: height,
                  child: FListView(
                    shrinkWrap: true,
                    children: [
                      QuickFWidget(
                        TreeView(
                          treeController: treeController,
                          nodes: _nodes,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            FContainer(
              height: height - 20,
              child: FVerticalDivider(
                thickness: 1,
                color: Colors.grey,
                width: 1,
              ),
            ),
            FContainer(
              margin: EdgeInsets.only(top: 50, left: 40, bottom: 20),
              height: height,
              width: width,
              child: FColumn(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  FText(
                    i18nBook.common.selected.t,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  if (selectedCount > 0) ...[
                    _buildSelectedUsers(height),
                  ],
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  ///初始化树形结构
  void _initTree(bool isFirst) {
    List<TreeNode> children = [];
    final deps = controller.state.deps; //二级菜单
    final users = controller.state.users; //所有用户，最底层
    deps.forEach((element) {
      //循环部门，用于初始化所有的二级节点
      List<TreeNode> userChildren = [];
      //寻找当前部门下所有的用户
      final userinfos =
          users.where((e) => e.organizationCode == element.organizationCode);
      userinfos.forEach((u) {
        userChildren.add(
          TreeNode(
            key: ValueKey<String>(u.userCode ?? ''),
            content: FTreeNodeWidget(
              u.displayName!,
              onNodeTap: () {
                controller.onNodeTap(u.userCode ?? '');
                setState(() {});
              },
              isSelected: controller.state.selectedUsers
                  .any((element) => element.userCode == u.userCode),
            ),
          ),
        );
      });
      var expanded = controller.state.selectedUsers
          .any((u) => userinfos.any((x) => x.userCode == u.userCode));

      ///首次加载时，判断节点下是否履有已经选择的用户，有则展开节点，无则不展开
      if (isFirst && expanded && !_deps.contains(element.organizationCode)) {
        _deps.add(element.organizationCode!);
      }
      var orgNodeKey = ValueKey<String>(element.organizationCode ?? '');
      if (_deps.contains(element.organizationCode)) {
        treeController.expandNode(orgNodeKey);
      } else {
        treeController.collapseNode(orgNodeKey);
      }
      children.add(
        TreeNode(
          key: orgNodeKey,
          content: FTreeNodeWidget(
            element.organizationName ?? '',
            isParent: true,
            onNodeTap: () {
              onExpandNodeChange(orgNodeKey);
            },
          ),
          children: userChildren,
        ),
      );
    });
    List<TreeNode> noDepUsersChilden = [];
    //找出所有未分配的用户，单独作为一个节点，与部门同级
    final noDepUsers = users.where((element) =>
        (element.organizationCode != null &&
            element.organizationCode! == Store.user.rootOrganizationCode));
    noDepUsers.forEach((u) {
      noDepUsersChilden.add(
        TreeNode(
          key: ValueKey<String>(u.userCode ?? ''),
          content: FTreeNodeWidget(
            u.displayName!,
            onNodeTap: () {
              controller.onNodeTap(u.userCode ?? '');
              setState(() {});
            },
            isSelected: controller.state.selectedUsers
                .any((element) => element.userCode == u.userCode),
          ),
        ),
      );
    });
    var expanded = controller.state.selectedUsers
        .any((u) => noDepUsers.any((x) => x.userCode == u.userCode));
    if (expanded && isFirst && !_deps.contains('noDepUsers')) {
      _deps.add('noDepUsers');
    }
    var noDepUsersKey = ValueKey<String>("noDepUsers");
    if (_deps.contains('noDepUsers')) {
      treeController.expandNode(noDepUsersKey);
    } else {
      treeController.collapseNode(noDepUsersKey);
    }
    children.add(
      TreeNode(
        key: noDepUsersKey,
        content: FTreeNodeWidget(
          i18nBook.common.unDistributed.t,
          isParent: true,
          onNodeTap: () {
            onExpandNodeChange(noDepUsersKey);
          },
        ),
        children: noDepUsersChilden,
      ),
    );
    var rootOrgKey = ValueKey<String>(Store.user.rootOrganizationCode!);
    _nodes.add(
      TreeNode(
        key: rootOrgKey,
        content: FTreeNodeWidget(
          Store.user.rootOrganizationName,
          isParent: true,
          onNodeTap: () {
            onExpandNodeChange(rootOrgKey);
          },
        ),
        children: children,
      ),
    );
    treeController.expandNode(rootOrgKey);
  }

  void onExpandNodeChange(ValueKey<String> key) {
    ///已经展开的则收起，已收起则展开
    if (treeController.isNodeExpanded(key)) {
      setState(() {
        treeController.collapseNode(key);
      });
    } else {
      setState(() {
        treeController.expandNode(key);
      });
    }
  }

  ///已选用户集合
  FWidget _buildSelectedUsers(double height) {
    return FContainer(
      margin: EdgeInsets.only(top: 20),
      height: height - 90,
      child: FListView.builder(
        itemCount: controller.state.selectedUsers.length,
        itemBuilder: (context, index) {
          final user = controller.state.selectedUsers[index];
          return FContainer(
            margin: EdgeInsets.only(left: 5, top: 10),
            child: FRow(
              children: [
                if (user.headImageUrl!.isNotEmpty) ...[
                  FContainer(
                    margin: EdgeInsets.only(right: 10),
                    child: FClipOval(
                      child: FImage.network(
                        user.headImageUrl!,
                        width: 40,
                        height: 40,
                      ),
                    ),
                  ),
                ] else ...[
                  FContainer(
                    margin: EdgeInsets.only(right: 10),
                    child: FClipOval(
                      child: FAvatar(
                        imageProvider:
                            AssetImage("assets/images/avatar_man.png"),
                        size: 40,
                      ),
                    ),
                  ),
                ],
                FText(
                  user.displayName!,
                  style: TextStyle(
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  ///分享设备底部按钮
  FWidget _buildShareTerminalBottomButton() {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        // mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          FElevatedButton(
            name: "submitUsers",
            businessParent: this.widget,
            onPressed: () {
              controller.submitUsers();
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.confirm4Btn.t),
          ),
          FSizedBox(
            width: 20,
          ),
          FOutlinedButton(
            businessParent: this.widget,
            name: "back",
            onPressed: () => router.back(),
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                Colors.white,
              ),
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(vertical: 15, horizontal: 25),
              ),
            ),
            child: FText(
              i18nBook.common.cancel4Btn.t,
              style: TextStyle(
                color: Color.fromRGBO(61, 146, 252, 1),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
