import 'dart:convert';

import 'package:fis_jsonrpc/rpc.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:fis_ui/base_define/page.dart';

import 'package:flyinsono/architecture/services/entity/default_entry_setting.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_public_widgets/wx_scaffold.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:get/get.dart' hide Node;
import 'entry_selection_dialog.dart';

// 页面选择后的返回值
class EntrySelectResult {
  // 描述
  final String description;
  // 结论
  final String conclusion;

  EntrySelectResult({
    required this.description,
    required this.conclusion,
  });
}

class ReportEntryelectionPage extends StatefulWidget implements FPage {
  ReportEntryelectionPage({
    this.descriptionInitValue = '',
    this.conclusionInitValue = '',
  });
  // 描述初始值
  final String descriptionInitValue;
  // 结论初始值
  final String conclusionInitValue;

  @override
  _ReportEntryelectionPageState createState() =>
      _ReportEntryelectionPageState();

  @override
  String get pageName => "ReportEntryelectionPage";
}

class _ReportEntryelectionPageState extends State<ReportEntryelectionPage> {
  // ThesaurusTemplateInfoDTO _thesaurusInfo = ThesaurusTemplateInfoDTO();
  List<Node<dynamic>> _nodes = [];
  Map<String, List<ThesaurusItemDTO>> _thesaurusMap = {};
  final TextEditingController _desController = TextEditingController();
  final TextEditingController _conController = TextEditingController();
  final ScrollController _desScrollerController = ScrollController();
  final ScrollController _conScrollerController = ScrollController();
  final TextStyle _textStyle = TextStyle(fontSize: 16);

