import 'package:flutter/material.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import '../model/tree_node_model.dart';
import '../utils/GetConfig.dart';
import '../utils/flutter_toast.dart';
import 'ImageText.dart';

class ChoosePositionDialog extends StatefulWidget {
  final ValueChanged<TreeNodeModel> callback;
  final ValueChanged<TreeNodeModel> confirm;
  final Function close;
  final Function noneSelect;
  final List<dynamic> data;

  TreeNodeModel selectedModel;
  final String theme;
  final String name;

  ChoosePositionDialog({
    this.callback,
    @required this.data,
    this.noneSelect,
    this.confirm,
    this.close,
    this.theme,
    this.selectedModel,
    this.name,
  });

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

class _PositionDescriptionDialogState extends State<ChoosePositionDialog> {
  ///保存所有数据的List
  List<TreeNodeModel> nodes = [];

  ///保存当前展示数据的List
  List<TreeNodeModel> expand = [];
  List<TreeNodeModel> seleList = [];

  ///保存List的下标的List，用来做标记用
  List<String> mark = [];

  ///第一个节点的index
  int nodeId = 1;

  TreeNodeModel _selectedModel;

  @override
  void initState() {
    super.initState();
    _selectedModel = TreeNodeModel();
    _selectedModel = widget.selectedModel;
    _selectedModel.name = widget.name;
    for (var item in widget.data) {
      parseData(item);
    }
    _addRoot();
    if (_selectedModel.parentId != null) {
      _nodesId(_selectedModel.parentId);
      setState(() {});
    }
  }

  _nodesId(String id) {
    for (final TreeNodeModel node in nodes) {
      if (node.id == id) {
        if (node.parentId == '0') {
          _expand(node.id);
          for (int i = seleList.length - 1; i >= 0; i--) {
            _expand(seleList[i].id);
          }
        } else {
          seleList.add(node);
          _nodesId(node.parentId);
        }
      }
    }
  }

  void parseData(item, {int depth = 0, int fatherId = -1}) {
    nodes.add(TreeNodeModel.withData(item, depth: depth, expand: false, fatherId: fatherId));
    if (item['children'] != null) {
      final items = item['children'];
      for (var it in items) {
        parseData(it, depth: depth + 1, fatherId: depth + 1);
      }
    }
  }

  void _addRoot() {
    for (final TreeNodeModel node in nodes) {
      if (node.fatherId == -1) {
        expand.add(node);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<Object>(builder: (context, snapshot) {
      return SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              buildTopBar(context),
              buildListContent(context, widget.data),
              Container(
                width: double.infinity,
                height: 96.rpx,
                child: RaisedButton(
                  shape: const BeveledRectangleBorder(),
                  color: GetConfig.getColor(widget.theme),
                  onPressed: () => onPressed(),
                  child: Text(
                    '确定',
                    style: Theme.of(context).textTheme.subtitle1.copyWith(color: Colors.white),
                  ),
                ),
              )
            ],
          ),
        ),
      );
    });
  }

  // 点击确定
  void onPressed() {
    if (_selectedModel != null) {
      Navigator.of(context).pop();
      if (widget.confirm != null) {
        widget.confirm(_selectedModel);
      }
    } else {
      FlutterToast.toastCenter('请选择位置!');
    }
  }

  // 关闭
  void cancel(context) {
    if (widget.close != null) {
      widget.close();
    }
    if (_selectedModel != null && widget.noneSelect != null) {
      widget.noneSelect();
    }
    Navigator.of(context).pop();
  }

  // 头部
  Widget buildTopBar(context) {
    return Container(
      height: 44.px,
      child: Stack(children: [
        Container(
          padding: EdgeInsets.symmetric(vertical: 10.px),
          decoration: ShapeDecoration(
              color: const Color(0xFFefeff4),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(5.px), topRight: Radius.circular(5.px)))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '${_selectedModel.name == null ? '选择位置' : (_selectedModel.absolutePosition ?? (_selectedModel.fullName ?? _selectedModel.name))}',
                style: Theme.of(context).textTheme.subtitle1,
                overflow: TextOverflow.ellipsis,
              )
            ],
          ),
        ),
        Align(
            alignment: Alignment.centerRight,
            child: Container(
              padding: const EdgeInsets.only(right: 10),
              child: IconButton(
                onPressed: () => cancel(context),
                icon: const Icon(Icons.clear,size: 20,),
              ),
            ))
      ]),
    );
  }

  Widget buildListContent(context, data) {
    return Container(
        height: 300.px,
        child: ListView(
          children: _buildNode(expand),
        ));
  }

  ///扩展机构树：id代表被点击的机构id
  /// 做法是遍历整个list列表，将直接挂在该机构下面的节点增加到一个临时列表中，
  ///然后将临时列表插入到被点击的机构下面
  void _expand(String id) {
    //保存到临时列表
    List<TreeNodeModel> tmp = [];
    for (final TreeNodeModel node in nodes) {
      if (node.parentId == id) {
        tmp.add(node);
      }
    }
    //找到插入点
    int index = -1;
    int length = expand.length;
    for (int i = 0; i < length; i++) {
      if (id == expand[i].id) {
        index = i + 1;
        break;
      }
    }
    //插入
    expand.insertAll(index, tmp);
  }

  //收起机构树：id代表被点击的机构id
  // 做法是遍历整个expand列表，将直接和间接挂在该机构下面的节点标记，
  //将这些被标记节点删除即可，此处用到的是将没有被标记的节点加入到新的列表中
  void _collect(String id) {
    //清楚之前的标记
    mark.clear();
    //标记
    _mark(id);
    //重新对expand赋值
    List<TreeNodeModel> tmp = [];
    for (final TreeNodeModel node in expand) {
      if (!mark.contains(node.id)) {
        tmp.add(node);
      } else {
        node.expand = false;
      }
    }
    expand.clear();
    expand.addAll(tmp);
  }

  //标记，在收起机构树的时候用到
  void _mark(String id) {
    for (TreeNodeModel node in expand) {
      if (id == node.parentId) {
        if (node.children != null) {
          _mark(node.id);
        }
        mark.add(node.id);
      }
    }
  }

  ///构建元素
  List<Widget> _buildNode(List<TreeNodeModel> nodes) {
    List<Widget> widgets = [];
    if (nodes != null && nodes.isNotEmpty) {
      for (final TreeNodeModel node in nodes) {
        widgets.add(InkWell(
          child: Container(
              color: node.id == _selectedModel.id ? const Color(0xfff0f0f0) : Colors.white,
              child: ImageText(
                node.children != null
                    ? node.expand
                        ? 'assets/images/expand.png'
                        : 'assets/images/collect.png'
                    : 'assets/images/member.png',
                node.name,
                padding: node.depth * 20.0, //如果展示搜索结果，那么不缩进
              )),
          onTap: () {
            if (node.children != null) {
              if (node.expand) {
                //之前是扩展状态，收起列表
                node.expand = false;
                _collect(node.id);
              } else {
                //之前是收起状态，扩展列表
                node.expand = true;
                _expand(node.id);
              }
              setState(() {});
            }
            // 保存点击位置信息
            setState(() {
              _selectedModel = node;
            });
            if (widget.callback != null) {
              widget.callback(node);
            }
          },
        ));
      }
    }
    return widgets;
  }
}
