import 'dart:convert';

import 'package:fis_common/event/event_type.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/tree/flutter_treeview/lib/flutter_treeview.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/services/entity/default_entry_setting.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/controller.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/widgets/entry_selected_item.dart';
import 'package:get/get.dart' hide Node;

class EntrySelectionPage extends StatefulWidget implements FPage {
  final void Function(String, String) onPressed;
  late final bool isUserCenter;
  late final List<ThesaurusItemDTO> thesaurus;
  late final FEventHandler<String> onThesaurusChange;
  late final VocabularyEntryController? controller;
  final TextEditingController? desController;
  final TextEditingController? summaryController;

  @override
  final String pageName;
  EntrySelectionPage(
    this.onPressed, {
    bool? isUserCenter,
    List<ThesaurusItemDTO>? thesaurus,
    FEventHandler<String>? onThesaurusChange,
    VocabularyEntryController? controller,
    this.desController,
    this.summaryController,
    this.pageName = 'EntrySelectionPage',
  }) {
    this.isUserCenter = isUserCenter ?? false;
    this.thesaurus = thesaurus ?? [];
    this.onThesaurusChange = onThesaurusChange ?? new FEventHandler();
    this.controller = controller;
  }

  @override
  State<StatefulWidget> createState() {
    return EntrySelectionState();
  }
}

class EntrySelectionState extends State<EntrySelectionPage> {
  late final TextEditingController _desController;
  late final TextEditingController _summaryController;
  final ScrollController _desScrollerController = ScrollController();
  final ScrollController _summaryScrollerController = ScrollController();
  List<ThesaurusItemDTO> _defaultThesaurusList = [];
  final TextStyle _textStyle = TextStyle(fontSize: 16);
  DefaultEntrySetting defaultEntrySetting = DefaultEntrySetting.ins;

  ///树形视图Controller
  late TreeViewController treeController = TreeViewController(children: _nodes);

  List<Node> _nodes = [];

