import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/search_bar_widget.dart';
import 'package:qhd_prevention/pages/http/ApiService.dart';
import 'package:qhd_prevention/tools/tools.dart';


// 数据模型
class Category {
  final String id;
  final String name;
  final List<Category> children;

  Category({required this.id, required this.name, this.children = const []});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['id'] as String,
      name: json['name'] as String,
      children:
          (json['nodes'] as List<dynamic>)
              .map((e) => Category.fromJson(e as Map<String, dynamic>))
              .toList(),
    );
  }
}

/// 弹窗回调签名：返回完整的多级路径 JSON 对象
typedef DeptSelectHiddenTypeCallback =
    void Function(Map<String, List<String>> result);

class DepartmentPickerHiddenType extends StatefulWidget {
  final DeptSelectHiddenTypeCallback onSelected;

  const DepartmentPickerHiddenType({Key? key, required this.onSelected})
    : super(key: key);

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

class _DepartmentPickerHiddenTypeState
    extends State<DepartmentPickerHiddenType> {
  String selectedId = '';
  String selectedName = '';
  Set<String> expandedSet = {};
  List<Category> original = [];
  List<Category> filtered = [];
  bool loading = true;
  final TextEditingController _searchController = TextEditingController();
  final Map<String, Category?> parentMap = {};

  @override
  void initState() {
    super.initState();
    _searchController.addListener(_onSearchChanged);
    _loadData();
  }

  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    try {
      List<dynamic> raw;
      // 从 SessionService 读取或通过 API 拉取
      if (SessionService.instance.departmentHiddenTypeJsonStr?.isNotEmpty ??
          false) {
        raw =
            json.decode(SessionService.instance.departmentHiddenTypeJsonStr!)
                as List;
      } else {
        // ... 同前逻辑，获取 parentId 并调用 API
        final resultLevel = await ApiService.getHiddenLevelsListTwo();
        List<dynamic> levelList = resultLevel['list'] as List;
        String parentId = '';
        for (var item in levelList) {
          if ((item['BIANMA'] as String).contains(
            SessionService.instance.loginUser?["PROVINCE"] ?? '',
          )) {
            parentId = item['DICTIONARIES_ID'];
            break;
          }
        }
        final result = await ApiService.getHiddenTypeList(parentId);
        final nodes = result['zTreeNodes'] as String;
        SessionService.instance.departmentHiddenTypeJsonStr = nodes;
        raw = json.decode(nodes) as List;
      }

      // 构建 Category 列表并生成 parentMap
      final list =
          raw.map((e) => Category.fromJson(e as Map<String, dynamic>)).toList();
      _buildParentMap(list);

      setState(() {
        original = list;
        filtered = list;
        loading = false;
      });
    } catch (_) {
      setState(() => loading = false);
    }
  }

  void _buildParentMap(List<Category> list, [Category? parent]) {
    for (var cat in list) {
      parentMap[cat.id] = parent;
      if (cat.children.isNotEmpty) {
        _buildParentMap(cat.children, cat);
      }
    }
  }

  void _onSearchChanged() {
    final q = _searchController.text.toLowerCase().trim();
    setState(() {
      filtered = q.isEmpty ? original : _filterCategories(original, q);
    });
  }

  List<Category> _filterCategories(List<Category> list, String q) {
    final res = <Category>[];
    for (var cat in list) {
      final children = _filterCategories(cat.children, q);
      if (cat.name.toLowerCase().contains(q) || children.isNotEmpty) {
        res.add(Category(id: cat.id, name: cat.name, children: children));
      }
    }
    return res;
  }

  Category? _findById(String id) {
    Category? found;
    void dfs(List<Category> list) {
      for (var c in list) {
        if (c.id == id) {
          found = c;
          return;
        }
        dfs(c.children);
        if (found != null) return;
      }
    }

    dfs(original);
    return found;
  }

  /// 构建从根到选中节点的路径列表
  List<Category> _buildPath(String id) {
    final path = <Category>[];
    var cur = _findById(id);
    while (cur != null) {
      path.insert(0, cur);
      cur = parentMap[cur.id];
    }
    return path;
  }

  Widget _buildRow(Category cat, int indent) {
    final hasChildren = cat.children.isNotEmpty;
    final expanded = expandedSet.contains(cat.id);
    final selected = cat.id == selectedId;
    return Column(
      children: [
        InkWell(
          onTap: () {
            setState(() {
              if (hasChildren) {
                expanded ? expandedSet.remove(cat.id) : expandedSet.add(cat.id);
              }
              selectedId = cat.id;
            });
          },
          child: Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 12),
            child: Row(
              children: [
                SizedBox(width: 16.0 * indent),
                if (hasChildren)
                  Icon(
                    expanded
                        ? Icons.arrow_drop_down_rounded
                        : Icons.arrow_right_rounded,
                    size: 24,
                    color: Colors.grey[600],
                  )
                else
                  const SizedBox(width: 24),
                const SizedBox(width: 8),
                Expanded(child: Text(cat.name)),
                Icon(
                  selected
                      ? Icons.radio_button_checked
                      : Icons.radio_button_unchecked,
                  color: Colors.green,
                ),
                const SizedBox(width: 16),
              ],
            ),
          ),
        ),
        if (hasChildren && expanded)
          ...cat.children.map((c) => _buildRow(c, indent + 1)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: MediaQuery.of(context).size.height * 0.7,
      color: Colors.white,
      child: Column(
        children: [
          // 顶部操作栏
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: const Text('取消'),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: SearchBarWidget(
                    controller: _searchController,
                    isShowSearchButton: false,
                    onSearch: (_) {},
                  ),
                ),
                const SizedBox(width: 16),
                GestureDetector(
                  onTap: () {
                    final pathCats = _buildPath(selectedId);
                    final ids = pathCats.map((e) => e.id).toList();
                    final names = pathCats.map((e) => e.name).toList();
                    widget.onSelected({'id': ids, 'name': names});
                    Navigator.of(context).pop();
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.green),
                  ),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          // 列表区
          Expanded(
            child:
                loading
                    ? const Center(child: CircularProgressIndicator())
                    : ListView.builder(
                      itemCount: filtered.length,
                      itemBuilder: (_, idx) => _buildRow(filtered[idx], 0),
                    ),
          ),
        ],
      ),
    );
  }
}
