import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_treeview/flutter_treeview.dart';
import 'package:get/route_manager.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/city_address_bo.dart';
import 'package:special_equipment_flutter/utils/tree_data_util.dart';
import 'package:special_equipment_flutter/widgets/app_bar/custom_app_bar.dart';

class AddressPage extends StatefulWidget {
  const AddressPage({super.key});

  @override
  State<AddressPage> createState() => _AddressPageState();
}

class _AddressPageState extends State<AddressPage> {
  final String _selectedNode = "";
  List<Node<dynamic>> nodes = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  getData() async {
    HttpUtils.getTreeData(context).then((value) {
      if (value != null) {
        List<CityAddressBo> cityAddressBo = value;
        setState(() {
          nodes = TreeDataUtil.loadNodes(cityAddressBo);
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarCustom(
        text: '归属区域',
        height: 50,
      ),
      body: TreeView(
        onNodeTap: (String value) {
          var address = '';
          for (var item in nodes) {
            var areaChildren = item.children;
            for (var areaItem in areaChildren) {
              var key = areaItem.key;
              var id = key.split('-*-')[1];
              var split = value.toString().split('-*-');
              var parentId = split[0];
              var name = split[2];
              if (id == parentId) {
                for (var item in nodes) {
                  var cityKey = item.key;
                  var cityId = cityKey.split('-*-')[1];
                  var key = areaItem.key;
                  var id = key.split('-*-')[0];
                  if (cityId == id) {
                    address = item.label + areaItem.label + name;
                    break;
                  }
                }
              }
            }
          }
          var split = value.toString().split('-*-');
          var id = split[1];
          Map result = {};
          result['id'] = id;
          result['address'] = address;
          Get.back(result: result);
        },
        controller:
            TreeViewController(children: nodes, selectedKey: _selectedNode),
      ),
    );
  }
}