  @override
  initState() {
    _desController = widget.desController ?? TextEditingController();
    _summaryController = widget.summaryController ?? TextEditingController();
    if (defaultEntrySetting.defaultEntry.isEmpty && widget.thesaurus.isEmpty) {
      return;
    }
    widget.onThesaurusChange.addListener((sender, e) {
      setState(() {
        _initNodes(keyword: e);
      });
    });
    _initNodes();
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    if (defaultEntrySetting.defaultEntry.isEmpty) {
      PromptBox.toast(i18nBook.remedical.noEntrys.t);
      return FSizedBox();
    }

    return FScaffold(
      appBar: widget.isUserCenter
          ? null
          : FAppBar(
              centerTitle: true,
              title: FText(
                i18nBook.remedical.selectWord.t,
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white,
                ),
              ),
              actions: [
                FElevatedButton(
                  name: "confirm",
                  businessParent: this.widget,
                  style: ButtonStyle(elevation: MaterialStateProperty.all(0)),
                  onPressed: () {
                    widget.onPressed
                        .call(_desController.text, _summaryController.text);
                    router.back();
                  },
                  child: FText(i18nBook.common.confirm.t),
                )
              ],
            ),
      body: _buildEntrySelectionContentView(),
      backgroundColor: widget.isUserCenter ? Colors.white : Colors.grey[200],
    );
  }

  ///手机端词条选择内容视图
  FWidget _buildEntrySelectionContentView() {
    List<FWidget> chidren = [];
    chidren.add(FSizedBox(height: 10));
    if (!widget.isUserCenter) {
      chidren.addAll(_buildSummaryAndDes());
      chidren.add(FSizedBox(height: 5));
    }
    chidren.add(FDivider(
      thickness: 1,
      height: 1,
      color: Colors.grey[400],
    ));
    chidren.addAll(_buildEntryTree());
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: chidren,
    );
  }

  List<FWidget> _buildSummaryAndDes() {
    return [
      FContainer(
        margin: EdgeInsets.only(left: 15, bottom: 5),
        child: FText(
          i18nBook.remedical.description.t,
          style: _textStyle,
        ),
      ),
      FContainer(
        margin: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
        child: FTextField(
          scrollController: _desScrollerController,
          controller: _desController,
          maxLines: 3,
          style: _textStyle,
          textAlignVertical: TextAlignVertical.top,
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.black,
              ),
            ),
          ),
          onChanged: (v) {},
        ),
      ),
      FContainer(
        margin: EdgeInsets.only(left: 15),
        child: FText(
          i18nBook.remedical.summary.t,
          style: _textStyle,
        ),
      ),
      FContainer(
        margin: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
        child: FTextField(
          scrollController: _summaryScrollerController,
          controller: _summaryController,
          maxLines: 3,
          style: _textStyle,
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderSide: BorderSide(
                color: Colors.black,
              ),
            ),
          ),
          onChanged: (v) {},
        ),
      ),
    ];
  }

  ///词条选择
  Iterable<FWidget> _buildEntryTree() {
    return [
      FExpanded(
        child: FTreeView(
          controller: treeController,
          onNodeTap: (v) {
            final result = onNodeTap(v);
            if (result) {
              setState(() {});
            }
          },
          onExpansionChanged: (String v, bool expanded) {
            setState(() {
              onExpansionChanged(v, expanded);
            });
          },
        ),
      ),
    ];
  }

  bool onNodeTap(String v) {
    final entryInfo = _defaultThesaurusList
        .firstWhere((element) => element.parentItemCode == v);

    if (widget.isUserCenter) {
      Get.to(() => EntrySelectedItem(entryInfo));
    } else {
      if (_desController.text.isNotEmpty) {
        _desController.text += '\n';
      }
      if (_summaryController.text.isNotEmpty) {
        _summaryController.text += '\n';
      }
      _desController.text += entryInfo.thesaurusItemDescription ?? '';
      _summaryController.text += entryInfo.thesaurusItemConclusion ?? '';
      // 下一帧执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    }
    return true;
  }

  void _scrollToBottom() {
    _desScrollerController.animateTo(
      _desScrollerController.position.maxScrollExtent,
      duration: Duration(milliseconds: 500),
      curve: Curves.ease,
    );
    _summaryScrollerController.animateTo(
      _summaryScrollerController.position.maxScrollExtent,
      duration: Duration(milliseconds: 500),
      curve: Curves.ease,
    );
  }

  ///获取用户默认词条
  List<ThesaurusItemDTO> _getDefaultThesaurus() {
    List<ThesaurusItemDTO> allThesaurusList = [];
    final defaultThesaurusList = jsonDecode(defaultEntrySetting.defaultEntry);
    defaultThesaurusList.forEach(
      (element) {
        allThesaurusList.add(
          ThesaurusItemDTO(
            thesaurusItemCode: element['ThesaurusItemCode'],
            thesaurusItemType: element['ThesaurusItemType'] == 0
                ? ThesaurusItemTypeEnum.Classification
                : ThesaurusItemTypeEnum.Contents,
            thesaurusItemName: element['ThesaurusItemName'],
            thesaurusItemDescription: element['ThesaurusItemDescription'],
            thesaurusItemConclusion: element['ThesaurusItemConclusion'],
            parentItemCode: element['ParentItemCode'],
            hasChildren: element['HasChildren'],
          ),
        );
      },
    );
    return allThesaurusList;
  }

  void _initNodes({String? keyword}) {
    _defaultThesaurusList =
        widget.isUserCenter ? widget.thesaurus : _getDefaultThesaurus();
    _nodes.clear();
    final controller = widget.controller;
    if (keyword != null && keyword.isNotEmpty && controller != null) {
      _defaultThesaurusList = controller.state.selectedThesaurusItems;
    }
    final parents = _defaultThesaurusList
        .where((element) =>
            element.thesaurusItemType == ThesaurusItemTypeEnum.Classification &&
            (element.hasChildren || element.parentItemCode == ''))
        .toList();

    parents.forEach((element) {
      List<Node> secondChildren = [];
      final thesaurusList = _defaultThesaurusList
          .where((e) => e.parentItemCode == element.thesaurusItemCode);
      secondChildren = thesaurusList.map((e) {
        return Node(
          key: e.thesaurusItemCode ?? '',
          label: _getLableNameConditionly(e),
        );
      }).toList();
      final key = element.thesaurusItemCode ?? '';
      final parentNode = Node(
        key: key,
        label: element.thesaurusItemName ?? '',
        children: secondChildren,
      );
      _nodes.add(parentNode);
    });
    treeController = TreeViewController(children: _nodes);
  }

  @override
  void dispose() {
    final controller = widget.controller;
    if (controller != null) {
      controller.state.selectedThesaurusItems = [];
      controller.state.keyWord = '';
      controller.serachInput.text = '';
    }
    super.dispose();
  }

  ///点击辩题目录和二级目录触发
  void onExpansionChanged(String v, bool expanded) {
    final selectedNode = _nodes.firstWhereOrNull((element) => element.key == v);
    if (selectedNode != null) {
      final index = _nodes.indexOf(selectedNode);
      _nodes[index] = Node(
        key: v,
        parent: selectedNode.parent,
        label: selectedNode.label,
        expanded: expanded,
        children: selectedNode.children,
      );
    } else {
      _nodes.forEach((node) {
        node.children.forEach((element) {
          if (element.key == v) {
            final selectedIndex = node.children.indexOf(element);
            node.children[selectedIndex] = Node(
              key: v,
              label: element.label,
              expanded: expanded,
              children: element.children,
              parent: element.parent,
            );
          }
        });
      });
    }
  }

  String _getLableNameConditionly(ThesaurusItemDTO e) {
    if (e.thesaurusItemName == null || e.thesaurusItemName!.isEmpty) {
      return "${i18nBook.remedical.description.t}\r\n${e.thesaurusItemDescription ?? ''}\r\n${i18nBook.remedical.summary.t}\r\n${e.thesaurusItemConclusion ?? ''}";
    }
    return e.thesaurusItemName ?? '';
  }
}
