import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/apis/api.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/models/dept.model.dart';
import 'package:sk_base_mobile/util/logger_util.dart';
import 'package:sk_base_mobile/util/screen_adaper_util.dart';
import 'package:sk_base_mobile/widgets/core/sk_cascade_picker.dart';

class DeptPicker extends StatelessWidget {
  final Function(CascadeItem<int, DeptModel>)? onSelected;
  DeptPicker({super.key, this.onSelected});
  @override
  Widget build(BuildContext context) {
    return SkCascadePicker<int, DeptModel>(
      getData: getData,
      initialPageData: (cascadeController) =>
          cascadeController.treeData.toList(),
      nextPageData: (pageCallback, currentPage, selectIndex, currentPageItem,
          cascadeController) async {
        if (currentPageItem.children != null) {
          List<CascadeItem<int, DeptModel>>? nextPageData = currentPageItem
              .children!
              .map<CascadeItem<int, DeptModel>>((e) =>
                  CascadeItem(label: e.name, value: e.id, children: e.children))
              .toList();
          if (nextPageData.isNotEmpty) pageCallback(nextPageData);
        }
      },
      onConfirm: (List<CascadeItem<int, DeptModel>> value) {
        if (onSelected != null && value.isNotEmpty) {
          onSelected!(value.last);
        }
      },
      maxPageNum: 10,
      selectedIcon: const Icon(Icons.check, color: AppTheme.primaryColorLight),
    );
  }

  Future<List<CascadeItem<int, DeptModel>>> getData() async {
    try {
      final res = await Api.getDepts();
      if (res.data != null) {
        List<CascadeItem<int, DeptModel>> result =
            res.data.map<CascadeItem<int, DeptModel>>((e) {
          DeptModel data = DeptModel.fromJson(e);
          return CascadeItem(
              label: data.name, value: data.id, children: data.children);
        }).toList();
        return result;
      }
      return [];
    } catch (e) {
      LoggerUtil().error(e);
      return [];
    }
  }
}