  @override
  void initState() {
    _desController.text = widget.descriptionInitValue;
    _conController.text = widget.conclusionInitValue;
    List<ThesaurusItemDTO> allEntrys = _initThesaurusInfo();
    List<Map<String, dynamic>> allEntrysMap = _generateNodesMap(allEntrys);
    _thesaurusMap = _generateThesaurusMap(allEntrys);
    _nodes = allEntrysMap.map((e) => Node.fromMap(e)).toList();
    print("_nodes: $_nodes");
    print("_thesaurusMap: $_thesaurusMap");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FScaffold(
      appBar: 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: () {
              _onBackWithParam();
            },
            child: FText(i18nBook.common.confirm.t),
          )
        ],
      ),
      body: _buildEntrySelectionContentView(),
      backgroundColor: Colors.grey[200],
    );
  }

  FWidget _buildSummaryAndDes() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        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: _conScrollerController,
            controller: _conController,
            maxLines: 3,
            style: _textStyle,
            decoration: InputDecoration(
              border: OutlineInputBorder(
                borderSide: BorderSide(
                  color: Colors.black,
                ),
              ),
            ),
            onChanged: (v) {},
          ),
        ),
      ],
    );
  }

  FWidget _buildEntrySelectionContentView() {
    return FGestureDetector(
      businessParent: widget,
      name: "entry_selection_content_view",
      onTap: () {
        print("request unfocus");
        if (FocusManager.instance.primaryFocus != null) {
          FocusManager.instance.primaryFocus!.unfocus();
        }
      },
      behavior: HitTestBehavior.translucent,
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FSizedBox(height: 10),
          _buildSummaryAndDes(),
          FSizedBox(height: 5),
          FDivider(
            thickness: 1,
            height: 1,
            color: Colors.grey[400],
          ),
          FExpanded(child: _buildEntryList())
        ],
      ),
    );
  }

  // 构建词条列表
  FWidget _buildEntryList() {
    if (_nodes.isEmpty) {
      return FContainer();
    }
    return FTreeView(
      theme: FTreeViewTheme(
        expanderTheme: ExpanderThemeData(
          animated: true,
        ),
        expandSpeed: Duration(milliseconds: 100),
        levelPadding: 0,
        verticalSpacing: 0,
      ),
      onNodeTap: _onEntryTap,
      controller: TreeViewController(
        children: _nodes,
      ),
      nodeBuilder: (context, node) {
        return InkWell(
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    node.label,
                    style: TextStyle(
                      fontSize: 16,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 点击词条
  void _onEntryTap(String key) async {
    List<ThesaurusItemDTO> itmes = getItemsByThesaurusKey(key);
    EntrySelectResult? result =
        await Get.dialog<EntrySelectResult>(EntrySelectionDialog(
      items: itmes,
    ));

    if (result != null) {
      if (_desController.text.isNotEmpty) {
        _desController.text += '\n';
      }
      if (_conController.text.isNotEmpty) {
        _conController.text += '\n';
      }
      _desController.text += result.description;
      _conController.text += result.conclusion;
      // 文本框失焦
      FocusScope.of(context).requestFocus(FocusNode());
      // 下一帧执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    } else {
      print("get null result");
    }
  }

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

  /// 带参数返回
  void _onBackWithParam() async {
    EntrySelectResult result = EntrySelectResult(
      description: _desController.text,
      conclusion: _conController.text,
    );
    Get.back(result: result);
  }

  /// 通过树形图中选项的key值获取词条数据
  List<ThesaurusItemDTO> getItemsByThesaurusKey(String key) {
    List<ThesaurusItemDTO>? items = _thesaurusMap[key];
    return items ?? [];
  }

  ///获取用户默认词条
  List<ThesaurusItemDTO> _initThesaurusInfo() {
    List<ThesaurusItemDTO> allThesaurusList = [];
    DefaultEntrySetting defaultEntrySetting = DefaultEntrySetting.ins;
    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;
  }

  /// 平铺结构的 List<ThesaurusItemDTO> 转为树形结构的 Map<String, dynamic>
  List<Map<String, dynamic>> _generateNodesMap(List<ThesaurusItemDTO> items) {
    // 创建一个映射，用于保存所有节点
    List<Map<String, dynamic>> nodesMap = [];
    Map<String, List<Map<String, dynamic>>> childrenNodesMap = {}; // 叶子节点
    // 遍历所有项目，取出所有叶子节点，归类为一个 Map
    for (ThesaurusItemDTO item in items) {
      if (item.thesaurusItemName == null || item.thesaurusItemName!.isEmpty) {
        continue;
      }
      if (item.hasChildren) {
        continue;
      }
      Map<String, dynamic> node = {
        'key': item.thesaurusItemCode,
        'label': item.thesaurusItemName,
        'data': item,
      };
      if (childrenNodesMap.containsKey(item.parentItemCode)) {
        childrenNodesMap[item.parentItemCode]!.add(node);
      } else {
        childrenNodesMap[item.parentItemCode!] = [node];
      }
      // nodesMap.add(node);
    }

    /// 将叶子节点添加至父节点
    for (ThesaurusItemDTO item in items) {
      if (item.thesaurusItemName == null || item.thesaurusItemName!.isEmpty) {
        continue;
      }
      if (!item.hasChildren) {
        continue;
      }
      Map<String, dynamic> node = {
        'key': item.thesaurusItemCode,
        'label': item.thesaurusItemName,
        'data': item,
      };
      if (childrenNodesMap.containsKey(item.thesaurusItemCode)) {
        node['children'] = childrenNodesMap[item.thesaurusItemCode];
      }
      nodesMap.add(node);
    }
    if (childrenNodesMap.containsKey("") && childrenNodesMap[""]!.isNotEmpty) {
      nodesMap.addAll(childrenNodesMap[""]!);
    }
    return nodesMap;
  }

  /// 生成词条 Map
  Map<String, List<ThesaurusItemDTO>> _generateThesaurusMap(
      List<ThesaurusItemDTO> items) {
    Map<String, List<ThesaurusItemDTO>> nodesMap = {}; // 父节点
    // 遍历所有项目，取出所有叶子节点，归类为一个 Map
    for (ThesaurusItemDTO item in items) {
      if (item.thesaurusItemName != null &&
          item.thesaurusItemName!.isNotEmpty) {
        continue;
      }
      if (nodesMap.containsKey(item.parentItemCode)) {
        nodesMap[item.parentItemCode]!.add(item);
      } else {
        nodesMap[item.parentItemCode!] = [item];
      }
    }
    return nodesMap;
  }

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